From 45847f13106b8c683cae3a13622b4c56df82cfdc Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Wed, 21 Aug 2024 10:19:50 +0300 Subject: [PATCH 01/70] start on graph pipenet port :) (very much WIP, doesn't launch at all, etc.) --- dependencies.gradle | 4 + .../api/blockentity/IDirtyNotifiable.java | 6 + .../blockentity/IHasWorldObjectAndCoords.java | 37 + .../gtceu/api/blockentity/INeighborCache.java | 33 + .../blockentity/NeighborCacheBlockEntity.java | 90 ++ .../gtceu/api/graphnet/AbstractGroupData.java | 20 + .../gtceu/api/graphnet/GraphNetBacker.java | 280 +++++++ .../gtceu/api/graphnet/IGraphNet.java | 213 +++++ .../gtceu/api/graphnet/MultiNodeHelper.java | 138 ++++ .../gtceu/api/graphnet/NetGroup.java | 190 +++++ .../gtceu/api/graphnet/NetNode.java | 156 ++++ .../api/graphnet/alg/AlgorithmBuilder.java | 12 + .../DynamicWeightsShortestPathsAlgorithm.java | 97 +++ .../gtceu/api/graphnet/alg/INetAlgorithm.java | 11 + .../api/graphnet/alg/NetAlgorithmWrapper.java | 45 + .../gtceu/api/graphnet/alg/NetPathMapper.java | 39 + .../graphnet/alg/ShortestPathsAlgorithm.java | 64 ++ .../api/graphnet/alg/SinglePathAlgorithm.java | 89 ++ .../graphnet/alg/iter/IteratorFactory.java | 29 + .../alg/iter/SimpleIteratorFactories.java | 43 + .../graphnet/edge/AbstractNetFlowEdge.java | 109 +++ .../gtceu/api/graphnet/edge/NetEdge.java | 92 +++ .../gtceu/api/graphnet/edge/NetFlowEdge.java | 159 ++++ .../api/graphnet/edge/NetFlowSharedEdge.java | 169 ++++ .../gtceu/api/graphnet/edge/SimulatorKey.java | 25 + .../gtceu/api/graphnet/graph/GraphEdge.java | 56 ++ .../gtceu/api/graphnet/graph/GraphVertex.java | 34 + .../gtceu/api/graphnet/graph/INetGraph.java | 21 + .../api/graphnet/graph/NetDirectedGraph.java | 62 ++ .../graphnet/graph/NetUndirectedGraph.java | 62 ++ .../logic/AbstractDoubleLogicData.java | 49 ++ .../graphnet/logic/AbstractIntLogicData.java | 48 ++ .../graphnet/logic/AbstractLongLogicData.java | 50 ++ .../api/graphnet/logic/ChannelCountLogic.java | 24 + .../logic/INetLogicEntryListener.java | 6 + .../graphnet/logic/MultiNetCountLogic.java | 24 + .../api/graphnet/logic/NetLogicData.java | 240 ++++++ .../api/graphnet/logic/NetLogicEntry.java | 127 +++ .../api/graphnet/logic/NetLogicRegistry.java | 36 + .../api/graphnet/logic/ThroughputLogic.java | 24 + .../api/graphnet/logic/WeightFactorLogic.java | 24 + .../api/graphnet/path/AbstractNetPath.java | 90 ++ .../graphnet/path/GenericGraphNetPath.java | 44 + .../gtceu/api/graphnet/path/INetPath.java | 41 + .../pipenet/BasicWorldPipeNetPath.java | 44 + .../pipenet/FlowWorldPipeNetPath.java | 44 + .../graphnet/pipenet/IPipeNetNodeHandler.java | 28 + .../api/graphnet/pipenet/NodeLossCache.java | 74 ++ .../api/graphnet/pipenet/NodeLossResult.java | 53 ++ .../api/graphnet/pipenet/WorldPipeNet.java | 219 +++++ .../graphnet/pipenet/WorldPipeNetNode.java | 84 ++ .../logic/EdgeCoverReferenceLogic.java | 146 ++++ .../pipenet/logic/EnumLossFunction.java | 111 +++ .../pipenet/logic/TemperatureLogic.java | 328 ++++++++ .../logic/TemperatureLossFunction.java | 89 ++ .../graphnet/pipenet/physical/IBurnable.java | 23 + .../graphnet/pipenet/physical/IFreezable.java | 17 + .../pipenet/physical/IInsulatable.java | 6 + .../physical/IPipeCapabilityObject.java | 17 + .../physical/IPipeChanneledStructure.java | 6 + .../physical/IPipeMaterialStructure.java | 8 + .../pipenet/physical/IPipeStructure.java | 63 ++ .../physical/PipeStructureRegistry.java | 35 + .../physical/block/ItemMaterialPipeBlock.java | 32 + .../pipenet/physical/block/ItemPipeBlock.java | 51 ++ .../physical/block/PipeActivableBlock.java | 50 ++ .../pipenet/physical/block/PipeBlock.java | 767 ++++++++++++++++++ .../physical/block/PipeMaterialBlock.java | 140 ++++ .../pipenet/physical/block/RayTraceAABB.java | 35 + .../pipenet/physical/tile/IActivable.java | 8 + .../physical/tile/IWorldPipeNetTile.java | 44 + .../tile/PipeActivableBlockEntity.java | 62 ++ .../physical/tile/PipeBlockEntity.java | 696 ++++++++++++++++ .../physical/tile/PipeCapabilityWrapper.java | 51 ++ .../physical/tile/PipeCoverHolder.java | 300 +++++++ .../physical/tile/PipeMaterialTileEntity.java | 79 ++ .../pipenet/predicate/BlockedPredicate.java | 51 ++ .../pipenet/predicate/FilterPredicate.java | 101 +++ .../pipenet/transfer/TransferControl.java | 28 + .../transfer/TransferControlProvider.java | 8 + .../traverse/AbstractTileRoundRobinData.java | 73 ++ .../traverse/SimpleTileRoundRobinData.java | 41 + .../api/graphnet/predicate/EdgePredicate.java | 62 ++ .../predicate/EdgePredicateHandler.java | 117 +++ .../predicate/NetPredicateRegistry.java | 36 + .../predicate/test/FluidTestObject.java | 55 ++ .../predicate/test/IPredicateTestObject.java | 13 + .../predicate/test/ItemTestObject.java | 69 ++ .../api/graphnet/servernet/ServerNet.java | 126 +++ .../api/graphnet/servernet/ServerNetNode.java | 37 + .../traverse/AbstractTraverseData.java | 45 + .../graphnet/traverse/DistributorHelper.java | 24 + .../traverse/IEqualizableTraverseData.java | 23 + .../graphnet/traverse/IRoundRobinData.java | 32 + .../traverse/IRoundRobinTraverseData.java | 52 ++ .../api/graphnet/traverse/ITraverseData.java | 78 ++ .../traverse/ITraverseGuideProvider.java | 15 + .../traverse/TraverseDataProvider.java | 15 + .../api/graphnet/traverse/TraverseGuide.java | 46 ++ .../graphnet/traverse/TraverseHelpers.java | 484 +++++++++++ .../traverse/util/CompleteLossOperator.java | 18 + .../traverse/util/CompositeLossOperator.java | 22 + .../traverse/util/FlatLossOperator.java | 21 + .../traverse/util/FlowConsumptionStack.java | 49 ++ .../traverse/util/MultLossOperator.java | 34 + .../traverse/util/ReversibleLossOperator.java | 21 + .../gtceu/api/graphnet/worldnet/WorldNet.java | 152 ++++ .../api/graphnet/worldnet/WorldNetNode.java | 45 + .../gtceu/common/block/CableBlock.java | 2 +- .../gtceu/utils/EntityDamageUtil.java | 4 +- 110 files changed, 8918 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/blockentity/IDirtyNotifiable.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/blockentity/IHasWorldObjectAndCoords.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/AbstractGroupData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/AlgorithmBuilder.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/INetAlgorithm.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetAlgorithmWrapper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/IteratorFactory.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/SimpleIteratorFactories.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetEdge.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowEdge.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/SimulatorKey.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphEdge.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphVertex.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/INetGraph.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetDirectedGraph.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetUndirectedGraph.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/INetLogicEntryListener.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/path/AbstractNetPath.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossResult.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EnumLossFunction.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IInsulatable.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeChanneledStructure.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IActivable.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCapabilityWrapper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControlProvider.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/IPredicateTestObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/DistributorHelper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseGuideProvider.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseGuide.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompleteLossOperator.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompositeLossOperator.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlatLossOperator.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlowConsumptionStack.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/MultLossOperator.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/ReversibleLossOperator.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNetNode.java diff --git a/dependencies.gradle b/dependencies.gradle index 449dd14302..0904d237c7 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,6 +1,10 @@ dependencies { compileOnly 'org.jetbrains:annotations:24.1.0' + // Shadowed Dependencies + // Packages that aren't mods, and thus need to be included in the release files. + shadow(implementation('org.jgrapht:jgrapht-core:1.5.2')) // JGraphT 1.4.0 + // LDLib modApi(forge.ldlib.forge) { transitive = false } jarJar(forge.ldlib.forge) diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/IDirtyNotifiable.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/IDirtyNotifiable.java new file mode 100644 index 0000000000..56848697c1 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/IDirtyNotifiable.java @@ -0,0 +1,6 @@ +package com.gregtechceu.gtceu.api.blockentity; + +public interface IDirtyNotifiable { + + void markAsDirty(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/IHasWorldObjectAndCoords.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/IHasWorldObjectAndCoords.java new file mode 100644 index 0000000000..33b93e48ea --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/IHasWorldObjectAndCoords.java @@ -0,0 +1,37 @@ +package com.gregtechceu.gtceu.api.blockentity; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; + +public interface IHasWorldObjectAndCoords extends IDirtyNotifiable { + + Level getLevel(); + + BlockPos getBlockPos(); + + default boolean isServerSide() { + return getLevel() != null && !getLevel().isClientSide; + } + + default boolean isClientSide() { + return getLevel() != null && getLevel().isClientSide; + } + + default void notifyBlockUpdate() { + if (getLevel() != null) { + getLevel().updateNeighborsAt(getBlockPos(), getLevel().getBlockState(getBlockPos()).getBlock()); + } + } + + default void scheduleRenderUpdate() { + var pos = getBlockPos(); + if (getLevel() != null) { + var state = getLevel().getBlockState(pos); + if (getLevel().isClientSide) { + getLevel().sendBlockUpdated(pos, state, state, 1 << 3); + } else { + getLevel().blockEvent(pos, state.getBlock(), 1, 0); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java new file mode 100644 index 0000000000..e070d27a7a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java @@ -0,0 +1,33 @@ +package com.gregtechceu.gtceu.api.blockentity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * An interface defining access to cached neighboring tile entities to a block or tile entity + */ +public interface INeighborCache extends IHasWorldObjectAndCoords { + + /** + * @param facing the side at which the neighbor is located + * @return the neighboring tile entity at the side + */ + default @Nullable BlockEntity getNeighbor(@NotNull Direction facing) { + return getLevel().getBlockEntity(getBlockPos().relative(facing)); + } + + default @Nullable BlockEntity getNeighborNoChunkloading(@NotNull Direction facing) { + BlockPos pos = getBlockPos().relative(facing); + return getLevel().isLoaded(pos) ? getLevel().getBlockEntity(pos) : null; + } + + /** + * Called when an adjacent neighboring block has changed at a side in some way + * + * @param facing the side at which the neighbor has changed + */ + void onNeighborChanged(@NotNull Direction facing); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java new file mode 100644 index 0000000000..e2f3fa2d98 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java @@ -0,0 +1,90 @@ +package com.gregtechceu.gtceu.api.blockentity; + +import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; +import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; +import com.lowdragmc.lowdraglib.syncdata.blockentity.IRPCBlockEntity; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; + +public abstract class NeighborCacheBlockEntity extends BlockEntity implements INeighborCache, + IAsyncAutoSyncBlockEntity, IRPCBlockEntity, IAutoPersistBlockEntity { + + private final BlockEntity[] neighbors = new BlockEntity[6]; + private boolean neighborsInvalidated = false; + /** + * @param doInvalidationHere set to false if you override {@link NeighborCacheBlockEntity#invalidateNeighbors()} + * with a method that references something you do not yet have set. + */ + public NeighborCacheBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState, boolean doInvalidationHere) { + super(type, pos, blockState); + if (doInvalidationHere) invalidateNeighbors(); + } + + protected void invalidateNeighbors() { + if (!this.neighborsInvalidated) { + Arrays.fill(this.neighbors, this); + this.neighborsInvalidated = true; + } + } + + @MustBeInvokedByOverriders + @Override + public void setLevel(@NotNull Level LevelIn) { + super.setLevel(LevelIn); + invalidateNeighbors(); + } + + @Override + public void setRemoved() { + super.setRemoved(); + invalidateNeighbors(); + } + + @Override + public void onChunkUnloaded() { + super.onChunkUnloaded(); + invalidateNeighbors(); + } + + @Override + public @Nullable BlockEntity getNeighbor(@NotNull Direction facing) { + if (level == null || this.getBlockPos() == null) return null; + int i = facing.get3DDataValue(); + BlockEntity neighbor = this.neighbors[i]; + if (neighbor == this || (neighbor != null && neighbor.isRemoved())) { + neighbor = level.getBlockEntity(worldPosition.relative(facing)); + this.neighbors[i] = neighbor; + this.neighborsInvalidated = false; + } + return neighbor; + } + + @Override + public @Nullable BlockEntity getNeighborNoChunkloading(@NotNull Direction facing) { + if (level == null || this.getBlockPos() == null) return null; + int i = facing.get3DDataValue(); + BlockEntity neighbor = this.neighbors[i]; + if (neighbor == this || (neighbor != null && neighbor.isRemoved())) { + BlockPos pos = getBlockPos().relative(facing); + if (level.isLoaded(pos)) { + neighbor = level.getBlockEntity(pos); + this.neighbors[i] = neighbor; + this.neighborsInvalidated = false; + } else return null; + } + return neighbor; + } + + public void onNeighborChanged(@NotNull Direction facing) { + this.neighbors[facing.get3DDataValue()] = this; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/AbstractGroupData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/AbstractGroupData.java new file mode 100644 index 0000000000..a2ae810a13 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/AbstractGroupData.java @@ -0,0 +1,20 @@ +package com.gregtechceu.gtceu.api.graphnet; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public abstract class AbstractGroupData { + + protected NetGroup group; + + public void withGroup(NetGroup group) { + this.group = group; + } + + public abstract boolean mergeAllowed(@NotNull AbstractGroupData other); + + @Nullable + public AbstractGroupData merge(@NotNull AbstractGroupData other) { + return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java new file mode 100644 index 0000000000..2c96f7697a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java @@ -0,0 +1,280 @@ +package com.gregtechceu.gtceu.api.graphnet; + +import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; +import com.gregtechceu.gtceu.api.graphnet.alg.NetAlgorithmWrapper; +import com.gregtechceu.gtceu.api.graphnet.alg.NetPathMapper; +import com.gregtechceu.gtceu.api.graphnet.alg.iter.IteratorFactory; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NBTTagList; + +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.Iterator; + +/** + * The bridge between JGraphT graphs and graphnet abstractions. + * Doesn't do any automatic linking, weighting, predicating, etc. Simply handles storing the JGraphT graph to disk, + * interfacing with graph algorithms, and interacting with the JGraphT graph. + */ +public final class GraphNetBacker { + + private final IGraphNet backedNet; + private final INetGraph pipeGraph; + private final Object2ObjectOpenHashMap vertexMap; + private final NetAlgorithmWrapper[] netAlgorithms; + + public GraphNetBacker(IGraphNet backedNet, INetGraph graph, + AlgorithmBuilder @NotNull... algorithmBuilders) { + this.backedNet = backedNet; + this.pipeGraph = graph; + this.netAlgorithms = new NetAlgorithmWrapper[algorithmBuilders.length]; + for (int i = 0; i < algorithmBuilders.length; i++) { + this.netAlgorithms[i] = new NetAlgorithmWrapper(backedNet, algorithmBuilders[i], + backedNet.supportsPredication() || backedNet.usesDynamicWeights(i)); + } + this.vertexMap = new Object2ObjectOpenHashMap<>(); + } + + public IGraphNet getBackedNet() { + return backedNet; + } + + public void addNode(NetNode node) { + GraphVertex vertex = new GraphVertex(node); + getGraph().addVertex(vertex); + this.vertexMap.put(node.getEquivalencyData(), vertex); + backedNet.markDirty(); + } + + @Nullable + public NetNode getNode(Object equivalencyData) { + GraphVertex vertex = this.vertexMap.get(equivalencyData); + return vertex == null ? null : vertex.wrapped; + } + + public boolean removeNode(@Nullable NetNode node) { + if (node != null) { + if (!this.getGraph().containsVertex(node.wrapper)) { + // edge case -- the node's group most likely still has this node registered, + // but the node doesn't actually exist in the graph. + // no idea what causes this, but it happens. + NetGroup group = node.getGroupUnsafe(); + if (group != null) group.removeNode(node); + } + if (!this.getGraph().edgesOf(node.wrapper).isEmpty()) this.invalidateAlgs(); + NetGroup group = node.getGroupUnsafe(); + if (group != null) { + group.splitNode(node); + } else this.removeVertex(node.wrapper); + backedNet.markDirty(); + return true; + } else return false; + } + + @ApiStatus.Internal + public void removeVertex(GraphVertex vertex) { + if (this.getGraph().removeVertex(vertex)) { + this.vertexMap.remove(vertex.wrapped.getEquivalencyData()); + vertex.wrapped.onRemove(); + backedNet.markDirty(); + } + } + + @Nullable + public NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, double weight) { + if (!NetGroup.isEdgeAllowed(source, target)) return null; + GraphEdge graphEdge = getGraph().addEdge(source.wrapper, target.wrapper); + if (graphEdge != null) { + getGraph().setEdgeWeight(graphEdge, weight); + NetGroup.mergeEdge(source, target); + backedNet.markDirty(); + } + return graphEdge == null ? null : graphEdge.wrapped; + } + + @Nullable + public NetEdge getEdge(@NotNull NetNode source, @NotNull NetNode target) { + GraphEdge graphEdge = getGraph().getEdge(source.wrapper, target.wrapper); + return graphEdge == null ? null : graphEdge.wrapped; + } + + public boolean removeEdge(@NotNull NetNode source, NetNode target) { + NetGroup group = source.getGroupUnsafe(); + if (group == null) { + // weird since there should always be a group for two joined nodes, but whatever + return removeEdge(source.wrapper, target.wrapper) != null; + } else return group.splitEdge(source, target); + } + + @ApiStatus.Internal + public GraphEdge removeEdge(GraphVertex source, GraphVertex target) { + GraphEdge edge = this.getGraph().removeEdge(source, target); + if (edge != null) { + backedNet.markDirty(); + } + return edge; + } + + @ApiStatus.Internal + public boolean removeEdge(GraphEdge edge) { + if (this.getGraph().removeEdge(edge)) { + backedNet.markDirty(); + return true; + } + return false; + } + + /** + * Note - if an error is thrown with a stacktrace descending from this method, + * most likely a bad remapper was passed in.
+ * This method should never be exposed outside the net this backer is backing due to this fragility. + */ + public > Iterator getPaths(@Nullable NetNode node, int algorithmID, + @NotNull NetPathMapper remapper, + IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + if (node == null) return Collections.emptyIterator(); + this.getGraph().setupInternal(this, backedNet.usesDynamicWeights(algorithmID)); + + Iterator> cache = node.getPathCache(testObject, simulator, queryTick); + if (cache != null) return (Iterator) cache; + + IteratorFactory factory = this.netAlgorithms[algorithmID] + .getPathsIterator(node.wrapper, remapper, testObject, simulator, queryTick); + if (factory.cacheable()) { + return (Iterator) (node.setPathCache(factory).getPathCache(testObject, simulator, queryTick)); + } else return factory.newIterator(getGraph(), testObject, simulator, queryTick); + } + + public void invalidateAlg(int algorithmID) { + this.netAlgorithms[algorithmID].invalidate(); + } + + public void invalidateAlgs() { + for (NetAlgorithmWrapper netAlgorithm : this.netAlgorithms) { + netAlgorithm.invalidate(); + } + } + + public INetGraph getGraph() { + return pipeGraph; + } + + // PROPOSAL FOR ALTERNATIVE STORAGE MECHANISM TO REDUCE MEMORY COSTS + // > Always loaded & nbt stored data: + // map & weak map of group ids to groups. No references to group objects exist outside of this, only references to + // grou ids. + // (for pipenet) pipes store a reference to their group id + // > Disk-stored data: + // contents of groups, specifically their nodes and edges. + // > Impl (for pipenet) + // When a pipe is loaded, it goes fetch its group and tells it the pipe's chunk. This chunk is added to a *set* of + // chunks that are 'loading' this group. + // When a chunk is unloaded, it is removed from the set of 'loading' chunks for all groups. + // When the set of 'loading' chunks for a group is empty, the group writes its data to disk and removes itself from + // the map and the graph but not the weak map. + // (proposal - create a graph impl that allows for weak references to vertices and edges, in order to remove need + // for explicit removal of group from graph?) + // When a pipe fetches its group, if the group is not found in the map, it then checks the weak map. + // If found in the weak map, the pipe's chunk is added to the 'loading' chunks and a reference to the group is added + // to the map and the contents are added to the graph. + // If not found in the weak map, the group is instead read from disk and initialized. + // > Benefits of this Impl + // By only loading the (potentially) large number of edges and nodes into the graph that a group contains when that + // group is needed, + // the number of unnecessary references in the graphnet on, say, a large server is drastically reduced. + // however, since there are necessarily more read/write actions to disk, the cpu load would increase in turn. + + public void readFromNBT(@NotNull CompoundTag nbt) { + // construct map of node ids -> nodes, while building nodes to groups + // construct edges using map + Int2ObjectOpenHashMap groupMap = new Int2ObjectOpenHashMap<>(); + NBTTagList vertices = nbt.getTagList("Vertices", 10); + int vertexCount = vertices.tagCount(); + Int2ObjectOpenHashMap vertexMap = new Int2ObjectOpenHashMap<>(vertexCount); + for (int i = 0; i < vertexCount; i++) { + CompoundTag tag = vertices.getCompoundTagAt(i); + NetNode node = this.backedNet.getNewNode(); + node.deserializeNBT(tag); + if (tag.hasKey("GroupID")) { + int id = tag.getInteger("GroupID"); + NetGroup group = groupMap.get(id); + if (group == null) { + group = new NetGroup(this.backedNet); + groupMap.put(id, group); + } + group.addNode(node); + } + GraphVertex vertex = new GraphVertex(node); + this.getGraph().addVertex(vertex); + vertexMap.put(i, vertex); + this.vertexMap.put(node.getEquivalencyData(), vertex); + } + + NBTTagList edges = nbt.getTagList("Edges", 10); + int edgeCount = edges.tagCount(); + for (int i = 0; i < edgeCount; i++) { + CompoundTag tag = edges.getCompoundTagAt(i); + GraphEdge graphEdge = this.getGraph().addEdge(vertexMap.get(tag.getInteger("SourceID")), + vertexMap.get(tag.getInteger("TargetID"))); + this.getGraph().setEdgeWeight(graphEdge, tag.getDouble("Weight")); + graphEdge.wrapped.deserializeNBT(tag); + } + } + + @Contract("_ -> param1") + public @NotNull CompoundTag writeToNBT(CompoundTag compound) { + // map of net groups -> autogenerated ids; + // tag of autogenerated vertex ids -> node nbt & group id + // tag of autogenerated edge ids -> edge nbt & source/target ids + Object2IntOpenHashMap groupMap = new Object2IntOpenHashMap<>(); + Object2IntOpenHashMap vertexMap = new Object2IntOpenHashMap<>(); + int i = 0; + int g = 0; + NBTTagList vertices = new NBTTagList(); + for (GraphVertex graphVertex : this.getGraph().vertexSet()) { + vertexMap.put(graphVertex, i); + NetGroup group = graphVertex.wrapped.getGroupUnsafe(); + CompoundTag tag = graphVertex.wrapped.serializeNBT(); + if (group != null) { + int groupID; + if (!groupMap.containsKey(group)) { + groupMap.put(group, g); + groupID = g; + g++; + } else groupID = groupMap.getInt(group); + tag.setInteger("GroupID", groupID); + } + vertices.appendTag(tag); + i++; + } + compound.setTag("Vertices", vertices); + + NBTTagList edges = new NBTTagList(); + for (GraphEdge graphEdge : this.getGraph().edgeSet()) { + CompoundTag tag = graphEdge.wrapped.serializeNBT(); + tag.setInteger("SourceID", vertexMap.getInt(graphEdge.getSource())); + tag.setInteger("TargetID", vertexMap.getInt(graphEdge.getTarget())); + tag.setDouble("Weight", graphEdge.getWeight()); + edges.appendTag(tag); + } + compound.setTag("Edges", edges); + + return compound; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java new file mode 100644 index 0000000000..e62db59e7a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java @@ -0,0 +1,213 @@ +package com.gregtechceu.gtceu.api.graphnet; + +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jgrapht.traverse.BreadthFirstIterator; + +import java.util.Iterator; + +public interface IGraphNet { + + /** + * Controls whether dynamic weight lookup will be used. + * Dynamic weight lookup can be more expensive, so this should not be enabled unless necessary. + */ + default boolean usesDynamicWeights(int algorithmID) { + return false; + } + + /** + * Controls whether predication of edges is allowed for this net. When false, path caching is improved by + * skipping the recomputation required in order to compensate for predication. + * + * @return whether predication should be allowed for this net. + */ + default boolean supportsPredication() { + return false; + } + + /** + * Adds a node to the graphnet. + * + * @param node The node to add. + */ + void addNode(@NotNull NetNode node); + + /** + * Gets the net node with the given equivalency data, if one exists. + * + * @param equivalencyData the equivalency data to match. + * @return the matching net node, if one exists. + */ + @Nullable + NetNode getNode(@NotNull Object equivalencyData); + + /** + * Removes a node from the graphnet. + * + * @param node The node to remove. + */ + void removeNode(@NotNull NetNode node); + + /** + * Links two nodes by an edge. + * + * @param source Source node. + * @param target Target node. + * @param bothWays If the graph is directional, passing in true will create both the forwards and backwards edge. + * @return the created edge, if it was created. Returns null if bothWays is set to true. + */ + @Nullable + @Contract("_, _, false -> _; _, _, true -> null") + NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays); + + /** + * Returns the edge linking two nodes together, if one exists. + * + * @param source Source node. + * @param target Target node. + * @return the linking edge, if one exists. + */ + @Nullable + NetEdge getEdge(@NotNull NetNode source, @NotNull NetNode target); + + /** + * Removes the edge linking two nodes together, if one exists. + * + * @param source Source node. + * @param target Target node. + * @param bothWays If the graph is directional, passing in true will remove both the forwards and backwards edge. + */ + void removeEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays); + + /** + * Gets the {@link INetGraph} backing this graphnet. This should NEVER be modified directly, but can be queried. + * + * @return the backing net graph + */ + @ApiStatus.Internal + default INetGraph getGraph() { + return getBacker().getGraph(); + } + + /** + * Gets the {@link GraphNetBacker} backing this graphnet. This should NEVER be used except inside the graphnet impl. + * + * @return the backing graphnet backer + */ + @ApiStatus.Internal + GraphNetBacker getBacker(); + + /** + * Get a blank group data for this graph.
+ * Make sure to override this if your NetGroups use data. + * + * @return The correct data variant. + */ + @Nullable + default AbstractGroupData getBlankGroupData() { + return null; + } + + /** + * Get a default node data for this graph. Generally used for immediate nbt deserialization. + * + * @return A default node data object. + */ + @NotNull + default NetLogicData getDefaultNodeData() { + return new NetLogicData().setLogicEntry(WeightFactorLogic.INSTANCE.getWith(1)); + } + + /** + * Returns whether a node exists in this graph. + * + * @param node the node in question. + * @return whether the node exists. + */ + default boolean containsNode(NetNode node) { + return getGraph().containsVertex(node.wrapper); + } + + /** + * Returns a breadth-first iterator through this graph, starting from the passed in node. + * + * @param node the node to start from. + * @return a breadth-first iterator through this graph. + */ + @NotNull + default Iterator breadthIterator(NetNode node) { + return new Iterator<>() { + + private final BreadthFirstIterator iterator = new BreadthFirstIterator<>(getGraph(), + node.wrapper); + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public NetNode next() { + return iterator.next().wrapped; + } + }; + } + + /** + * Used in {@link MultiNodeHelper} to determine if a node can be traversed, based on the nets that have been + * recently traversed in the {@link MultiNodeHelper}. + * + * @param net a recently traversed net + * @return if node traversal should be blocked. + */ + default boolean clashesWith(IGraphNet net) { + return false; + } + + /** + * @return the class all registered nodes are expected to be children of. + */ + Class getNodeClass(); + + /** + * While this is crude, it does allow for avoiding generics literally everywhere. + * The systems that make up a graphnet intertwine such that generics would be needed in basically every class. + * Basically, instead of a bunch of generics everywhere, we just instate an honor system that crashes the game if + * you violate it. + */ + default void nodeClassCheck(NetNode node) { + if (!(getNodeClass().isInstance(node))) + throw new IllegalArgumentException("Cannot provide a " + this.getClass().getSimpleName() + + " with a " + node.getClass().getSimpleName() + " node!"); + } + + /** + * @return a new node with no data, to be either nbt deserialized or initialized in some other way. + */ + @NotNull + NetNode getNewNode(); + + /** + * @return a new edge with no data, to be either nbt deserialized or initialized in some other way. + */ + @NotNull + default NetEdge getNewEdge() { + return new NetEdge(); + } + + /** + * Should only be used by the internal {@link GraphNetBacker} backing this graphnet. + */ + @ApiStatus.Internal + void markDirty(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java new file mode 100644 index 0000000000..0bf6b9e4f9 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java @@ -0,0 +1,138 @@ +package com.gregtechceu.gtceu.api.graphnet; + +import com.gregtechceu.gtceu.api.graphnet.logic.INetLogicEntryListener; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; + +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.NotNull; + +import java.lang.ref.WeakReference; +import java.util.List; + +/** + * MultiNodeHelpers are utility objects used to preserve sync between multiple nodes owned by different graphs. They do + * this by
+ * A) keeping a record of traversals to allow for blocking traversal when another net has been traversed + * recently and
+ * B) making sure that logic entries requiring it are the same object across all synced nodes.
+ *
+ * MultiNodeHelpers have no standard implementation and must be handled by a net and its nodes; see + * {@link com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet} and {@link com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode} + * for an example of this in action. + */ +public class MultiNodeHelper implements INetLogicEntryListener { + + protected final Object2ObjectOpenHashMap handledDatas = new Object2ObjectOpenHashMap<>(); + + protected final Object2LongOpenHashMap recentTransferNets = new Object2LongOpenHashMap<>(); + protected final int transferTimeout; + + protected final NetLogicData mergedData = new NetLogicData(); + + public MultiNodeHelper(int transferTimeout) { + this.transferTimeout = transferTimeout; + } + + public boolean traverse(IGraphNet net, long queryTick, boolean simulate) { + var iter = recentTransferNets.object2LongEntrySet().fastIterator(); + boolean allowed = true; + while (iter.hasNext()) { + var next = iter.next(); + if (net.clashesWith(next.getKey())) { + if (next.getLongValue() <= queryTick) { + iter.remove(); + } else { + allowed = false; + break; + } + } + } + if (allowed && !simulate) { + recentTransferNets.put(net, queryTick + transferTimeout); + } + return allowed; + } + + @Override + public void markLogicEntryAsUpdated(NetLogicEntry entry, boolean fullChange) { + // TODO have a helper or something on clientside to avoid redundant packets + handledDatas.forEach((k, v) -> v.data.markLogicEntryAsUpdated(entry, fullChange)); + } + + public void addNode(@NotNull NetNode node) { + List> toSet = new ObjectArrayList<>(); + for (NetLogicEntry entry : node.getData().getEntries()) { + if (entry.mergedToMultiNodeHelper()) { + NetLogicEntry existing = mergedData.getLogicEntryNullable(entry); + if (existing != null) { + existing.merge(node, entry); + // don't put it into the data yet because we're currently iterating through the data's entries. + toSet.add(existing); + } else { + addNewLogicEntry(entry); + } + } + } + handledDatas.put(node.getNet(), new LogicDataHandler(node)); + for (NetLogicEntry entry : toSet) { + node.getData().setLogicEntry(entry); + } + } + + public void removeNode(@NotNull NetNode node) { + LogicDataHandler removed = handledDatas.remove(node.getNet()); + if (removed != null) { + removed.invalidate(); + for (NetLogicEntry entry : this.mergedData.getEntries()) { + node.getData().removeLogicEntry(entry); + entry.unmerge(node); + } + } + } + + private void addNewLogicEntry(@NotNull NetLogicEntry entry) { + entry.registerToMultiNodeHelper(this); + mergedData.setLogicEntry(entry); + handledDatas.values().forEach(h -> h.data.setLogicEntry(entry)); + } + + protected class LogicDataHandler implements NetLogicData.ILogicDataListener { + + public final WeakReference nodeRef; + public final @NotNull NetLogicData.LogicDataListener listener; + public final @NotNull NetLogicData data; + + public LogicDataHandler(@NotNull NetNode node) { + this.data = node.getData(); + this.listener = data.createListener(this); + this.nodeRef = new WeakReference<>(node); + } + + public void invalidate() { + this.listener.invalidate(); + } + + @Override + public void markChanged(NetLogicEntry updatedEntry, boolean removed, boolean fullChange) { + if (!fullChange || !updatedEntry.mergedToMultiNodeHelper()) return; + NetNode node = nodeRef.get(); + if (node == null) return; + NetLogicEntry existing = mergedData.getLogicEntryNullable(updatedEntry); + if (removed) { + if (existing != null) mergedData.removeLogicEntry(existing); + } else { + if (existing != null) { + if (existing != updatedEntry) { + existing.merge(node, updatedEntry); + data.setLogicEntry(existing); + } + } else { + addNewLogicEntry(updatedEntry); + } + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java new file mode 100644 index 0000000000..412b80215d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java @@ -0,0 +1,190 @@ +package com.gregtechceu.gtceu.api.graphnet; + +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; + +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; +import java.util.stream.Collectors; + +public class NetGroup { + + public final IGraphNet net; + + private final Set nodes; + + private AbstractGroupData data; + + public NetGroup(IGraphNet net) { + this(net, new ObjectOpenHashSet<>()); + } + + public NetGroup(@NotNull IGraphNet net, + Set nodes) { + this.net = net; + this.data = net.getBlankGroupData(); + if (data != null) data.withGroup(this); + this.nodes = nodes; + nodes.forEach(this::onAddedToGroup); + } + + public void addNode(NetNode node) { + this.nodes.add(node); + this.onAddedToGroup(node); + } + + protected void addNodes(Collection nodes) { + this.nodes.addAll(nodes); + nodes.forEach(this::onAddedToGroup); + } + + protected void removeNode(NetNode node) { + this.nodes.remove(node); + } + + protected void removeNodes(Collection nodes) { + this.nodes.removeAll(nodes); + } + + protected void clearNodes() { + this.nodes.clear(); + } + + protected void onAddedToGroup(@NotNull NetNode node) { + node.setGroup(this); + } + + public static boolean isEdgeAllowed(@NotNull NetNode source, @NotNull NetNode target) { + NetGroup sourceGroup = source.getGroupUnsafe(); + NetGroup targetGroup = target.getGroupUnsafe(); + + if (sourceGroup == null || targetGroup == null) return true; + AbstractGroupData sourceData = sourceGroup.getData(); + AbstractGroupData targetData = targetGroup.getData(); + if (sourceData == null || targetData == null) return true; + + return sourceData.mergeAllowed(targetData) && targetData.mergeAllowed(sourceData); + } + + /** + * Merges the groups of an edge if necessary. Does not actually perform the edge creation. + * + * @param source the source node of the edge + * @param target the target node of the edge + */ + public static void mergeEdge(@NotNull NetNode source, @NotNull NetNode target) { + NetGroup sourceGroup = source.getGroupUnsafe(); + NetGroup targetGroup = target.getGroupUnsafe(); + if (sourceGroup == targetGroup) { + if (sourceGroup == null) { + sourceGroup = source.getGroupSafe(); + } else { + sourceGroup.clearPathCaches(); + return; + } + } + if (sourceGroup != null) { + sourceGroup.mergeNode(target); + } else { + targetGroup.mergeNode(source); + } + } + + protected void mergeNode(@NotNull NetNode node) { + NetGroup group = node.getGroupUnsafe(); + if (group != null) { + this.addNodes(group.getNodes()); + group.clearNodes(); + AbstractGroupData data = group.getData(); + if (data != null) { + if (this.data == null) this.data = data; + else this.data.merge(data); + } + } else addNode(node); + this.clearPathCaches(); + } + + /** + * Split this group by removing a node. Automatically removes the node from the backing graph. + * + * @param source node to remove + */ + public void splitNode(NetNode source) { + if (!this.net.containsNode(source)) return; + this.clearPathCaches(); + ObjectLinkedOpenHashSet targets = this.net.getGraph().outgoingEdgesOf(source.wrapper).stream() + .map(a -> { + GraphVertex target = a.getTarget(); + // handling so undirected graphs don't throw an error + if (!net.getGraph().isDirected() && target == source.wrapper) + return a.getSource().wrapped; + return target.wrapped; + }).collect(Collectors.toCollection(ObjectLinkedOpenHashSet::new)); + this.net.getBacker().removeVertex(source.wrapper); + this.removeNode(source); + while (!targets.isEmpty()) { + NetNode target = targets.removeLast(); + + Set targetGroup = new ObjectOpenHashSet<>(); + Iterator i = this.net.breadthIterator(target); + NetNode temp; + while (i.hasNext()) { + temp = i.next(); + targetGroup.add(temp); + // if we find a target node in our search, remove it from the list + targets.remove(temp); + } + this.removeNodes(targetGroup); + if (!targetGroup.isEmpty()) { + new NetGroup(this.net, targetGroup); + } + } + } + + /** + * Split this group by removing an edge. Automatically removes the edge from the graph. + * + * @param source source of the edge + * @param target target of the edge + * @return Whether the edge existed in the graph + */ + public boolean splitEdge(@NotNull NetNode source, @NotNull NetNode target) { + if (this.net.getBacker().removeEdge(source.wrapper, target.wrapper) != null) { + this.clearPathCaches(); + Set targetGroup = new ObjectOpenHashSet<>(); + Iterator i = this.net.breadthIterator(target); + NetNode temp; + while (i.hasNext()) { + temp = i.next(); + // if there's another complete path to the source node from the target node, there's no need to split + if (source == temp) return true; + targetGroup.add(temp); + } + this.removeNodes(targetGroup); + if (targetGroup.size() != 0) { + new NetGroup(this.net, targetGroup); + } + return true; + } + return false; + } + + /** + * For memory considerations, returns the uncloned set. Do not modify this directly. + */ + public Set getNodes() { + return nodes; + } + + public void clearPathCaches() { + this.getNodes().forEach(NetNode::clearPathCache); + } + + public AbstractGroupData getData() { + return this.data; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java new file mode 100644 index 0000000000..bb1374eaee --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java @@ -0,0 +1,156 @@ +package com.gregtechceu.gtceu.api.graphnet; + +import com.gregtechceu.gtceu.api.graphnet.alg.iter.IteratorFactory; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.INBTSerializable; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; +import java.util.Objects; + +public abstract class NetNode implements INBTSerializable { + + /** + * For interacting with the internal graph representation ONLY, do not use or set this field otherwise. + */ + @ApiStatus.Internal + public GraphVertex wrapper; + + private boolean isActive = false; + + private final @NotNull IGraphNet net; + private final @NotNull NetLogicData data; + private @Nullable NetGroup group = null; + + @Nullable + private IteratorFactory> pathCache = null; + + public NetNode(@NotNull IGraphNet net) { + this.net = net; + this.data = net.getDefaultNodeData(); + } + + public @NotNull IGraphNet getNet() { + return net; + } + + /** + * Determines whether the node should be treated as a valid destination of pathing algorithms + */ + public boolean isActive() { + return isActive; + } + + /** + * Sets whether the node should be treated as a valid destination of pathing algorithms + */ + public void setActive(boolean active) { + if (isActive != active) { + isActive = active; + NetGroup group = getGroupUnsafe(); + if (group != null) group.clearPathCaches(); + else this.clearPathCache(); + } + } + + public @NotNull NetLogicData getData() { + return data; + } + + public boolean traverse(long queryTick, boolean simulate) { + return true; + } + + @Nullable + public Iterator> getPathCache(IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + if (pathCache == null) return null; + return pathCache.newIterator(net.getGraph(), testObject, simulator, queryTick); + } + + /** + * Sets the path cache to the provided iterator factory. Returns itself for convenience. + * + * @param pathCache The new cache. + * @return The new cache. + */ + public NetNode setPathCache(IteratorFactory> pathCache) { + this.pathCache = pathCache; + return this; + } + + public void clearPathCache() { + this.pathCache = null; + } + + @NotNull + public NetGroup getGroupSafe() { + if (this.group == null) { + new NetGroup(this.getNet()).addNode(this); + // addNodes automatically sets our group to the new group + } + return this.group; + } + + @Nullable + public NetGroup getGroupUnsafe() { + return this.group; + } + + public NetGroup setGroup(NetGroup group) { + this.group = group; + return group; + } + + /** + * Use this to remove references that would keep this node from being collected by the garbage collector. + * This is called when a node is removed from the graph and should be discarded. + */ + public void onRemove() {} + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + tag.setTag("Data", this.data.serializeNBT()); + tag.setBoolean("IsActive", this.isActive()); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + this.isActive = nbt.getBoolean("IsActive"); + this.data.clearData(); + this.data.deserializeNBT((NBTTagList) nbt.getTag("Data")); + } + + /** + * Used to determine if two nodes are equal, for graph purposes. + * Should not change over the lifetime of a node, except when {@link #deserializeNBT(CompoundTag)} is called. + * + * @return equivalency data. Needs to work with {@link Objects#equals(Object, Object)} + */ + public abstract Object getEquivalencyData(); + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NetNode node = (NetNode) o; + return Objects.equals(getEquivalencyData(), node.getEquivalencyData()); + } + + @Override + public int hashCode() { + return Objects.hash(getEquivalencyData()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/AlgorithmBuilder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/AlgorithmBuilder.java new file mode 100644 index 0000000000..b95c75336b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/AlgorithmBuilder.java @@ -0,0 +1,12 @@ +package com.gregtechceu.gtceu.api.graphnet.alg; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; + +import org.jetbrains.annotations.NotNull; + +@FunctionalInterface +public interface AlgorithmBuilder { + + @NotNull + INetAlgorithm build(@NotNull IGraphNet net, boolean recomputeEveryCall); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java new file mode 100644 index 0000000000..5b3185e9ff --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java @@ -0,0 +1,97 @@ +package com.gregtechceu.gtceu.api.graphnet.alg; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.alg.iter.IteratorFactory; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.Nullable; +import org.jgrapht.alg.shortestpath.DefaultManyToManyShortestPaths; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public class DynamicWeightsShortestPathsAlgorithm extends DefaultManyToManyShortestPaths + implements INetAlgorithm { + + private final boolean recomputeEveryCall; + + public DynamicWeightsShortestPathsAlgorithm(IGraphNet net, boolean recomputeEveryCall) { + super(net.getGraph()); + this.recomputeEveryCall = recomputeEveryCall; + } + + @Override + public > IteratorFactory getPathsIteratorFactory(GraphVertex source, + NetPathMapper remapper) { + Set searchSpace = source.wrapped.getGroupSafe().getNodes().stream().filter(NetNode::isActive) + .map(n -> n.wrapper).filter(node -> !source.equals(node)).collect(Collectors.toSet()); + return (graph, testObject, simulator, queryTick) -> { + if (recomputeEveryCall) graph.prepareForAlgorithmRun(testObject, simulator, queryTick); + return new LimitedIterator<>(source, searchSpace, remapper); + }; + } + + protected class LimitedIterator> implements Iterator { + + private static final int MAX_ITERATIONS = 100; + + private final GraphVertex source; + private final Set searchSpace; + private final NetPathMapper remapper; + + private int iterationCount = 0; + private final ObjectArrayList visited = new ObjectArrayList<>(); + private @Nullable Path next; + + public LimitedIterator(GraphVertex source, Set searchSpace, NetPathMapper remapper) { + this.source = source; + this.searchSpace = searchSpace; + this.remapper = remapper; + } + + @Override + public boolean hasNext() { + if (next == null && iterationCount < MAX_ITERATIONS) calculateNext(); + return next != null; + } + + @Override + public Path next() { + if (!hasNext()) throw new NoSuchElementException(); + Path temp = next; + next = null; + return temp; + } + + private void calculateNext() { + iterationCount++; + if (iterationCount == 1) { + next = remapper.map(source); + return; + } + ManyToManyShortestPaths paths = getManyToManyPaths(Collections.singleton(source), + searchSpace); + Optional next = searchSpace.stream().map(node -> paths.getPath(source, node)).filter(Objects::nonNull) + .map(remapper::map).filter(this::isUnique).min(Comparator.comparingDouble(INetPath::getWeight)); + this.next = next.orElse(null); + next.ifPresent(this.visited::add); + } + + private boolean isUnique(Path path) { + for (Path other : visited) { + if (path.matches(other)) return false; + } + return true; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/INetAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/INetAlgorithm.java new file mode 100644 index 0000000000..4e7b0ca5b7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/INetAlgorithm.java @@ -0,0 +1,11 @@ +package com.gregtechceu.gtceu.api.graphnet.alg; + +import com.gregtechceu.gtceu.api.graphnet.alg.iter.IteratorFactory; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; + +public interface INetAlgorithm { + + > IteratorFactory getPathsIteratorFactory(GraphVertex source, + NetPathMapper remapper); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetAlgorithmWrapper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetAlgorithmWrapper.java new file mode 100644 index 0000000000..d35a65cf92 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetAlgorithmWrapper.java @@ -0,0 +1,45 @@ +package com.gregtechceu.gtceu.api.graphnet.alg; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.alg.iter.IteratorFactory; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class NetAlgorithmWrapper { + + private final IGraphNet net; + private final boolean recomputeEveryCall; + @Nullable + private INetAlgorithm alg; + + private final AlgorithmBuilder builder; + + public NetAlgorithmWrapper(IGraphNet net, @NotNull AlgorithmBuilder builder, boolean recomputeEveryCall) { + this.net = net; + this.builder = builder; + this.recomputeEveryCall = recomputeEveryCall; + } + + public IGraphNet getNet() { + return net; + } + + public void invalidate() { + this.alg = null; + } + + public > IteratorFactory getPathsIterator(GraphVertex source, + NetPathMapper remapper, + IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, + long queryTick) { + if (!recomputeEveryCall) net.getGraph().prepareForAlgorithmRun(testObject, simulator, queryTick); + if (alg == null) alg = builder.build(net, recomputeEveryCall); + return alg.getPathsIteratorFactory(source, remapper); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java new file mode 100644 index 0000000000..2381c4bb7f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java @@ -0,0 +1,39 @@ +package com.gregtechceu.gtceu.api.graphnet.alg; + +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import gregtech.api.util.function.TriFunction; + +import org.jetbrains.annotations.NotNull; +import org.jgrapht.GraphPath; + +import java.util.List; +import java.util.function.Function; + +public class NetPathMapper> { + + private final Function singlePathMapper; + private final TriFunction, List, @NotNull Double, Path> fullConstructMapper; + private final Function, Path> graphPathMapper; + + public NetPathMapper(Function singlePathMapper, + TriFunction, List, @NotNull Double, Path> fullConstructMapper, + Function, Path> graphPathMapper) { + this.singlePathMapper = singlePathMapper; + this.fullConstructMapper = fullConstructMapper; + this.graphPathMapper = graphPathMapper; + } + + public Path map(GraphVertex graphVertex) { + return singlePathMapper.apply(graphVertex); + } + + public Path map(List vertices, List graphEdges, double weight) { + return fullConstructMapper.apply(vertices, graphEdges, weight); + } + + public Path map(GraphPath graphPath) { + return graphPathMapper.apply(graphPath); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java new file mode 100644 index 0000000000..5d4b89d16a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java @@ -0,0 +1,64 @@ +package com.gregtechceu.gtceu.api.graphnet.alg; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.alg.iter.IteratorFactory; +import com.gregtechceu.gtceu.api.graphnet.alg.iter.SimpleIteratorFactories; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; + +import org.jgrapht.alg.shortestpath.CHManyToManyShortestPaths; +import org.jgrapht.util.ConcurrencyUtil; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Set; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.stream.Collectors; + +public final class ShortestPathsAlgorithm extends CHManyToManyShortestPaths + implements INetAlgorithm { + + private static final ThreadPoolExecutor BACKGROUND_EXECUTOR = ConcurrencyUtil.createThreadPoolExecutor(2); + + private final boolean recomputeEveryCall; + + public ShortestPathsAlgorithm(IGraphNet net, boolean recomputeEveryCall) { + super(net.getGraph(), BACKGROUND_EXECUTOR); + this.recomputeEveryCall = recomputeEveryCall; + } + + @Override + public > IteratorFactory getPathsIteratorFactory(GraphVertex source, + NetPathMapper remapper) { + if (!graph.containsVertex(source)) { + throw new IllegalArgumentException("Graph must contain the source vertex"); + } + // if the source has no group, it has no paths other than the path to itself. + if (source.wrapped.getGroupUnsafe() == null) { + Path path = remapper.map(source); + return SimpleIteratorFactories.fromSingleton(path); + } + + Set searchSpace = source.wrapped.getGroupSafe().getNodes().stream() + .filter(NetNode::isActive).map(n -> n.wrapper).collect(Collectors.toSet()); + Set singleton = Collections.singleton(source); + if (recomputeEveryCall) { + return (graph1, testObject, simulator, queryTick) -> { + graph1.prepareForAlgorithmRun(testObject, simulator, queryTick); + ManyToManyShortestPaths manyToManyPaths = getManyToManyPaths(singleton, + searchSpace); + return searchSpace.stream().map(node -> manyToManyPaths.getPath(source, node)) + .map(remapper::map).sorted(Comparator.comparingDouble(INetPath::getWeight)).iterator(); + }; + } else { + ManyToManyShortestPaths manyToManyPaths = getManyToManyPaths(singleton, + searchSpace); + return SimpleIteratorFactories.fromIterable(searchSpace.stream() + .map(node -> manyToManyPaths.getPath(source, node)) + .map(remapper::map).sorted(Comparator.comparingDouble(INetPath::getWeight)) + .collect(Collectors.toList())); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java new file mode 100644 index 0000000000..5f45c96939 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java @@ -0,0 +1,89 @@ +package com.gregtechceu.gtceu.api.graphnet.alg; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.alg.iter.IteratorFactory; +import com.gregtechceu.gtceu.api.graphnet.alg.iter.SimpleIteratorFactories; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; + +import com.github.bsideup.jabel.Desugar; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.Iterator; +import java.util.List; + +public final class SinglePathAlgorithm implements INetAlgorithm { + + private final IGraphNet net; + private final boolean recomputeEveryCall; + + public SinglePathAlgorithm(IGraphNet pipenet, boolean recomputeEveryCall) { + this.net = pipenet; + this.recomputeEveryCall = recomputeEveryCall; + } + + @Override + public > IteratorFactory getPathsIteratorFactory(GraphVertex source, + NetPathMapper remapper) { + if (recomputeEveryCall) { + return (graph, testObject, simulator, queryTick) -> { + graph.prepareForAlgorithmRun(testObject, simulator, queryTick); + List graphEdges = new ObjectArrayList<>(); + List nodes = new ObjectArrayList<>(); + Results results = compute(source, nodes, graphEdges); + if (!results.valid()) return SimpleIteratorFactories.getSingletonIterator(null); + if (graphEdges.isEmpty()) return SimpleIteratorFactories.getSingletonIterator(remapper.map(source)); + return SimpleIteratorFactories.getSingletonIterator(remapper.map(nodes, graphEdges, results.weight())); + }; + } else { + List graphEdges = new ObjectArrayList<>(); + List nodes = new ObjectArrayList<>(); + Results results = compute(source, nodes, graphEdges); + if (!results.valid()) return SimpleIteratorFactories.emptyFactory(); + if (graphEdges.isEmpty()) return SimpleIteratorFactories.fromSingleton(remapper.map(source)); + return SimpleIteratorFactories.fromSingleton(remapper.map(nodes, graphEdges, results.weight())); + } + } + + private Results compute(GraphVertex source, + List nodes, List graphEdges) { + nodes.add(source); + GraphVertex lastNode = null; + GraphVertex node = source; + GraphEdge graphEdge; + double sumWeight = 0; + boolean valid = true; + while (valid) { + Iterator i = this.net.getGraph().outgoingEdgesOf(node).iterator(); + if (!i.hasNext()) break; // we've reached the end, exit the loop while still valid + graphEdge = i.next(); + // if we are directed, we know that the target is the target. + // if we aren't directed, we need to see if the graphEdge's target is secretly the source + boolean reversedEdge = !this.net.getGraph().isDirected() && graphEdge.getTarget() == node; + if ((!reversedEdge && graphEdge.getTarget() == lastNode) || + (reversedEdge && graphEdge.getSource() == lastNode)) { + // current edge points to a previous node, either get the other edge or exit safely. + if (i.hasNext()) { + graphEdge = i.next(); + reversedEdge = !this.net.getGraph().isDirected() && graphEdge.getTarget() == node; + // we know that the new edge cannot point to the previous node + } else break; // we've reached the end, exit the loop while still valid + } else if (i.hasNext()) i.next(); // remove the second edge, if it exists. + if (i.hasNext()) valid = false; // third graphEdge detected - that's an invalid group + lastNode = node; + node = reversedEdge ? graphEdge.getSource() : graphEdge.getTarget(); + graphEdges.add(graphEdge); + nodes.add(node); + sumWeight += getWeight(graphEdge); + } + return new Results(sumWeight, valid); + } + + private double getWeight(GraphEdge graphEdge) { + return this.net.getGraph().getEdgeWeight(graphEdge); + } + + @Desugar + private record Results(double weight, boolean valid) {} +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/IteratorFactory.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/IteratorFactory.java new file mode 100644 index 0000000000..4b1498b6b2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/IteratorFactory.java @@ -0,0 +1,29 @@ +package com.gregtechceu.gtceu.api.graphnet.alg.iter; + +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public interface IteratorFactory { + + /** + * The provided iterator must always be used and discarded before the end of the tick. + */ + @Contract("_, _, _, _ -> new") + Iterator newIterator(INetGraph graph, IPredicateTestObject testObject, @Nullable SimulatorKey simulator, + long queryTick); + + static void defaultPrepareRun(INetGraph graph, IPredicateTestObject testObject, @Nullable SimulatorKey simulator, + long queryTick) { + graph.prepareForAlgorithmRun(testObject, simulator, queryTick); + } + + default boolean cacheable() { + return true; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/SimpleIteratorFactories.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/SimpleIteratorFactories.java new file mode 100644 index 0000000000..f8cacb5c03 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/iter/SimpleIteratorFactories.java @@ -0,0 +1,43 @@ +package com.gregtechceu.gtceu.api.graphnet.alg.iter; + +import java.util.Iterator; + +public final class SimpleIteratorFactories { + + public static IteratorFactory emptyFactory() { + return (graph, testObject, simulator, queryTick) -> new SingletonIterator<>(null); + } + + public static IteratorFactory fromIterable(Iterable prototype) { + return (graph, testObject, simulator, queryTick) -> prototype.iterator(); + } + + public static IteratorFactory fromSingleton(T singleton) { + return (graph, testObject, simulator, queryTick) -> new SingletonIterator<>(singleton); + } + + public static SingletonIterator getSingletonIterator(T singleton) { + return new SingletonIterator<>(singleton); + } + + private static class SingletonIterator implements Iterator { + + private T singleton; + + public SingletonIterator(T singleton) { + this.singleton = singleton; + } + + @Override + public boolean hasNext() { + return singleton != null; + } + + @Override + public T next() { + T temp = singleton; + singleton = null; + return temp; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java new file mode 100644 index 0000000000..cd03f0f587 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java @@ -0,0 +1,109 @@ +package com.gregtechceu.gtceu.api.graphnet.edge; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.logic.ChannelCountLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; +import java.util.Set; +import java.util.WeakHashMap; + +public abstract class AbstractNetFlowEdge extends NetEdge { + + private final AbstractChannelsHolder channels; + private final WeakHashMap simulatedChannels; + + public AbstractNetFlowEdge() { + this.channels = getNewHolder(null, null); + this.simulatedChannels = new WeakHashMap<>(9); + } + + @Override + public double getDynamicWeight(IPredicateTestObject channel, IGraphNet net, @Nullable SimulatorKey simulator, + long queryTick, + double defaultWeight) { + long flow = getFlowLimit(channel, net, queryTick, simulator); + if (flow <= 0) { + return defaultWeight * getThroughput() * Short.MAX_VALUE; + } else return defaultWeight * getThroughput() / flow; + } + + public boolean cannotSupportChannel(IPredicateTestObject channel, long queryTick, + @Nullable SimulatorKey simulator) { + if (!this.test(channel)) return false; + else return getChannels(simulator).cannotSupportChannel(channel, queryTick); + } + + protected AbstractChannelsHolder getChannels(@Nullable SimulatorKey simulator) { + if (simulator == null) return this.channels; + else { + AbstractChannelsHolder channels = simulatedChannels.get(simulator); + if (channels == null) { + channels = getNewHolder(this.channels, simulator); + simulatedChannels.put(simulator, channels); + } + return channels; + } + } + + protected int getChannelCount() { + return getData().getLogicEntryDefaultable(ChannelCountLogic.INSTANCE).getValue(); + } + + public long getThroughput() { + return getData().getLogicEntryDefaultable(ThroughputLogic.INSTANCE).getValue(); + } + + public long getFlowLimit(IPredicateTestObject channel, IGraphNet graph, long queryTick, + @Nullable SimulatorKey simulator) { + if (!this.test(channel)) return 0; + else return getChannels(simulator).getFlowLimit(channel, graph, queryTick); + } + + protected long getConsumedLimit(IPredicateTestObject channel, long queryTick, @Nullable SimulatorKey simulator) { + if (!this.test(channel)) return 0; + else return getChannels(simulator).getConsumedLimit(channel, queryTick); + } + + public void consumeFlowLimit(IPredicateTestObject channel, IGraphNet graph, long amount, long queryTick, + @Nullable SimulatorKey simulator) { + if (this.test(channel)) { + getChannels(simulator).consumeFlowLimit(channel, graph, amount, queryTick); + } + } + + public Set getActiveChannels(@Nullable SimulatorKey simulator, long queryTick) { + return getChannels(simulator).getActiveChannels(queryTick); + } + + protected abstract AbstractChannelsHolder getNewHolder(AbstractChannelsHolder prototype, + SimulatorKey simulator); + + protected abstract static class AbstractChannelsHolder { + + private final WeakReference simulator; + + public AbstractChannelsHolder(SimulatorKey simulator) { + this.simulator = new WeakReference<>(simulator); + } + + public SimulatorKey getSimulator() { + return simulator.get(); + } + + abstract void recalculateFlowLimits(long queryTick); + + abstract boolean cannotSupportChannel(IPredicateTestObject channel, long queryTick); + + abstract long getFlowLimit(IPredicateTestObject channel, IGraphNet graph, long queryTick); + + abstract long getConsumedLimit(IPredicateTestObject channel, long queryTick); + + abstract void consumeFlowLimit(IPredicateTestObject channel, IGraphNet graph, long amount, long queryTick); + + abstract Set getActiveChannels(long queryTick); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetEdge.java new file mode 100644 index 0000000000..458dfcedc7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetEdge.java @@ -0,0 +1,92 @@ +package com.gregtechceu.gtceu.api.graphnet.edge; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicateHandler; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraftforge.common.util.INBTSerializable; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class NetEdge implements INBTSerializable { + + /** + * For interacting with the internal graph representation ONLY, do not use or set this field otherwise. + */ + @ApiStatus.Internal + public @Nullable GraphEdge wrapper; + + private @Nullable EdgePredicateHandler predicateHandler; + + private @Nullable NetLogicData data; + + protected @Nullable NetNode getSource() { + if (wrapper == null) return null; + return wrapper.getSource().wrapped; + } + + protected @Nullable NetNode getTarget() { + if (wrapper == null) return null; + return wrapper.getTarget().wrapped; + } + + /** + * Should only be used on fake edges that are not registered to the graph. + */ + public void setData(@NotNull NetLogicData data) { + if (this.wrapper == null) this.data = data; + } + + /** + * This data is transient and should not be written to. + */ + public @NotNull NetLogicData getData() { + if (this.data == null) { + this.data = NetLogicData.unionNullable(getSource() == null ? null : getSource().getData(), + getTarget() == null ? null : getTarget().getData()); + // if we can't calculate it, create a new one just to guarantee nonnullness + if (this.data == null) this.data = new NetLogicData(); + } + return this.data; + } + + @NotNull + public EdgePredicateHandler getPredicateHandler() { + if (predicateHandler == null) predicateHandler = new EdgePredicateHandler(); + return predicateHandler; + } + + public boolean test(IPredicateTestObject object) { + if (predicateHandler == null) return true; + else return predicateHandler.test(object); + } + + public double getDynamicWeight(IPredicateTestObject channel, IGraphNet graph, @Nullable SimulatorKey simulator, + long queryTick, double defaultWeight) { + return defaultWeight; + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + // we don't need to write our NetLogicData to NBT because we can regenerate it from our nodes + if (predicateHandler != null && !predicateHandler.shouldIgnore()) + tag.put("Predicate", predicateHandler.serializeNBT()); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + if (nbt.contains("Predicate")) { + this.predicateHandler = new EdgePredicateHandler(); + this.predicateHandler.deserializeNBT(nbt.getList("Predicate", Tag.TAG_COMPOUND)); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowEdge.java new file mode 100644 index 0000000000..24280a5ed2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowEdge.java @@ -0,0 +1,159 @@ +package com.gregtechceu.gtceu.api.graphnet.edge; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Set; + +public class NetFlowEdge extends AbstractNetFlowEdge { + + private final int flowBufferTicks; + private final int regenerationTime; + + /** + * NetEdge that provides standard flow behavior handling + * + * @param flowBufferTicks Determines how many ticks of 'buffer' flow capacity can be built up along edges. Allows + * for once-an-interval push/pull operations instead of needing them every tick for maximum + * throughput. + */ + public NetFlowEdge(int flowBufferTicks) { + this.flowBufferTicks = Math.max(flowBufferTicks, 1); + this.regenerationTime = 1; + } + + /** + * NetEdge that provides standard flow behavior handling + * + * @param flowBufferMult Determines maximum mult of 'buffer' flow capacity that can be built up along edges. + * Allows for once-an-interval push/pull operations instead of needing them every unit of + * time for maximum throughput. + * @param regenerationTime Ticks required for flow to regenerate once. Allows slowing down the rate of regeneration. + */ + public NetFlowEdge(int flowBufferMult, int regenerationTime) { + this.flowBufferTicks = Math.max(flowBufferMult, 1); + this.regenerationTime = Math.max(regenerationTime, 1); + } + + @Override + protected AbstractChannelsHolder getNewHolder(AbstractChannelsHolder prototype, + SimulatorKey simulator) { + if (prototype instanceof ChannelsHolder holder) return new ChannelsHolder(holder, simulator); + return new ChannelsHolder(simulator); + } + + @Nullable + private NetFlowEdge getInverse(IGraphNet graph) { + if (getTarget() == null || getSource() == null) return null; + NetEdge edge = graph.getEdge(getTarget(), getSource()); + if (edge instanceof NetFlowEdge i && i != this) { + return i; + } + return null; + } + + private final class ChannelsHolder extends AbstractChannelsHolder { + + private final Object2LongOpenHashMap map; + private long lastQueryTick; + private boolean init; + + public ChannelsHolder(SimulatorKey simulator) { + super(simulator); + this.map = new Object2LongOpenHashMap<>(9); + } + + public ChannelsHolder(ChannelsHolder prototype, SimulatorKey simulator) { + super(simulator); + this.map = prototype.map.clone(); + this.lastQueryTick = prototype.lastQueryTick; + } + + @Override + boolean cannotSupportChannel(IPredicateTestObject channel, long queryTick) { + recalculateFlowLimits(queryTick); + if (map.containsKey(channel)) return map.getLong(channel) <= 0; + else return map.size() >= getChannelCount(); + } + + @Override + long getFlowLimit(IPredicateTestObject channel, IGraphNet graph, long queryTick) { + if (cannotSupportChannel(channel, queryTick)) return 0; + long limit = map.getLong(channel); + + NetFlowEdge inverse = getInverse(graph); + if (inverse != null) { + if (inverse.cannotSupportChannel(channel, queryTick, getSimulator())) return 0; + limit += inverse.getConsumedLimit(channel, queryTick, getSimulator()); + } + + return limit; + } + + @Override + long getConsumedLimit(IPredicateTestObject channel, long queryTick) { + recalculateFlowLimits(queryTick); + long limit = map.defaultReturnValue(); + return limit - map.getLong(channel); + } + + @Override + void consumeFlowLimit(IPredicateTestObject channel, IGraphNet graph, long amount, long queryTick) { + if (amount == 0) return; + recalculateFlowLimits(queryTick); + + // check against reverse edge + NetFlowEdge inverse = getInverse(graph); + if (inverse != null) { + long inverseConsumed = inverse.getConsumedLimit(channel, queryTick, getSimulator()); + if (inverseConsumed != 0) { + long toFreeUp = Math.min(inverseConsumed, amount); + inverse.consumeFlowLimit(channel, graph, -toFreeUp, queryTick, getSimulator()); + if (toFreeUp == amount) return; + amount -= toFreeUp; + } + } + + long finalAmount = amount; + map.compute(channel, (k, v) -> { + long d = map.defaultReturnValue(); + if (v == null) v = d; + v -= finalAmount; + if (v >= d) return null; + return v; + }); + } + + @Override + public void recalculateFlowLimits(long queryTick) { + if (!this.init) { + this.map.defaultReturnValue(getThroughput() * flowBufferTicks); + this.init = true; + } + int regenerationUnits = (int) (queryTick - this.lastQueryTick) / regenerationTime; + if (regenerationUnits < 0) { + this.map.clear(); + } else if (regenerationUnits > 0) { + List toRemove = new ObjectArrayList<>(); + this.map.replaceAll((k, v) -> { + v += (long) regenerationUnits * getThroughput(); + if (v >= map.defaultReturnValue()) toRemove.add(k); + return v; + }); + toRemove.forEach(this.map::removeLong); + this.lastQueryTick += (long) regenerationUnits * regenerationTime; + } + } + + @Override + Set getActiveChannels(long queryTick) { + recalculateFlowLimits(queryTick); + return map.keySet(); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java new file mode 100644 index 0000000000..1e6790c5f5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java @@ -0,0 +1,169 @@ +package com.gregtechceu.gtceu.api.graphnet.edge; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.util.math.MathHelper; + +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Set; + +public class NetFlowSharedEdge extends AbstractNetFlowEdge { + + private final int flowBufferTicks; + private final int regenerationTime; + + /** + * NetEdge that provides flow behavior where the capacity along an edge is shared by all channels. + * + * @param flowBufferTicks Determines how many ticks of 'buffer' flow capacity can be built up along edges. Allows + * for once-an-interval push/pull operations instead of needing them every tick for maximum + * throughput. + */ + public NetFlowSharedEdge(int flowBufferTicks) { + this.flowBufferTicks = Math.max(flowBufferTicks, 1); + this.regenerationTime = 1; + } + + /** + * NetEdge that provides flow behavior where the capacity along an edge is shared by all channels. + * + * @param flowBufferTicks Determines how many ticks of 'buffer' flow capacity can be built up along edges. Allows + * for once-an-interval push/pull operations instead of needing them every tick for maximum + * throughput. + * @param regenerationTime Ticks required for flow to regenerate once. Allows slowing down the rate of regeneration. + */ + public NetFlowSharedEdge(int flowBufferTicks, int regenerationTime) { + this.flowBufferTicks = Math.max(flowBufferTicks, 1); + this.regenerationTime = Math.max(regenerationTime, 1); + } + + @Override + protected AbstractChannelsHolder getNewHolder(AbstractChannelsHolder prototype, + SimulatorKey simulator) { + if (prototype instanceof ChannelsHolder holder) return new ChannelsHolder(holder, simulator); + return new ChannelsHolder(simulator); + } + + @Nullable + private NetFlowSharedEdge getInverse(IGraphNet graph) { + if (getTarget() == null || getSource() == null) return null; + NetEdge edge = graph.getEdge(getTarget(), getSource()); + if (edge instanceof NetFlowSharedEdge i && i != this) { + return i; + } + return null; + } + + private final class ChannelsHolder extends AbstractChannelsHolder { + + private long maxCapacity; + private long sharedCapacity; + private final Object2LongOpenHashMap map; + private long lastQueryTick; + private boolean init; + + public ChannelsHolder(SimulatorKey simulator) { + super(simulator); + this.map = new Object2LongOpenHashMap<>(9); + this.map.defaultReturnValue(0); + } + + public ChannelsHolder(ChannelsHolder prototype, SimulatorKey simulator) { + super(simulator); + this.map = prototype.map.clone(); + this.lastQueryTick = prototype.lastQueryTick; + } + + @Override + public boolean cannotSupportChannel(IPredicateTestObject channel, long queryTick) { + recalculateFlowLimits(queryTick); + if (sharedCapacity <= 0) return true; + else return map.size() >= getChannelCount(); + } + + @Override + long getFlowLimit(IPredicateTestObject channel, IGraphNet graph, long queryTick) { + if (cannotSupportChannel(channel, queryTick)) return 0; + + NetFlowSharedEdge inverse = getInverse(graph); + if (inverse != null) { + if (inverse.cannotSupportChannel(channel, queryTick, getSimulator())) return 0; + return sharedCapacity + inverse.getConsumedLimit(channel, queryTick, getSimulator()); + } else return sharedCapacity; + } + + @Override + long getConsumedLimit(IPredicateTestObject channel, long queryTick) { + recalculateFlowLimits(queryTick); + return map.getLong(channel); + } + + @Override + void consumeFlowLimit(IPredicateTestObject channel, IGraphNet graph, long amount, long queryTick) { + if (amount == 0) return; + recalculateFlowLimits(queryTick); + + // check against reverse edge + NetFlowSharedEdge inverse = getInverse(graph); + if (inverse != null) { + long inverseConsumed = inverse.getConsumedLimit(channel, queryTick, getSimulator()); + if (inverseConsumed != 0) { + long toFreeUp = Math.min(inverseConsumed, amount); + inverse.consumeFlowLimit(channel, graph, -toFreeUp, queryTick, getSimulator()); + if (toFreeUp == amount) return; + amount -= toFreeUp; + } + } + + long finalAmount = amount; + map.compute(channel, (k, v) -> { + if (v == null) v = 0L; + v += finalAmount; + if (v <= 0) return null; + return v; + }); + sharedCapacity -= finalAmount; + boundCapacity(); + } + + @Override + public void recalculateFlowLimits(long queryTick) { + if (!this.init) { + this.maxCapacity = getThroughput() * flowBufferTicks; + this.init = true; + } + int regenerationUnits = (int) (queryTick - this.lastQueryTick) / regenerationTime; + if (regenerationUnits < 0) { + this.map.clear(); + } else { + List toRemove = new ObjectArrayList<>(); + long regenerationPer = MathHelper.ceil((double) regenerationUnits * getThroughput() / map.size()); + map.replaceAll((k, v) -> { + v -= regenerationPer; + if (v <= 0) toRemove.add(k); + return v; + }); + sharedCapacity += regenerationPer * map.size(); + boundCapacity(); + toRemove.forEach(map::removeLong); + this.lastQueryTick += (long) regenerationUnits * regenerationTime; + } + } + + private void boundCapacity() { + if (this.sharedCapacity > this.maxCapacity) this.sharedCapacity = this.maxCapacity; + else if (this.sharedCapacity < 0) this.sharedCapacity = 0; + } + + @Override + Set getActiveChannels(long queryTick) { + recalculateFlowLimits(queryTick); + return map.keySet(); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/SimulatorKey.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/SimulatorKey.java new file mode 100644 index 0000000000..1af62157ea --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/SimulatorKey.java @@ -0,0 +1,25 @@ +package com.gregtechceu.gtceu.api.graphnet.edge; + +public final class SimulatorKey { + + private static int ID; + private final int id; + + private SimulatorKey() { + this.id = ID++; + } + + /** + * Claims a new, unique simulator instance for properly simulating flow edge limits without actually changing them. + *
+ * This simulator must be discarded after use so that the garbage collector can clean up. + */ + public static SimulatorKey getNewSimulatorInstance() { + return new SimulatorKey(); + } + + @Override + public int hashCode() { + return id; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphEdge.java new file mode 100644 index 0000000000..85363365d4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphEdge.java @@ -0,0 +1,56 @@ +package com.gregtechceu.gtceu.api.graphnet.graph; + +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; + +import org.jetbrains.annotations.NotNull; +import org.jgrapht.graph.DefaultWeightedEdge; + +import java.util.Objects; + +public final class GraphEdge extends DefaultWeightedEdge { + + public final @NotNull NetEdge wrapped; + + public GraphEdge(@NotNull NetEdge wrapped) { + this.wrapped = wrapped; + wrapped.wrapper = this; + } + + public @NotNull NetEdge getWrapped() { + return wrapped; + } + + @Override + public GraphVertex getSource() { + return (GraphVertex) super.getSource(); + } + + @Override + public GraphVertex getTarget() { + return (GraphVertex) super.getTarget(); + } + + /** + * Use this very sparingly. It's significantly better to go through {@link org.jgrapht.Graph#getEdgeWeight(Object)} + * instead, unless you are doing nbt serialization for example. + * + * @return the edge weight. + */ + @Override + public double getWeight() { + return super.getWeight(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GraphEdge graphEdge = (GraphEdge) o; + return Objects.equals(wrapped, graphEdge.wrapped); + } + + @Override + public int hashCode() { + return Objects.hash(wrapped); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphVertex.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphVertex.java new file mode 100644 index 0000000000..ee2c5430c9 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/GraphVertex.java @@ -0,0 +1,34 @@ +package com.gregtechceu.gtceu.api.graphnet.graph; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; + +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +public final class GraphVertex { + + public final @NotNull NetNode wrapped; + + public GraphVertex(@NotNull NetNode wrapped) { + this.wrapped = wrapped; + wrapped.wrapper = this; + } + + public @NotNull NetNode getWrapped() { + return wrapped; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GraphVertex graphVertex = (GraphVertex) o; + return Objects.equals(wrapped, graphVertex.wrapped); + } + + @Override + public int hashCode() { + return Objects.hash(wrapped); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/INetGraph.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/INetGraph.java new file mode 100644 index 0000000000..a8fc2e1451 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/INetGraph.java @@ -0,0 +1,21 @@ +package com.gregtechceu.gtceu.api.graphnet.graph; + +import com.gregtechceu.gtceu.api.graphnet.GraphNetBacker; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.ApiStatus; +import org.jgrapht.Graph; + +public interface INetGraph extends Graph { + + void prepareForAlgorithmRun(IPredicateTestObject testObject, SimulatorKey simulator, long queryTick); + + boolean isDirected(); + + /** + * This should only be called by {@link GraphNetBacker} + */ + @ApiStatus.Internal + void setupInternal(GraphNetBacker backer, boolean dynamicWeights); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetDirectedGraph.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetDirectedGraph.java new file mode 100644 index 0000000000..925b074bcc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetDirectedGraph.java @@ -0,0 +1,62 @@ +package com.gregtechceu.gtceu.api.graphnet.graph; + +import com.gregtechceu.gtceu.api.graphnet.GraphNetBacker; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jgrapht.graph.SimpleDirectedWeightedGraph; + +import java.util.function.Function; +import java.util.function.Supplier; + +public class NetDirectedGraph extends SimpleDirectedWeightedGraph implements INetGraph { + + private boolean dynamicWeights; + private IGraphNet net; + + private IPredicateTestObject testObject; + private SimulatorKey simulator; + private long queryTick; + + public NetDirectedGraph(Supplier vertexSupplier, Supplier edgeSupplier) { + super(vertexSupplier, edgeSupplier); + } + + @Override + public void prepareForAlgorithmRun(IPredicateTestObject testObject, SimulatorKey simulator, long queryTick) { + this.testObject = testObject; + this.simulator = simulator; + this.queryTick = queryTick; + } + + @Override + public boolean isDirected() { + return true; + } + + @Override + public void setupInternal(GraphNetBacker backer, boolean dynamicWeights) { + this.net = backer.getBackedNet(); + this.dynamicWeights = dynamicWeights; + } + + @Override + public double getEdgeWeight(GraphEdge graphEdge) { + if (!graphEdge.getSource().wrapped.traverse(queryTick, true) || + !graphEdge.getTarget().wrapped.traverse(queryTick, true)) + return Double.POSITIVE_INFINITY; + + if (graphEdge.wrapped.test(testObject)) { + if (dynamicWeights) { + return graphEdge.wrapped.getDynamicWeight(testObject, net, simulator, queryTick, + graphEdge.getWeight()); + } else return graphEdge.getWeight(); + } else return Double.POSITIVE_INFINITY; + } + + public static Function standardBuilder() { + return iGraphNet -> new NetDirectedGraph(() -> new GraphVertex(iGraphNet.getNewNode()), + () -> new GraphEdge(iGraphNet.getNewEdge())); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetUndirectedGraph.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetUndirectedGraph.java new file mode 100644 index 0000000000..a491b55bcd --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/graph/NetUndirectedGraph.java @@ -0,0 +1,62 @@ +package com.gregtechceu.gtceu.api.graphnet.graph; + +import com.gregtechceu.gtceu.api.graphnet.GraphNetBacker; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jgrapht.graph.SimpleWeightedGraph; + +import java.util.function.Function; +import java.util.function.Supplier; + +public class NetUndirectedGraph extends SimpleWeightedGraph implements INetGraph { + + private boolean dynamicWeights; + private IGraphNet net; + + private IPredicateTestObject testObject; + private SimulatorKey simulator; + private long queryTick; + + public NetUndirectedGraph(Supplier vertexSupplier, Supplier edgeSupplier) { + super(vertexSupplier, edgeSupplier); + } + + @Override + public void prepareForAlgorithmRun(IPredicateTestObject testObject, SimulatorKey simulator, long queryTick) { + this.testObject = testObject; + this.simulator = simulator; + this.queryTick = queryTick; + } + + @Override + public boolean isDirected() { + return false; + } + + @Override + public void setupInternal(GraphNetBacker backer, boolean dynamicWeights) { + this.net = backer.getBackedNet(); + this.dynamicWeights = dynamicWeights; + } + + @Override + public double getEdgeWeight(GraphEdge graphEdge) { + if (!graphEdge.getSource().wrapped.traverse(queryTick, true) || + !graphEdge.getTarget().wrapped.traverse(queryTick, true)) + return Double.POSITIVE_INFINITY; + + if (graphEdge.wrapped.test(testObject)) { + if (dynamicWeights) { + return graphEdge.wrapped.getDynamicWeight(testObject, net, simulator, queryTick, + graphEdge.getWeight()); + } else return graphEdge.getWeight(); + } else return Double.POSITIVE_INFINITY; + } + + public static Function standardBuilder() { + return iGraphNet -> new NetUndirectedGraph(() -> new GraphVertex(iGraphNet.getNewNode()), + () -> new GraphEdge(iGraphNet.getNewEdge())); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java new file mode 100644 index 0000000000..d4b93c36de --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java @@ -0,0 +1,49 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import net.minecraft.nbt.NBTTagDouble; +import net.minecraft.network.PacketBuffer; + +import org.jetbrains.annotations.NotNull; + +public abstract class AbstractDoubleLogicData> + extends NetLogicEntry { + + private double value; + + protected AbstractDoubleLogicData(@NotNull String name) { + super(name); + } + + public T getWith(double value) { + return getNew().setValue(value); + } + + protected T setValue(double value) { + this.value = value; + return (T) this; + } + + public double getValue() { + return this.value; + } + + @Override + public NBTTagDouble serializeNBT() { + return new NBTTagDouble(this.value); + } + + @Override + public void deserializeNBT(NBTTagDouble nbt) { + this.value = nbt.getDouble(); + } + + @Override + public void encode(PacketBuffer buf, boolean fullChange) { + buf.writeDouble(value); + } + + @Override + public void decode(PacketBuffer buf, boolean fullChange) { + this.value = buf.readDouble(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java new file mode 100644 index 0000000000..dfa8e2cc24 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java @@ -0,0 +1,48 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import net.minecraft.nbt.NBTTagInt; +import net.minecraft.network.PacketBuffer; + +import org.jetbrains.annotations.NotNull; + +public abstract class AbstractIntLogicData> extends NetLogicEntry { + + private int value; + + protected AbstractIntLogicData(@NotNull String name) { + super(name); + } + + public T getWith(int value) { + return getNew().setValue(value); + } + + protected T setValue(int value) { + this.value = value; + return (T) this; + } + + public int getValue() { + return this.value; + } + + @Override + public NBTTagInt serializeNBT() { + return new NBTTagInt(this.value); + } + + @Override + public void deserializeNBT(NBTTagInt nbt) { + this.value = nbt.getInt(); + } + + @Override + public void encode(PacketBuffer buf, boolean fullChange) { + buf.writeVarInt(this.value); + } + + @Override + public void decode(PacketBuffer buf, boolean fullChange) { + this.value = buf.readVarInt(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java new file mode 100644 index 0000000000..a5dae29cb2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java @@ -0,0 +1,50 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import net.minecraft.nbt.NBTTagLong; +import net.minecraft.network.PacketBuffer; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +public abstract class AbstractLongLogicData> extends NetLogicEntry { + + private long value; + + protected AbstractLongLogicData(@NotNull String name) { + super(name); + } + + public T getWith(long value) { + return getNew().setValue(value); + } + + @Contract("_ -> this") + public T setValue(long value) { + this.value = value; + return (T) this; + } + + public long getValue() { + return this.value; + } + + @Override + public NBTTagLong serializeNBT() { + return new NBTTagLong(this.value); + } + + @Override + public void deserializeNBT(NBTTagLong nbt) { + this.value = nbt.getLong(); + } + + @Override + public void encode(PacketBuffer buf, boolean fullChange) { + buf.writeVarLong(this.value); + } + + @Override + public void decode(PacketBuffer buf, boolean fullChange) { + this.value = buf.readVarLong(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java new file mode 100644 index 0000000000..75ba582ea3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java @@ -0,0 +1,24 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import org.jetbrains.annotations.NotNull; + +public final class ChannelCountLogic extends AbstractIntLogicData { + + public static final ChannelCountLogic INSTANCE = new ChannelCountLogic().setValue(1); + + public ChannelCountLogic() { + super("ChannelCount"); + } + + @Override + public @NotNull ChannelCountLogic getNew() { + return new ChannelCountLogic(); + } + + @Override + public ChannelCountLogic union(NetLogicEntry other) { + if (other instanceof ChannelCountLogic l) { + return this.getValue() < l.getValue() ? this : l; + } else return this; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/INetLogicEntryListener.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/INetLogicEntryListener.java new file mode 100644 index 0000000000..801ce2e418 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/INetLogicEntryListener.java @@ -0,0 +1,6 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +public interface INetLogicEntryListener { + + void markLogicEntryAsUpdated(NetLogicEntry entry, boolean fullChange); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java new file mode 100644 index 0000000000..e6c6f17c8e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java @@ -0,0 +1,24 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import org.jetbrains.annotations.NotNull; + +public final class MultiNetCountLogic extends AbstractIntLogicData { + + public static final MultiNetCountLogic INSTANCE = new MultiNetCountLogic().setValue(1); + + public MultiNetCountLogic() { + super("MultiNetCount"); + } + + @Override + public @NotNull MultiNetCountLogic getNew() { + return new MultiNetCountLogic(); + } + + @Override + public MultiNetCountLogic union(NetLogicEntry other) { + if (other instanceof MultiNetCountLogic l) { + return this.getValue() < l.getValue() ? this : l; + } else return this; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java new file mode 100644 index 0000000000..ce3554e751 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -0,0 +1,240 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.util.StringRepresentable; +import net.minecraftforge.common.util.INBTSerializable; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectCollection; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Set; + +/** + * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on logics, + * making a logics class return two different names is a valid way to register multiple instances. + */ +public final class NetLogicData implements INBTSerializable, INetLogicEntryListener { + + // TODO caching logic on simple logics to reduce amount of reduntant creation? + private final Object2ObjectOpenHashMap> logicEntrySet; + + private final Set listeners = new ObjectOpenHashSet<>(); + + public NetLogicData() { + logicEntrySet = new Object2ObjectOpenHashMap<>(4); + } + + private NetLogicData(Object2ObjectOpenHashMap> logicEntrySet) { + this.logicEntrySet = logicEntrySet; + } + + /** + * If the {@link NetLogicEntry#union(NetLogicEntry)} operation is not supported for this entry, + * nothing happens if an entry is already present. + */ + public NetLogicData mergeLogicEntry(NetLogicEntry entry) { + NetLogicEntry current = logicEntrySet.get(entry.getSerializedName()); + if (current == null) return setLogicEntry(entry); + + if (entry.getClass().isInstance(current)) { + entry = current.union(entry); + if (entry == null) return this; + } + return setLogicEntry(entry); + } + + public NetLogicData setLogicEntry(NetLogicEntry entry) { + entry.registerToNetLogicData(this); + logicEntrySet.put(entry.getSerializedName(), entry); + this.markLogicEntryAsUpdated(entry, true); + return this; + } + + /** + * Returns all registered logic entries; this should be treated in read-only manner. + */ + public ObjectCollection> getEntries() { + return logicEntrySet.values(); + } + + public void clearData() { + logicEntrySet.clear(); + logicEntrySet.trim(4); + } + + public NetLogicData removeLogicEntry(@NotNull NetLogicEntry key) { + return removeLogicEntry(key.getSerializedName()); + } + + public NetLogicData removeLogicEntry(@NotNull String key) { + NetLogicEntry entry = logicEntrySet.remove(key); + if (entry != null) { + entry.deregisterFromNetLogicData(this); + this.listeners.forEach(l -> l.markChanged(entry, true, true)); + logicEntrySet.trim(); + } + return this; + } + + @Override + public void markLogicEntryAsUpdated(NetLogicEntry entry, boolean fullChange) { + this.listeners.forEach(l -> l.markChanged(entry, false, fullChange)); + } + + public boolean hasLogicEntry(@NotNull String key) { + return logicEntrySet.containsKey(key); + } + + public boolean hasLogicEntry(@NotNull NetLogicEntry key) { + return logicEntrySet.containsKey(key.getSerializedName()); + } + + @Nullable + public NetLogicEntry getLogicEntryNullable(@NotNull String key) { + return logicEntrySet.get(key); + } + + @Nullable + public > T getLogicEntryNullable(@NotNull T key) { + try { + return (T) logicEntrySet.get(key.getSerializedName()); + } catch (ClassCastException ignored) { + return null; + } + } + + @NotNull + public > T getLogicEntryDefaultable(@NotNull T key) { + try { + T returnable = (T) logicEntrySet.get(key.getSerializedName()); + return returnable == null ? key : returnable; + } catch (ClassCastException ignored) { + return key; + } + } + + @Contract("null, null -> null; !null, _ -> new; _, !null -> new") + public static @Nullable NetLogicData unionNullable(@Nullable NetLogicData sourceData, + @Nullable NetLogicData targetData) { + if (sourceData == null && targetData == null) return null; + return union(sourceData == null ? targetData : sourceData, sourceData == null ? null : targetData); + } + + @Contract("_, _ -> new") + public static @NotNull NetLogicData union(@NotNull NetLogicData sourceData, @Nullable NetLogicData targetData) { + Object2ObjectOpenHashMap> newLogic = new Object2ObjectOpenHashMap<>( + sourceData.logicEntrySet); + if (targetData != null) { + for (String key : newLogic.keySet()) { + newLogic.computeIfPresent(key, (k, v) -> v.union(targetData.logicEntrySet.get(k))); + } + targetData.logicEntrySet.forEach((key, value) -> newLogic.computeIfAbsent(key, k -> value.union(null))); + } + return new NetLogicData(newLogic); + } + + @Contract("_, _ -> new") + public static @NotNull NetLogicData union(@NotNull NetLogicData first, @NotNull NetLogicData... others) { + Object2ObjectOpenHashMap> newLogic = new Object2ObjectOpenHashMap<>( + first.logicEntrySet); + for (NetLogicData other : others) { + for (String key : newLogic.keySet()) { + newLogic.computeIfPresent(key, (k, v) -> v.union(other.logicEntrySet.get(k))); + } + other.logicEntrySet.forEach((key, value) -> newLogic.computeIfAbsent(key, k -> value.union(null))); + } + return new NetLogicData(newLogic); + } + + public void addListener(LogicDataListener listener) { + this.listeners.add(listener); + } + + @Override + public ListTag serializeNBT() { + ListTag list = new ListTag(); + for (NetLogicEntry entry : getEntries()) { + CompoundTag tag = new CompoundTag(); + tag.putString("Name", entry.getSerializedName()); + Tag nbt = entry.serializeNBT(); + if (nbt != null) tag.put("Tag", nbt); + list.add(tag); + } + return list; + } + + @Override + public void deserializeNBT(ListTag nbt) { + for (int i = 0; i < nbt.size(); i++) { + CompoundTag tag = nbt.getCompound(i); + String key = tag.getString("Name"); + NetLogicEntry entry = this.logicEntrySet.get(key); + if (entry == null) entry = NetLogicRegistry.getSupplierNotNull(key).get(); + if (entry == null) continue; + entry.deserializeNBTNaive(tag.get("Tag")); + } + } + + //@Override + public void encode(FriendlyByteBuf buf) { + buf.writeVarInt(getEntries().size()); + for (NetLogicEntry entry : getEntries()) { + if (entry.shouldEncode()) { + buf.writeUtf(entry.getSerializedName()); + entry.encode(buf, true); + } else { + buf.writeUtf(""); + } + } + } + + //@Override + public void decode(FriendlyByteBuf buf) { + this.logicEntrySet.clear(); + int entryCount = buf.readVarInt(); + for (int i = 0; i < entryCount; i++) { + String name = buf.readUtf(255); + if (name.isEmpty()) continue; + NetLogicEntry existing = NetLogicRegistry.getSupplierErroring(name).get(); + existing.registerToNetLogicData(this); + existing.decode(buf); + this.logicEntrySet.put(name, existing); + } + this.logicEntrySet.trim(); + } + + public LogicDataListener createListener(ILogicDataListener listener) { + return new LogicDataListener(listener); + } + + public final class LogicDataListener { + + private final ILogicDataListener listener; + + private LogicDataListener(ILogicDataListener listener) { + this.listener = listener; + } + + private void markChanged(NetLogicEntry updatedEntry, boolean removed, boolean fullChange) { + this.listener.markChanged(updatedEntry, removed, fullChange); + } + + // TODO would a weak set be better? + public void invalidate() { + listeners.remove(this); + } + } + + @FunctionalInterface + public interface ILogicDataListener { + + void markChanged(NetLogicEntry updatedEntry, boolean removed, boolean fullChange); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java new file mode 100644 index 0000000000..8040301964 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java @@ -0,0 +1,127 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; + +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.util.StringRepresentable; +import net.minecraftforge.common.util.INBTSerializable; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Note - all extenders of this class are suggested to be final, in order to avoid unexpected + * {@link #union(NetLogicEntry)} behavior. + */ +public abstract class NetLogicEntry, N extends Tag> + implements INBTSerializable, StringRepresentable { + + private final @NotNull String name; + + protected NetLogicEntry(@NotNull String name) { + this.name = name; + NetLogicRegistry.register(this); + } + + @Override + public final @NotNull String getSerializedName() { + return name; + } + + public void deserializeNBTNaive(@Nullable Tag nbt) { + if (nbt != null) deserializeNBT((N) nbt); + } + + @Override + @Nullable + public abstract N serializeNBT(); + + /** + * Returns null if the operation is not supported. + */ + @Nullable + public T union(NetLogicEntry other) { + return null; + } + + /** + * Controls whether this logic entry should be merged to a MultiNodeHelper, if one is declared. + * The data entry must support {@link #merge(NetNode, NetLogicEntry)} with other entries of the same type, + * so that new nodes being added to the MultiNodeHelper can merge in. The multi node helper will ensure that + * all nodes registered to it contain the same object that their entries have been merged to, and when a node + * leaves the multi node helper {@link #unmerge(NetNode)} will be called for it. Server-Client sync is handled + * by the MultiNodeHelper, do not sync through NetLogicData. See {@link #registerToMultiNodeHelper(MultiNodeHelper)} + * + * @return whether logic entry should be merged to a MultiNodeHelper. + */ + public boolean mergedToMultiNodeHelper() { + return false; + } + + /** + * Called when this logic entry is added to a MultiNodeHelper. Any data syncing should go through the + * MultiNodeHelper after this method is called. + */ + public void registerToMultiNodeHelper(MultiNodeHelper helper) {} + + /** + * Should be used exclusively for {@link com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper} logic. + * + * @param otherOwner the net node being merged in + * @param other the logic being merged in + */ + public void merge(NetNode otherOwner, NetLogicEntry other) {} + + /** + * Should be used exclusively for {@link com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper} logic.
+ * Cannot be passed a logic entry since said logic entry would just be the instance this is being called for; + * if your logic needs to keep track then populate a map during {@link #merge(NetNode, NetLogicEntry)}. + * Keep in mind that this can be called for the data's original owner, despite + * {@link #merge(NetNode, NetLogicEntry)} not being called for the original owner. + * + * @param entryOwner the node being unmerged. + */ + public void unmerge(NetNode entryOwner) {} + + public void registerToNetLogicData(NetLogicData data) {} + + public void deregisterFromNetLogicData(NetLogicData data) {} + + public abstract @NotNull T getNew(); + + public T cast(NetLogicEntry entry) { + return (T) entry; + } + + /** + * Controls whether this {@link NetLogicEntry} will be synced to the client or not. + * + * @return + */ + public boolean shouldEncode() { + return true; + } + + public final void encode(FriendlyByteBuf buf) { + encode(buf, true); + } + + /** + * @param fullChange allows for less-full buffers to be sent and received. + * Useful for logics that can be partially modified, see {@link TemperatureLogic} + */ + public abstract void encode(FriendlyByteBuf buf, boolean fullChange); + + public final void decode(FriendlyByteBuf buf) { + decode(buf, true); + } + + /** + * @param fullChange allows for less-full buffers to be sent and received. + * Useful for logics that can be partially modified, see {@link TemperatureLogic} + */ + public abstract void decode(FriendlyByteBuf buf, boolean fullChange); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java new file mode 100644 index 0000000000..e783619091 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -0,0 +1,36 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.function.Supplier; + +public final class NetLogicRegistry { + + private static final Map>> REGISTRY = new Object2ObjectOpenHashMap<>(); + + static void register(NetLogicEntry entry) { + REGISTRY.putIfAbsent(entry.getName(), entry::getNew); + } + + public static @Nullable Supplier<@NotNull NetLogicEntry> getSupplierNullable(String name) { + return REGISTRY.get(name); + } + + public static @NotNull Supplier<@Nullable NetLogicEntry> getSupplierNotNull(String name) { + return REGISTRY.getOrDefault(name, () -> null); + } + + public static @NotNull Supplier<@NotNull NetLogicEntry> getSupplierErroring(String name) { + Supplier> supplier = REGISTRY.get(name); + if (supplier == null) throwNonexistenceError(); + return supplier; + } + + public static void throwNonexistenceError() { + throw new RuntimeException("Could not find a matching supplier for an encoded NetLogicEntry. " + + "This suggests that the server and client have different GT versions or modifications."); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java new file mode 100644 index 0000000000..bd092f3239 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java @@ -0,0 +1,24 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import org.jetbrains.annotations.NotNull; + +public final class ThroughputLogic extends AbstractLongLogicData { + + public static final ThroughputLogic INSTANCE = new ThroughputLogic().setValue(0); + + private ThroughputLogic() { + super("Throughput"); + } + + @Override + public @NotNull ThroughputLogic getNew() { + return new ThroughputLogic(); + } + + @Override + public ThroughputLogic union(NetLogicEntry other) { + if (other instanceof ThroughputLogic l) { + return this.getValue() < l.getValue() ? this : l; + } else return this; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java new file mode 100644 index 0000000000..f0eceb6e05 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java @@ -0,0 +1,24 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import org.jetbrains.annotations.NotNull; + +public final class WeightFactorLogic extends AbstractDoubleLogicData { + + public static final WeightFactorLogic INSTANCE = new WeightFactorLogic().setValue(0.1d); + + private WeightFactorLogic() { + super("WeightFactor"); + } + + @Override + public @NotNull WeightFactorLogic getNew() { + return new WeightFactorLogic(); + } + + @Override + public WeightFactorLogic union(NetLogicEntry other) { + if (other instanceof WeightFactorLogic l) { + return getWith(this.getValue() + l.getValue()); + } else return this; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/AbstractNetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/AbstractNetPath.java new file mode 100644 index 0000000000..29b6be4d4c --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/AbstractNetPath.java @@ -0,0 +1,90 @@ +package com.gregtechceu.gtceu.api.graphnet.path; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; + +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Objects; + +public abstract class AbstractNetPath implements INetPath { + + protected final List nodes; + + protected final List edges; + + protected final double weight; + + protected NetLogicData unifiedNodeData; + protected NetLogicData unifiedEdgeData; + + public AbstractNetPath(List nodes, List edges, double weight) { + this.nodes = nodes; + this.edges = edges; + this.weight = weight; + } + + @Override + public List getOrderedNodes() { + return nodes; + } + + @Override + public List getOrderedEdges() { + return edges; + } + + @Override + public double getWeight() { + return weight; + } + + @Override + public NetLogicData getUnifiedNodeData() { + if (unifiedNodeData == null) { + if (nodes.size() == 1) { + unifiedNodeData = nodes.get(0).getData(); + } else if (nodes.size() == 2) { + unifiedNodeData = NetLogicData.union(nodes.get(0).getData(), nodes.get(1).getData()); + } else { + unifiedNodeData = NetLogicData.union(nodes.get(0).getData(), + nodes.stream().skip(1).map(NetNode::getData).toArray(NetLogicData[]::new)); + } + } + return unifiedNodeData; + } + + @Override + @Nullable + public NetLogicData getUnifiedEdgeData() { + if (unifiedEdgeData == null) { + if (edges.size() == 0) { + return null; + } else if (edges.size() == 1) { + unifiedEdgeData = edges.get(0).getData(); + } else if (edges.size() == 2) { + unifiedEdgeData = NetLogicData.union(edges.get(0).getData(), edges.get(1).getData()); + } else { + unifiedEdgeData = NetLogicData.union(edges.get(0).getData(), + edges.stream().skip(1).map(NetEdge::getData).toArray(NetLogicData[]::new)); + } + } + return unifiedEdgeData; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AbstractNetPath that = (AbstractNetPath) o; + return Double.compare(that.weight, weight) == 0 && Objects.equals(nodes, that.nodes) && + Objects.equals(edges, that.edges); + } + + @Override + public int hashCode() { + return Objects.hash(nodes, edges, weight); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java new file mode 100644 index 0000000000..a88c4ab789 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java @@ -0,0 +1,44 @@ +package com.gregtechceu.gtceu.api.graphnet.path; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.alg.NetPathMapper; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.Nullable; +import org.jgrapht.GraphPath; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; + +public class GenericGraphNetPath extends AbstractNetPath { + + public static final NetPathMapper MAPPER = new NetPathMapper<>(GenericGraphNetPath::new, + GenericGraphNetPath::new, GenericGraphNetPath::new); + + public GenericGraphNetPath(GraphVertex vertex) { + this(Collections.singletonList(vertex), Collections.emptyList(), + vertex.wrapped.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue()); + } + + public GenericGraphNetPath(List vertices, List edges, double weight) { + super(vertices.stream().map(v -> v.wrapped).collect(Collectors.toList()), + edges.stream().map(e -> e.wrapped).collect(Collectors.toList()), weight); + } + + public GenericGraphNetPath(GraphPath path) { + this(path.getVertexList(), path.getEdgeList(), path.getWeight()); + } + + public interface Provider { + + Iterator getPaths(NetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java new file mode 100644 index 0000000000..adef782790 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java @@ -0,0 +1,41 @@ +package com.gregtechceu.gtceu.api.graphnet.path; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jgrapht.alg.util.ToleranceDoubleComparator; + +import java.util.List; + +public interface INetPath { + + ToleranceDoubleComparator WEIGHT_COMPARATOR = new ToleranceDoubleComparator(); + + List getOrderedNodes(); + + default N getSourceNode() { + return getOrderedNodes().get(0); + } + + default N getTargetNode() { + List nodes = getOrderedNodes(); + return nodes.get(nodes.size() - 1); + } + + List getOrderedEdges(); + + double getWeight(); + + default boolean matches(@NotNull INetPath other) { + return WEIGHT_COMPARATOR.compare(getWeight(), other.getWeight()) == 0 && + getOrderedNodes().equals(other.getOrderedNodes()) && getOrderedEdges().equals(other.getOrderedEdges()); + } + + NetLogicData getUnifiedNodeData(); + + @Nullable + NetLogicData getUnifiedEdgeData(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java new file mode 100644 index 0000000000..7a7f98acd4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java @@ -0,0 +1,44 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet; + +import com.gregtechceu.gtceu.api.graphnet.alg.NetPathMapper; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.path.AbstractNetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.Nullable; +import org.jgrapht.GraphPath; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; + +public class BasicWorldPipeNetPath extends AbstractNetPath { + + public static final NetPathMapper MAPPER = new NetPathMapper<>(BasicWorldPipeNetPath::new, + BasicWorldPipeNetPath::new, BasicWorldPipeNetPath::new); + + public BasicWorldPipeNetPath(GraphVertex vertex) { + this(Collections.singletonList(vertex), Collections.emptyList(), + vertex.wrapped.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue()); + } + + public BasicWorldPipeNetPath(List vertices, List edges, double weight) { + super(vertices.stream().map(v -> (WorldPipeNetNode) v.wrapped).collect(Collectors.toList()), + edges.stream().map(e -> e.wrapped).collect(Collectors.toList()), weight); + } + + public BasicWorldPipeNetPath(GraphPath path) { + this(path.getVertexList(), path.getEdgeList(), path.getWeight()); + } + + public interface Provider { + + Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java new file mode 100644 index 0000000000..d23d899795 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java @@ -0,0 +1,44 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet; + +import com.gregtechceu.gtceu.api.graphnet.alg.NetPathMapper; +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.path.AbstractNetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.Nullable; +import org.jgrapht.GraphPath; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; + +public class FlowWorldPipeNetPath extends AbstractNetPath { + + public static final NetPathMapper MAPPER = new NetPathMapper<>(FlowWorldPipeNetPath::new, + FlowWorldPipeNetPath::new, FlowWorldPipeNetPath::new); + + public FlowWorldPipeNetPath(GraphVertex vertex) { + this(Collections.singletonList(vertex), Collections.emptyList(), + vertex.wrapped.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue()); + } + + public FlowWorldPipeNetPath(List vertices, List edges, double weight) { + super(vertices.stream().map(v -> (WorldPipeNetNode) v.wrapped).collect(Collectors.toList()), + edges.stream().map(e -> (AbstractNetFlowEdge) e.wrapped).collect(Collectors.toList()), weight); + } + + public FlowWorldPipeNetPath(GraphPath path) { + this(path.getVertexList(), path.getEdgeList(), path.getWeight()); + } + + public interface Provider { + + Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java new file mode 100644 index 0000000000..bac3755c1a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; + +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.item.ItemStack; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.List; + +public interface IPipeNetNodeHandler { + + @NotNull + Collection getOrCreateFromNets(World world, BlockPos pos, IPipeStructure structure); + + @NotNull + Collection getFromNets(World world, BlockPos pos, IPipeStructure structure); + + void removeFromNets(World world, BlockPos pos, IPipeStructure structure); + + void addInformation(@NotNull ItemStack stack, World worldIn, @NotNull List tooltip, + @NotNull ITooltipFlag flagIn, + IPipeStructure structure); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java new file mode 100644 index 0000000000..1b97663fa7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java @@ -0,0 +1,74 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet; + +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseData; +import gregtech.api.util.TaskScheduler; +import gregtech.api.util.function.Task; + +import net.minecraft.world.World; + +import com.github.bsideup.jabel.Desugar; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.WeakHashMap; + +public class NodeLossCache implements Task { + + private static final WeakHashMap CACHE = new WeakHashMap<>(); + + public static void registerLossResult(Key key, NodeLossResult result) { + NodeLossCache existing = CACHE.get(key.node().getNet()); + if (existing == null) { + existing = new NodeLossCache(key.node().getNet().getLevel()); + CACHE.put(key.node().getNet(), existing); + } + existing.registerResult(key, result); + } + + public static @Nullable NodeLossResult getLossResult(Key key) { + NodeLossCache existing = CACHE.get(key.node().getNet()); + if (existing == null) { + existing = new NodeLossCache(key.node().getNet().getLevel()); + CACHE.put(key.node().getNet(), existing); + } + return existing.getResult(key); + } + + private final Map cache = new Object2ObjectOpenHashMap<>(); + + private NodeLossCache(World world) { + TaskScheduler.scheduleTask(world, TaskScheduler.weakTask(this)); + } + + public void registerResult(Key key, NodeLossResult result) { + cache.put(key, result); + } + + public @Nullable NodeLossResult getResult(Key key) { + return cache.get(key); + } + + @Override + public boolean run() { + if (cache.isEmpty()) return true; + for (var result : cache.entrySet()) { + result.getValue().triggerPostAction(result.getKey().node()); + } + cache.clear(); + return true; + } + + public static Key key(WorldPipeNetNode node, IPredicateTestObject testObject, SimulatorKey simulator) { + return new Key(node, testObject, simulator); + } + + public static Key key(WorldPipeNetNode node, ITraverseData data) { + return new Key(node, data.getTestObject(), data.getSimulatorKey()); + } + + @Desugar + public record Key(WorldPipeNetNode node, IPredicateTestObject testObject, SimulatorKey simulator) {} +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossResult.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossResult.java new file mode 100644 index 0000000000..5c636d7326 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossResult.java @@ -0,0 +1,53 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet; + +import com.gregtechceu.gtceu.api.graphnet.traverse.util.CompositeLossOperator; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; + +public final class NodeLossResult { + + public static final NodeLossResult IDENTITY = new NodeLossResult(null, ReversibleLossOperator.IDENTITY); + + private final @Nullable Consumer postAction; + private final @NotNull ReversibleLossOperator lossFunction; + + public NodeLossResult(@Nullable Consumer postAction, + @NotNull ReversibleLossOperator lossFunction) { + this.postAction = postAction; + this.lossFunction = lossFunction; + } + + @Contract("!null, !null -> new; !null, null -> param1; null, !null -> param2; null, null -> null") + public static NodeLossResult combine(@Nullable NodeLossResult a, @Nullable NodeLossResult b) { + if (a == null) return b; + if (b == null) return a; + Consumer postAction = a.postAction; + if (b.postAction != null) { + if (postAction == null) postAction = b.postAction; + else postAction = postAction.andThen(b.postAction); + } + return new NodeLossResult(postAction, new CompositeLossOperator(a.lossFunction, b.lossFunction)); + } + + public boolean hasPostAction() { + return postAction != null; + } + + public Consumer getPostAction() { + return postAction; + } + + public void triggerPostAction(WorldPipeNetNode node) { + if (postAction == null) return; + this.postAction.accept(node); + } + + public @NotNull ReversibleLossOperator getLossFunction() { + return lossFunction; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java new file mode 100644 index 0000000000..c1a839ae47 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -0,0 +1,219 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet; + +import com.gregtechceu.gtceu.api.blockentity.IDirtyNotifiable; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; +import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNet; + +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraftforge.common.capabilities.Capability; + +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Stream; + +public abstract class WorldPipeNet extends WorldNet { + + public static final int MULTI_NET_TIMEOUT = 10; + + private static final Object2ObjectOpenHashMap> dimensionNets = new Object2ObjectOpenHashMap<>(); + + public WorldPipeNet(String name, Function graphBuilder, + AlgorithmBuilder... algorithmBuilders) { + super(name, graphBuilder, algorithmBuilders); + } + + public WorldPipeNet(String name, boolean directed, AlgorithmBuilder... algorithmBuilders) { + super(name, directed, algorithmBuilders); + } + + @Override + public void setWorld(Level world) { + if (getLevel() == world) return; + super.setLevel(world); + dimensionNets.compute(getDimension(), (k, v) -> { + if (v == null) v = GTUtility.createWeakHashSet(); + v.add(this); + return v; + }); + } + + public final void updatePredication(@NotNull WorldPipeNetNode node, @NotNull PipeBlockEntity tile) { + if (supportsPredication()) updatePredicationInternal(node, tile); + } + + /** + * Called when a PipeBlockEntity is marked dirty through {@link IDirtyNotifiable#markAsDirty()}, which is generally + * when the state of its covers is changed. + * + * @param tile the tile marked dirty. + * @param node the associated node. + */ + protected void updatePredicationInternal(@NotNull WorldPipeNetNode node, @NotNull PipeBlockEntity tile) { + boolean dirty = false; + for (Direction facing : GTUtil.DIRECTIONS) { + PipeBlockEntity neighbor = tile.getPipeNeighbor(facing, false); + if (neighbor == null) continue; + WorldPipeNetNode neighborNode = this.getNode(neighbor.getBlockPos()); + if (neighborNode == null) continue; + NetEdge edge = getEdge(node, neighborNode); + if (edge == null) continue; + dirty |= predicateEdge(edge, node, tile.getCoverHolder().getCoverAtSide(facing), neighborNode, + neighbor.getCoverHolder().getCoverAtSide(facing.getOpposite())); + } + if (dirty) markDirty(); + } + + /** + * Preferred method to override if your net has complex custom predication rules. If the net is directed, + * this method will not be called twice, so special handling for directedness is needed. + * + * @param source the source of the edge. + * @param coverSource the cover on the source facing the target. + * @param target the target of the edge. + * @param coverTarget the cover on the target facing the source. + * @return whether the predication state has changed and this net needs to be marked dirty. + */ + protected boolean predicateEdge(@NotNull NetEdge edge, @NotNull WorldPipeNetNode source, + @Nullable Cover coverSource, + @NotNull WorldPipeNetNode target, @Nullable Cover coverTarget) { + Map> prevValue = new Object2ObjectOpenHashMap<>( + edge.getPredicateHandler().getPredicateSet()); + edge.getPredicateHandler().clearPredicates(); + coverPredication(edge, coverSource, coverTarget); + boolean edgeSame = !prevValue.equals(edge.getPredicateHandler().getPredicateSet()); + if (getGraph().isDirected()) { + edge = getEdge(target, source); + if (edge == null) return edgeSame; + if (edgeSame) { + prevValue.clear(); + prevValue.putAll(edge.getPredicateHandler().getPredicateSet()); + } + edge.getPredicateHandler().clearPredicates(); + coverPredication(edge, coverSource, coverTarget); + if (edgeSame) { + edgeSame = !prevValue.equals(edge.getPredicateHandler().getPredicateSet()); + } + } + return edgeSame; + } + + /** + * Preferred method to override if your net has custom predication rules that only depend on covers. + * If the net is directed, this method will be called twice, so no special handling for directedness is + * needed. + * + * @param edge the edge to predicate + * @param a the cover on the source of the edge + * @param b the cover on the sink of the edge + */ + protected void coverPredication(@NotNull NetEdge edge, @Nullable Cover a, @Nullable Cover b) {} + + public abstract Capability[] getTargetCapabilities(); + + public abstract IPipeCapabilityObject[] getNewCapabilityObjects(WorldPipeNetNode node); + + @Override + public @NotNull WorldPipeNetNode getOrCreateNode(@NotNull BlockPos pos) { + return (WorldPipeNetNode) super.getOrCreateNode(pos); + } + + @Override + public @Nullable WorldPipeNetNode getNode(@NotNull BlockPos equivalencyData) { + return (WorldPipeNetNode) getNode((Object) equivalencyData); + } + + protected Stream<@NotNull WorldPipeNet> sameDimensionNetsStream() { + return dimensionNets.getOrDefault(this.getDimension(), Collections.emptySet()).stream() + .filter(Objects::nonNull); + } + + public void synchronizeNode(WorldPipeNetNode node) { + // basically, if another net has a node in the exact same position, then we know it's the same block. + // thus, we set up a multi net node handler for the node in order to manage the overlap + // this is disk-load safe, since this method is called during nbt deserialization. + sameDimensionNetsStream().map(n -> n.getNode(node.getEquivalencyData())).filter(Objects::nonNull) + .forEach(n -> { + if (n.overlapHelper != node.overlapHelper) { + if (node.overlapHelper == null) { + // n handler is not null + node.overlapHelper = n.overlapHelper; + n.overlapHelper.addNode(node); + return; + } + } else if (n.overlapHelper == null) { + // both handlers are null + node.overlapHelper = new MultiNodeHelper(MULTI_NET_TIMEOUT); + node.overlapHelper.addNode(n); + } + // n handler does not match cast handler + n.overlapHelper = node.overlapHelper; + n.overlapHelper.addNode(node); + }); + } + + public static String getDataID(final String baseID, final World world) { + if (world == null || world.isRemote) + throw new RuntimeException("WorldPipeNets should only be created on the server!"); + int dimension = world.provider.getDimension(); + return baseID + '.' + dimension; + } + + /** + * Get the network ID for this net. Must be unique and deterministic between server and client, but can change + * between mod versions. + * + * @return the net's network id. + */ + public abstract int getNetworkID(); + + @Override + public final Class getNodeClass() { + return WorldPipeNetNode.class; + } + + @Override + public final @NotNull WorldPipeNetNode getNewNode() { + return new WorldPipeNetNode(this); + } + + @Contract(value = " -> new", pure = true) + public static @NotNull Object2ObjectOpenCustomHashMap getSensitiveHashMap() { + return new Object2ObjectOpenCustomHashMap<>(SensitiveStrategy.INSTANCE); + } + + protected static class SensitiveStrategy implements Hash.Strategy { + + public static final SensitiveStrategy INSTANCE = new SensitiveStrategy(); + + @Override + public int hashCode(WorldPipeNetNode o) { + return Objects.hash(o, o.getNet()); + } + + @Override + public boolean equals(WorldPipeNetNode a, WorldPipeNetNode b) { + return a.equals(b) && a.getNet().equals(b.getNet()); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java new file mode 100644 index 0000000000..ac81ae79ef --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -0,0 +1,84 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet; + +import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.IWorldPipeNetTile; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNetNode; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; + +public final class WorldPipeNetNode extends WorldNetNode { + + private static final PipeBlockEntity FALLBACK = new PipeBlockEntity(); + + @Nullable + MultiNodeHelper overlapHelper; + + private WeakReference tileReference; + + public WorldPipeNetNode(WorldPipeNet net) { + super(net); + } + + public @NotNull IWorldPipeNetTile getTileEntity() { + IWorldPipeNetTile tile = getTileEntity(true); + if (tile == null) { + // something went very wrong, return the fallback to prevent NPEs and remove us from the net. + getNet().removeNode(this); + tile = FALLBACK; + } + return tile; + } + + @Nullable + public IWorldPipeNetTile getTileEntityNoLoading() { + return getTileEntity(false); + } + + private IWorldPipeNetTile getTileEntity(boolean allowLoading) { + if (tileReference != null) { + IWorldPipeNetTile tile = tileReference.get(); + if (tile != null) return tile; + } + Level level = getNet().getLevel(); + if (!allowLoading && !level.isLoaded(getEquivalencyData())) return null; + BlockEntity tile = level.getBlockEntity(getEquivalencyData()); + if (tile instanceof IWorldPipeNetTile pipe) { + this.tileReference = new WeakReference<>(pipe); + return pipe; + } else return null; + } + + @Override + public void onRemove() { + if (this.overlapHelper != null) { + this.overlapHelper.removeNode(this); + this.overlapHelper = null; + } + } + + @Override + public @NotNull WorldPipeNet getNet() { + return (WorldPipeNet) super.getNet(); + } + + @Override + public WorldPipeNetNode setPos(BlockPos pos) { + super.setPos(pos); + this.getNet().synchronizeNode(this); + return this; + } + + @Override + public boolean traverse(long queryTick, boolean simulate) { + if (overlapHelper != null) { + return overlapHelper.traverse(this.getNet(), queryTick, simulate); + } else return true; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java new file mode 100644 index 0000000000..46c68c8780 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java @@ -0,0 +1,146 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import gregtech.api.cover.Cover; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import gregtech.api.util.DimensionFacingPos; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.PacketBuffer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Direction; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; + +public final class EdgeCoverReferenceLogic extends NetLogicEntry { + + public static final EdgeCoverReferenceLogic INSTANCE = new EdgeCoverReferenceLogic(); + + @Nullable + private WeakReference coverSource; + private DimensionFacingPos coverSourcePos; + @Nullable + private WeakReference coverTarget; + private DimensionFacingPos coverTargetPos; + + public EdgeCoverReferenceLogic() { + super("EdgeCoverReference"); + } + + @Contract("_,_ -> this") + public EdgeCoverReferenceLogic coverSource(@NotNull DimensionFacingPos pos, @NotNull Cover cover) { + this.coverSource = new WeakReference<>(cover); + this.coverSourcePos = pos; + return this; + } + + @Contract("_,_ -> this") + public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @NotNull Cover cover) { + this.coverTarget = new WeakReference<>(cover); + this.coverTargetPos = pos; + return this; + } + + private @Nullable Cover getSource() { + if (coverSource == null) return null; + Cover ref = coverSource.get(); + if (ref == null) { + World world = DimensionManager.getWorld(coverSourcePos.getDimension()); + if (world == null || !world.isBlockLoaded(coverSourcePos.getPos())) return null; + + TileEntity tile = world.getTileEntity(coverSourcePos.getPos()); + if (tile instanceof PipeBlockEntity pipe) { + Cover cover = pipe.getCoverHolder().getCoverAtSide(coverSourcePos.getFacing()); + if (cover != null) { + this.coverSource = new WeakReference<>(cover); + return cover; + } else { + // the cover doesn't exist, which makes no sense since we have a reference to its location but + // whatever + this.coverSource = null; + return null; + } + } else { + // the pipe doesn't exist, which makes no sense since the edge holding us exists but whatever + this.coverSource = null; + return null; + } + } else { + return ref; + } + } + + private @Nullable Cover getTarget() { + if (coverTarget == null) return null; + Cover ref = coverTarget.get(); + if (ref == null) { + World world = DimensionManager.getWorld(coverTargetPos.getDimension()); + if (world == null || !world.isBlockLoaded(coverTargetPos.getPos())) return null; + + TileEntity tile = world.getTileEntity(coverTargetPos.getPos()); + if (tile instanceof PipeBlockEntity pipe) { + Cover cover = pipe.getCoverHolder().getCoverAtSide(coverTargetPos.getFacing()); + if (cover != null) { + this.coverTarget = new WeakReference<>(cover); + return cover; + } else { + // the cover doesn't exist, which makes no sense since we have a reference to its location but + // whatever + this.coverTarget = null; + return null; + } + } else { + // the pipe doesn't exist, which makes no sense since the edge holding us exists but whatever + this.coverTarget = null; + return null; + } + } else { + return ref; + } + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + tag.setLong("SourcePos", coverSourcePos.getPos().toLong()); + tag.setByte("SourceFacing", (byte) coverSourcePos.getFacing().ordinal()); + tag.setInteger("SourceDim", coverSourcePos.getDimension()); + tag.setLong("TargetPos", coverTargetPos.getPos().toLong()); + tag.setByte("TargetFacing", (byte) coverTargetPos.getFacing().ordinal()); + tag.setInteger("TargetDim", coverTargetPos.getDimension()); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + this.coverSourcePos = new DimensionFacingPos(BlockPos.fromLong(nbt.getLong("SourcePos")), + GTUtil.DIRECTIONS[nbt.getByte("SourceFacing")], nbt.getInteger("SourceDim")); + this.coverSource = new WeakReference<>(null); + this.coverTargetPos = new DimensionFacingPos(BlockPos.fromLong(nbt.getLong("TargetPos")), + GTUtil.DIRECTIONS[nbt.getByte("TargetFacing")], nbt.getInteger("TargetDim")); + this.coverTarget = coverSource; + } + + @Override + public @NotNull EdgeCoverReferenceLogic getNew() { + return new EdgeCoverReferenceLogic(); + } + + @Override + public boolean shouldEncode() { + return false; + } + + @Override + public void encode(PacketBuffer buf, boolean fullChange) {} + + @Override + public void decode(PacketBuffer buf, boolean fullChange) {} +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EnumLossFunction.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EnumLossFunction.java new file mode 100644 index 0000000000..86799b9058 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EnumLossFunction.java @@ -0,0 +1,111 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; + +/** + * A bunch of loss functions. By the power of Wolfram Alpha. + * Demonstration Graph + */ +public enum EnumLossFunction { + + // DO NOT REORDER FUNCTIONS, THE ORDER IS USED FOR NBT SERIALIZATION + /** + * x value is lost every tick. + *
+ * A constant rate. + */ + ARITHMETIC { + + @Override + public float applyLoss(float value, float factorX, float factorY, int timePassed) { + float initialThermalEnergy = value; + value -= Math.signum(value) * factorX; + if (value < initialThermalEnergy) return 0; + return tolerate(value); + } + }, + /** + * x% of value is lost every tick. + *
+ * Faster than {@link EnumLossFunction#ARITHMETIC} at large values, but slower at small values. + */ + GEOMETRIC { + + @Override + public float applyLoss(float value, float factorX, float factorY, int timePassed) { + value *= Math.pow(1 - (factorX / 100), timePassed); + return tolerate(value); + } + }, + /** + * value is raised to the power of 1 - x every tick. + *
+ * Faster than {@link EnumLossFunction#GEOMETRIC} at large values, but incredibly slow at small values. + */ + POWER { + + @Override + public float applyLoss(float value, float factorX, float factorY, int timePassed) { + value = (float) (Math.signum(value) * + Math.pow(Math.abs(value), Math.pow(1 - factorX, timePassed))); + return tolerate(value); + } + }, + /** + * x% of value is lost, then y more, every tick. + *
+ * Slightly faster than {@link EnumLossFunction#GEOMETRIC} at large values, + * slightly faster than {@link EnumLossFunction#ARITHMETIC} at small values. + */ + GEOMETRIC_ARITHMETIC { + + @Override + public float applyLoss(float value, float factorX, float factorY, int timePassed) { + float initialThermalEnergy = value; + + float a = 1 - (factorX / 100); + float b = Math.signum(value) * factorY; + value = (float) ((b - Math.pow(a, timePassed) * + (-a * value + b + value)) / (a - 1)); + + if (value < initialThermalEnergy) return 0; + return tolerate(value); + } + }, + /** + * value is raised to the power of 1 - x, then y% more is lost, every tick. + *
+ * Slightly faster than {@link EnumLossFunction#POWER} at large values, + * slightly faster than {@link EnumLossFunction#GEOMETRIC} at small values. + */ + POWER_GEOMETRIC { + + @Override + public float applyLoss(float value, float factorX, float factorY, int timePassed) { + float c = 1 - factorX; + value = (float) (Math.pow(1 - (factorY / 100), (Math.pow(c, timePassed) - 1) / (c - 1)) * + Math.pow(Math.abs(value), Math.pow(c, timePassed)) * Math.signum(value)); + return tolerate(value); + } + }, + /** + * The evaluation of value = value - x * (value ^ y) is recursively found for every tick passed. + */ + WEAK_SCALING { + + @Override + public float applyLoss(float value, float factorX, float factorY, int timePassed) { + for (int i = 0; i < timePassed; i++) { + if (value < 0) value += factorX * Math.pow(-value, factorY); + else if (value > 0) value -= factorX * Math.pow(value, factorY); + } + return tolerate(value); + } + }; + + public static final float TOLERANCE = 0.1f; + + protected float tolerate(float value) { + return Math.abs(value) < TOLERANCE ? 0 : value; + } + + public abstract float applyLoss(float value, float factorX, float factorY, int timePassed); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java new file mode 100644 index 0000000000..338d8410dc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -0,0 +1,328 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; + +import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.logic.INetLogicEntryListener; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossResult; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.CompleteLossOperator; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; +import gregtech.client.particle.GTOverheatParticle; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.FMLCommonHandler; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; + +public final class TemperatureLogic extends NetLogicEntry { + + public static final TemperatureLogic INSTANCE = new TemperatureLogic(); + + public static final int DEFAULT_TEMPERATURE = 298; + + private WeakReference netListener; + private boolean isMultiNodeHelper = false; + + private int temperatureMaximum; + private @Nullable Integer partialBurnTemperature; + private int temperatureMinimum; + private float energy; + private int thermalMass; + + private @NotNull TemperatureLossFunction temperatureLossFunction = new TemperatureLossFunction(); + private int functionPriority; + private long lastRestorationTick; + + private TemperatureLogic() { + super("Temperature"); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum) { + return getWith(temperatureRestorationFunction, temperatureMaximum, 1); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum) { + return getWith(temperatureRestorationFunction, temperatureMaximum, temperatureMinimum, 1000); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum, int thermalMass) { + return getWith(temperatureRestorationFunction, temperatureMaximum, temperatureMinimum, thermalMass, 0); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum, int thermalMass, + @Nullable Integer partialBurnTemperature) { + return getWith(temperatureRestorationFunction, temperatureMaximum, temperatureMinimum, thermalMass, + partialBurnTemperature, 0); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum, int thermalMass, + @Nullable Integer partialBurnTemperature, int functionPriority) { + return getNew() + .setRestorationFunction(temperatureRestorationFunction) + .setTemperatureMaximum(temperatureMaximum) + .setTemperatureMinimum(temperatureMinimum) + .setThermalMass(thermalMass) + .setPartialBurnTemperature(partialBurnTemperature) + .setFunctionPriority(functionPriority); + } + + @Override + public void registerToMultiNodeHelper(MultiNodeHelper helper) { + this.isMultiNodeHelper = true; + this.netListener = new WeakReference<>(helper); + } + + @Override + public void registerToNetLogicData(NetLogicData data) { + if (!isMultiNodeHelper) this.netListener = new WeakReference<>(data); + } + + @Override + public void deregisterFromNetLogicData(NetLogicData data) { + if (!isMultiNodeHelper) this.netListener = new WeakReference<>(null); + } + + public @NotNull TemperatureLogic getNew() { + return new TemperatureLogic(); + } + + public boolean isOverMaximum(int temperature) { + return temperature > getTemperatureMaximum(); + } + + public boolean isOverPartialBurnThreshold(int temperature) { + return getPartialBurnTemperature() != null && temperature > getPartialBurnTemperature(); + } + + public boolean isUnderMinimum(int temperature) { + return temperature < getTemperatureMinimum(); + } + + @Nullable + public NodeLossResult getLossResult(long tick) { + int temp = getTemperature(tick); + if (isUnderMinimum(temp)) { + return new NodeLossResult(n -> { + World world = n.getNet().getLevel(); + BlockPos pos = n.getEquivalencyData(); + IBlockState state = world.getBlockState(pos); + if (state.getBlock() instanceof IFreezable freezable) { + freezable.fullyFreeze(state, world, pos); + } else { + world.setBlockToAir(pos); + } + }, CompleteLossOperator.INSTANCE); + } else if (isOverMaximum(temp)) { + return new NodeLossResult(n -> { + World world = n.getNet().getLevel(); + BlockPos pos = n.getEquivalencyData(); + IBlockState state = world.getBlockState(pos); + if (state.getBlock() instanceof IBurnable burnable) { + burnable.fullyBurn(state, world, pos); + } else { + world.setBlockToAir(pos); + } + }, CompleteLossOperator.INSTANCE); + } else if (isOverPartialBurnThreshold(temp)) { + return new NodeLossResult(n -> { + World world = n.getNet().getLevel(); + BlockPos pos = n.getEquivalencyData(); + IBlockState state = world.getBlockState(pos); + if (state.getBlock() instanceof IBurnable burnable) { + burnable.partialBurn(state, world, pos); + } + }, MultLossOperator.TENTHS[5]); + } else { + return null; + } + } + + public void applyThermalEnergy(float energy, long tick) { + restoreTemperature(tick); + this.energy += energy; + // since the decay logic is synced and deterministic, + // the only time client and server will desync is on external changes. + INetLogicEntryListener listener = this.netListener.get(); + if (listener != null) listener.markLogicEntryAsUpdated(this, false); + } + + public void moveTowardsTemperature(int temperature, long tick, float mult, boolean noParticle) { + int temp = getTemperature(tick); + float thermalEnergy = mult * (temperature - temp); + if (noParticle) { + float thermalMax = this.thermalMass * (GTOverheatParticle.TEMPERATURE_CUTOFF - DEFAULT_TEMPERATURE); + if (thermalMax > this.energy) return; + if (thermalEnergy + this.energy > thermalMax) { + thermalEnergy = thermalMax - this.energy; + } + } + if (thermalEnergy > 0) applyThermalEnergy(thermalEnergy, tick); + } + + public int getTemperature(long tick) { + restoreTemperature(tick); + return (int) (this.energy / this.thermalMass) + DEFAULT_TEMPERATURE; + } + + private void restoreTemperature(long tick) { + long timePassed = tick - lastRestorationTick; + this.lastRestorationTick = tick; + float energy = this.energy; + if (timePassed != 0) { + if (timePassed >= Integer.MAX_VALUE || timePassed < 0) { + this.energy = 0; + } else this.energy = temperatureLossFunction + .restoreTemperature(energy, (int) timePassed); + } + } + + public TemperatureLogic setRestorationFunction(TemperatureLossFunction temperatureRestorationFunction) { + this.temperatureLossFunction = temperatureRestorationFunction; + return this; + } + + public TemperatureLossFunction getRestorationFunction() { + return temperatureLossFunction; + } + + public TemperatureLogic setFunctionPriority(int functionPriority) { + this.functionPriority = functionPriority; + return this; + } + + public int getFunctionPriority() { + return functionPriority; + } + + public TemperatureLogic setTemperatureMaximum(int temperatureMaximum) { + this.temperatureMaximum = temperatureMaximum; + return this; + } + + public int getTemperatureMaximum() { + return temperatureMaximum; + } + + public TemperatureLogic setPartialBurnTemperature(@Nullable Integer partialBurnTemperature) { + this.partialBurnTemperature = partialBurnTemperature; + return this; + } + + public @Nullable Integer getPartialBurnTemperature() { + return partialBurnTemperature; + } + + public TemperatureLogic setTemperatureMinimum(int temperatureMinimum) { + this.temperatureMinimum = temperatureMinimum; + return this; + } + + public int getTemperatureMinimum() { + return temperatureMinimum; + } + + public TemperatureLogic setThermalMass(int thermalMass) { + this.thermalMass = thermalMass; + return this; + } + + public int getThermalMass() { + return thermalMass; + } + + @Override + public boolean mergedToMultiNodeHelper() { + return true; + } + + @Override + public void merge(NetNode otherOwner, NetLogicEntry unknown) { + if (!(unknown instanceof TemperatureLogic other)) return; + if (other.getTemperatureMinimum() > this.getTemperatureMinimum()) + this.setTemperatureMinimum(other.getTemperatureMinimum()); + if (other.getTemperatureMaximum() < this.getTemperatureMaximum()) + this.setTemperatureMaximum(other.getTemperatureMaximum()); + // since merge also occurs during nbt load, ignore the other's thermal energy. + if (other.getThermalMass() < this.getThermalMass()) this.setThermalMass(other.getThermalMass()); + if (other.getFunctionPriority() > this.getFunctionPriority()) { + this.setRestorationFunction(other.getRestorationFunction()); + this.setFunctionPriority(other.getFunctionPriority()); + } + if (other.getPartialBurnTemperature() != null && (this.getPartialBurnTemperature() == null || + other.getPartialBurnTemperature() < this.getPartialBurnTemperature())) + this.setPartialBurnTemperature(other.getPartialBurnTemperature()); + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + tag.setFloat("ThermalEnergy", this.energy); + tag.setInteger("TemperatureMax", this.temperatureMaximum); + tag.setInteger("TemperatureMin", this.temperatureMinimum); + tag.setInteger("ThermalMass", this.thermalMass); + tag.setTag("RestorationFunction", this.temperatureLossFunction.serializeNBT()); + tag.setInteger("FunctionPrio", this.functionPriority); + if (partialBurnTemperature != null) tag.setInteger("PartialBurn", partialBurnTemperature); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + this.energy = nbt.getFloat("ThermalEnergy"); + this.temperatureMaximum = nbt.getInteger("TemperatureMax"); + this.temperatureMinimum = nbt.getInteger("TemperatureMin"); + this.thermalMass = nbt.getInteger("ThermalMass"); + this.temperatureLossFunction = new TemperatureLossFunction(nbt.getCompoundTag("RestorationFunction")); + this.functionPriority = nbt.getInteger("FunctionPrio"); + if (nbt.hasKey("PartialBurn")) { + this.partialBurnTemperature = nbt.getInteger("PartialBurn"); + } else this.partialBurnTemperature = null; + } + + @Override + public void encode(PacketBuffer buf, boolean fullChange) { + buf.writeFloat(this.energy); + if (fullChange) { + buf.writeVarInt(this.temperatureMaximum); + buf.writeVarInt(this.temperatureMinimum); + buf.writeVarInt(this.thermalMass); + this.temperatureLossFunction.encode(buf); + buf.writeVarInt(this.functionPriority); + // laughs in java 9 + // noinspection ReplaceNullCheck + if (this.partialBurnTemperature == null) buf.writeVarInt(-1); + else buf.writeVarInt(this.partialBurnTemperature); + } + } + + @Override + public void decode(PacketBuffer buf, boolean fullChange) { + this.lastRestorationTick = FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter(); + this.energy = buf.readFloat(); + if (fullChange) { + this.temperatureMaximum = buf.readVarInt(); + this.temperatureMinimum = buf.readVarInt(); + this.thermalMass = buf.readVarInt(); + this.temperatureLossFunction.decode(buf); + this.functionPriority = buf.readVarInt(); + int partialBurn = buf.readVarInt(); + if (partialBurn != -1) this.partialBurnTemperature = partialBurn; + else this.partialBurnTemperature = null; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java new file mode 100644 index 0000000000..0709b6a9a8 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java @@ -0,0 +1,89 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; + +import gregtech.api.network.IPacket; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.common.util.INBTSerializable; + +import it.unimi.dsi.fastutil.floats.Float2ObjectArrayMap; + +public class TemperatureLossFunction implements INBTSerializable, IPacket { + + private static final Float2ObjectArrayMap CABLE_LOSS_CACHE = new Float2ObjectArrayMap<>(); + private static final Float2ObjectArrayMap PIPE_LOSS_CACHE = new Float2ObjectArrayMap<>(); + + private EnumLossFunction function; + private float factorX; + private float factorY; + + public TemperatureLossFunction(EnumLossFunction function, float factorX) { + this.function = function; + this.factorX = factorX; + } + + public TemperatureLossFunction(EnumLossFunction function, float factorX, float factorY) { + this.function = function; + this.factorX = factorX; + this.factorY = factorY; + } + + public TemperatureLossFunction() {} + + public TemperatureLossFunction(CompoundTag tag) { + deserializeNBT(tag); + } + + public float restoreTemperature(float energy, int timePassed) { + return function.applyLoss(energy, factorX, factorY, timePassed); + } + + public static TemperatureLossFunction getOrCreateCable(float factor) { + TemperatureLossFunction function = CABLE_LOSS_CACHE.get(factor); + if (function == null) { + function = new TemperatureLossFunction(EnumLossFunction.WEAK_SCALING, factor, 0.35f); + CABLE_LOSS_CACHE.put(factor, function); + } + return function; + } + + public static TemperatureLossFunction getOrCreatePipe(float factor) { + TemperatureLossFunction function = PIPE_LOSS_CACHE.get(factor); + if (function == null) { + // since pipes are hollow the exponent is larger + function = new TemperatureLossFunction(EnumLossFunction.WEAK_SCALING, factor, 0.45f); + PIPE_LOSS_CACHE.put(factor, function); + } + return function; + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + tag.setInteger("Ordinal", function.ordinal()); + tag.setFloat("X", factorX); + if (factorY != 0) tag.setFloat("Y", factorY); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + function = EnumLossFunction.values()[nbt.getInteger("Ordinal")]; + factorX = nbt.getFloat("X"); + factorY = nbt.getFloat("Y"); + } + + @Override + public void encode(PacketBuffer buf) { + buf.writeVarInt(function.ordinal()); + buf.writeFloat(factorX); + buf.writeFloat(factorY); + } + + @Override + public void decode(PacketBuffer buf) { + function = EnumLossFunction.values()[buf.readVarInt()]; + factorX = buf.readFloat(); + factorY = buf.readFloat(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java new file mode 100644 index 0000000000..9438bc3d2f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java @@ -0,0 +1,23 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +public interface IBurnable { + + /** + * Called when the block should be partially burned.
+ * Allows for partial burns with reference to temperature logic, used in insulated cables for example. + */ + default void partialBurn(IBlockState state, World world, BlockPos pos) {} + + /** + * Called when the block should be fully burned. + */ + default void fullyBurn(IBlockState state, World world, BlockPos pos) { + assert Blocks.FIRE != null; + world.setBlockState(pos, Blocks.FIRE.getDefaultState()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java new file mode 100644 index 0000000000..a23f1c3f16 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java @@ -0,0 +1,17 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +public interface IFreezable { + + /** + * Called when the block should be fully frozen. + */ + default void fullyFreeze(IBlockState state, World world, BlockPos pos) { + assert Blocks.FROSTED_ICE != null; + world.setBlockState(pos, Blocks.FROSTED_ICE.getDefaultState()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IInsulatable.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IInsulatable.java new file mode 100644 index 0000000000..0b51c49317 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IInsulatable.java @@ -0,0 +1,6 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +public interface IInsulatable { + + boolean isInsulated(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java new file mode 100644 index 0000000000..d57ed7312e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java @@ -0,0 +1,17 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; + +import net.minecraft.util.Direction; +import net.minecraftforge.common.capabilities.Capability; + +import org.jetbrains.annotations.Nullable; + +public interface IPipeCapabilityObject { + + void setTile(PipeBlockEntity tile); + + Capability[] getCapabilities(); + + T getCapabilityForSide(Capability capability, @Nullable Direction facing); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeChanneledStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeChanneledStructure.java new file mode 100644 index 0000000000..247a8f4a7b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeChanneledStructure.java @@ -0,0 +1,6 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +public interface IPipeChanneledStructure extends IPipeStructure { + + int getChannelCount(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java new file mode 100644 index 0000000000..605027d4a6 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java @@ -0,0 +1,8 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +import gregtech.api.unification.ore.OrePrefix; + +public interface IPipeMaterialStructure extends IPipeStructure { + + OrePrefix getOrePrefix(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java new file mode 100644 index 0000000000..199009d0f3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -0,0 +1,63 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; + +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.Direction; +import net.minecraft.util.StringRepresentable; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +public interface IPipeStructure extends StringRepresentable { + + /** + * Used as reference for misc things, e.g. rendering the backing of a cover. + * + * @return render thickness + */ + float getRenderThickness(); + + boolean isPaintable(); + + AbstractPipeModel getModel(); + + /** + * Allows for controlling what sides can be connected to based on current connections, + * such as in the case of optical and laser pipes. + */ + default boolean canConnectTo(Direction side, byte connectionMask) { + return true; + } + + @Contract("_ -> new") + default VoxelShape getPipeBoxes(@NotNull PipeBlockEntity tileContext) { + VoxelShape pipeBoxes = Shapes.empty(); + float thickness = getRenderThickness(); + if ((tileContext.getConnectionMask() & 63) < 63) { + pipeBoxes = Shapes.or(pipeBoxes, getSideBox(null, thickness)); + } + for (Direction facing : GTUtil.DIRECTIONS) { + if (tileContext.isConnected(facing)) + pipeBoxes = Shapes.or(pipeBoxes, getSideBox(facing, thickness)); + } + return pipeBoxes; + } + + static VoxelShape getSideBox(Direction side, float thickness) { + float min = (1.0f - thickness) / 2.0f, max = min + thickness; + float faceMin = 0f, faceMax = 1f; + + if (side == null) + return Shapes.box(min, min, min, max, max, max); + return switch (side) { + case WEST -> Shapes.box(faceMin, min, min, min, max, max); + case EAST -> Shapes.box(max, min, min, faceMax, max, max); + case NORTH -> Shapes.box(min, min, faceMin, max, max, min); + case SOUTH -> Shapes.box(min, min, max, max, max, faceMax); + case UP -> Shapes.box(min, max, min, max, faceMax, max); + case DOWN -> Shapes.box(min, faceMin, min, max, min, max); + }; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java new file mode 100644 index 0000000000..7dfe3e8f6c --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -0,0 +1,35 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +import gregtech.api.util.GTUtility; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +public final class PipeStructureRegistry { + + private static final Map, Set> REGISTRY = new Object2ObjectLinkedOpenHashMap<>(); + + public static void register(@NotNull T structure) { + Set structures = (Set) REGISTRY.get(structure.getClass()); + if (structures == null) { + structures = new LinkedHashSet<>(); + REGISTRY.put(structure.getClass(), structures); + } + structures.add(structure); + } + + /** + * Do not modify the returned set. + */ + public static @NotNull Set getStructures(Class structureClass) { + GTUtility.forceInitialization(structureClass); + Set structures = (Set) REGISTRY.get(structureClass); + if (structures == null) return Collections.emptySet(); + return structures; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java new file mode 100644 index 0000000000..d9b3819484 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java @@ -0,0 +1,32 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import gregtech.api.unification.material.Material; + +import net.minecraft.item.ItemStack; + +import org.jetbrains.annotations.NotNull; + +public class ItemMaterialPipeBlock extends ItemPipeBlock { + + public ItemMaterialPipeBlock(PipeMaterialBlock block) { + super(block); + setHasSubtypes(true); + } + + @Override + public int getMetadata(int damage) { + return damage; + } + + @Override + public @NotNull PipeMaterialBlock getBlock() { + return (PipeMaterialBlock) super.getBlock(); + } + + @NotNull + @Override + public String getItemStackDisplayName(@NotNull ItemStack stack) { + Material material = getBlock().getMaterialForStack(stack); + return material == null ? "unnamed" : getBlock().getStructure().getOrePrefix().getLocalNameForItem(material); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java new file mode 100644 index 0000000000..4da96e50b4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java @@ -0,0 +1,51 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import gregtech.common.items.MetaItems; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.Player; +import net.minecraft.item.EnumDyeColor; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.util.Direction; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import org.jetbrains.annotations.NotNull; + +public class ItemPipeBlock extends ItemBlock { + + public ItemPipeBlock(PipeBlock block) { + super(block); + } + + @Override + public @NotNull PipeBlock getBlock() { + return (PipeBlock) super.getBlock(); + } + + @Override + public boolean placeBlockAt(@NotNull ItemStack stack, @NotNull Player player, @NotNull World world, + @NotNull BlockPos pos, @NotNull Direction side, + float hitX, float hitY, float hitZ, @NotNull IBlockState newState) { + if (super.placeBlockAt(stack, player, world, pos, side, hitX, hitY, hitZ, newState)) { + ItemStack offhand = player.getHeldItemOffhand(); + for (int i = 0; i < EnumDyeColor.values().length; i++) { + if (offhand.isItemEqual(MetaItems.SPRAY_CAN_DYES[i].getStackForm())) { + MetaItems.SPRAY_CAN_DYES[i].getBehaviours().get(0).onItemUse(player, world, + pos, EnumHand.OFF_HAND, Direction.UP, 0, 0, 0); + break; + } + } + + PipeBlockEntity tile = getBlock().getTileEntity(world, pos); + if (tile != null) { + tile.placedBy(stack, player); + getBlock().doPlacementLogic(tile, side.getOpposite()); + } + return true; + } else return false; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java new file mode 100644 index 0000000000..2a91fb81fa --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java @@ -0,0 +1,50 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeActivableBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.pipe.ActivablePipeModel; + +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; + +public abstract class PipeActivableBlock extends PipeBlock { + + public PipeActivableBlock(IPipeStructure structure) { + super(structure); + } + + @Override + protected @NotNull BlockStateContainer.Builder constructState(BlockStateContainer.@NotNull Builder builder) { + return super.constructState(builder).add(ActivablePipeModel.ACTIVE_PROPERTY); + } + + @Override + public Class getTileClass(@NotNull World world, @NotNull IBlockState state) { + return PipeActivableBlockEntity.class; + } + + @Override + public @Nullable PipeActivableBlockEntity getTileEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { + if (GTUtility.arePosEqual(lastTilePos.get(), pos)) { + PipeBlockEntity tile = lastTile.get().get(); + if (tile != null && !tile.isInvalid()) return (PipeActivableBlockEntity) tile; + } + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof PipeActivableBlockEntity pipe) { + lastTilePos.set(pos.toImmutable()); + lastTile.set(new WeakReference<>(pipe)); + return pipe; + } else return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java new file mode 100644 index 0000000000..be5f62b220 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -0,0 +1,767 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import gregtech.api.block.BuiltInRenderBlock; +import gregtech.api.cover.Cover; +import gregtech.api.cover.CoverRayTracer; +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeChanneledStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCoverHolder; +import gregtech.api.items.toolitem.ToolClasses; +import gregtech.api.items.toolitem.ToolHelper; +import gregtech.api.unification.material.Material; +import gregtech.api.util.EntityDamageUtil; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.pipe.AbstractPipeModel; +import gregtech.client.renderer.pipe.cover.CoverRendererPackage; +import gregtech.client.utils.BloomEffectUtil; +import gregtech.client.utils.TooltipHelper; +import gregtech.common.ConfigHolder; +import gregtech.common.blocks.BlockFrame; +import gregtech.common.blocks.MetaBlocks; + +import net.minecraft.block.Block; +import net.minecraft.block.SoundType; +import net.minecraft.block.properties.PropertyBool; +import net.minecraft.block.state.BlockFaceShape; +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.I18n; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.Player; +import net.minecraft.item.EnumDyeColor; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockRenderLayer; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.Direction; +import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; +import net.minecraft.util.SoundCategory; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.property.IExtendedBlockState; +import net.minecraftforge.fml.common.FMLCommonHandler; + +import codechicken.lib.raytracer.RayTracer; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; +import java.util.Collection; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public abstract class PipeBlock extends BuiltInRenderBlock { + + public static final PropertyBool NORTH = PropertyBool.create("north"); + public static final PropertyBool EAST = PropertyBool.create("east"); + public static final PropertyBool SOUTH = PropertyBool.create("south"); + public static final PropertyBool WEST = PropertyBool.create("west"); + public static final PropertyBool UP = PropertyBool.create("up"); + public static final PropertyBool DOWN = PropertyBool.create("down"); + + public static final EnumMap FACINGS = buildFacings(); + + private static @NotNull EnumMap buildFacings() { + EnumMap map = new EnumMap<>(Direction.class); + map.put(Direction.NORTH, NORTH); + map.put(Direction.EAST, EAST); + map.put(Direction.SOUTH, SOUTH); + map.put(Direction.WEST, WEST); + map.put(Direction.UP, UP); + map.put(Direction.DOWN, DOWN); + return map; + } + + public static final PropertyBool FRAMED = PropertyBool.create("framed"); + + // do not touch these two unless you know what you are doing + protected final ThreadLocal lastTilePos = ThreadLocal.withInitial(() -> new BlockPos(0, 0, 0)); + protected final ThreadLocal> lastTile = ThreadLocal + .withInitial(() -> new WeakReference<>(null)); + + private final IPipeStructure structure; + + public PipeBlock(IPipeStructure structure) { + super(net.minecraft.block.material.Material.IRON); + this.structure = structure; + setTranslationKey(structure.getName()); + setSoundType(SoundType.METAL); + setHardness(2.0f); + setHarvestLevel(getToolClass(), 1); + setResistance(3.0f); + setLightOpacity(1); + disableStats(); + } + + public IPipeStructure getStructure() { + return structure; + } + + // net logic // + + public void doPlacementLogic(PipeBlockEntity tile, Direction placedBlockSearchSide) { + for (Direction facing : GTUtil.DIRECTIONS) { + TileEntity neighbor = tile.getNeighbor(facing); + if (neighbor instanceof PipeBlockEntity other) { + // first check -- does the other tile have a cover that would prevent connection + Cover cover = other.getCoverHolder().getCoverAtSide(facing.getOpposite()); + if (cover != null && !cover.canPipePassThrough()) continue; + // second check -- connect to matching mark pipes if side matches or config allows. + if (tile.getPaintingColor() == other.getPaintingColor() && (facing == placedBlockSearchSide || + !ConfigHolder.machines.gt6StylePipesCables)) { + if (coverCheck(tile, other, facing)) connectTile(tile, other, facing); + continue; + } + // third check -- connect to pipes with an open connection, no matter the mark status. + if (other.isConnected(facing.getOpposite())) { + if (coverCheck(tile, other, facing)) connectTile(tile, other, facing); + } + } else if (facing == placedBlockSearchSide) { + // if the placed on tile supports one of our capabilities, connect to it. + tile.updateActiveStatus(facing, true); + } + } + } + + @Override + public boolean onBlockActivated(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull IBlockState state, + @NotNull Player playerIn, @NotNull EnumHand hand, @NotNull Direction facing, + float hitX, float hitY, float hitZ) { + ItemStack item = playerIn.getHeldItem(hand); + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile != null) { + if (tile.getFrameMaterial() == null) { + BlockFrame frame = BlockFrame.getFrameBlockFromItem(item); + if (frame != null) { + tile.setFrameMaterial(frame.getGtMaterial(item)); + SoundType type = frame.getSoundType(item); + worldIn.playSound(playerIn, pos, type.getPlaceSound(), SoundCategory.BLOCKS, + (type.getVolume() + 1.0F) / 2.0F, type.getPitch() * 0.8F); + if (!playerIn.capabilities.isCreativeMode) { + item.shrink(1); + } + return true; + } + } + + RayTraceAABB trace = collisionRayTrace(playerIn, worldIn, pos); + if (trace == null) + return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ); + + Direction actualSide = CoverRayTracer.determineGridSideHit(trace); + if (actualSide != null) facing = actualSide; + + // cover comes first + PipeCoverHolder coverable = tile.getCoverHolder(); + Cover cover = coverable.getCoverAtSide(facing); + if (cover != null) { + if (ToolHelper.isTool(item, ToolClasses.SCREWDRIVER)) { + EnumActionResult result = cover.onScrewdriverClick(playerIn, hand, trace); + if (result != EnumActionResult.PASS) { + if (result == EnumActionResult.SUCCESS) { + ToolHelper.damageItem(item, playerIn); + ToolHelper.playToolSound(item, playerIn); + return true; + } + return false; + } + } + if (ToolHelper.isTool(item, ToolClasses.SOFT_MALLET)) { + EnumActionResult result = cover.onSoftMalletClick(playerIn, hand, trace); + if (result != EnumActionResult.PASS) { + if (result == EnumActionResult.SUCCESS) { + ToolHelper.damageItem(item, playerIn); + ToolHelper.playToolSound(item, playerIn); + return true; + } + return false; + } + } + EnumActionResult result = cover.onRightClick(playerIn, hand, trace); + if (result == EnumActionResult.SUCCESS) return true; + + // allow crowbar to run even if the right click returns a failure + if (ToolHelper.isTool(item, ToolClasses.CROWBAR)) { + coverable.removeCover(facing); + ToolHelper.damageItem(item, playerIn); + ToolHelper.playToolSound(item, playerIn); + return true; + } + + if (result == EnumActionResult.FAIL) return false; + } + // frame removal + Material frame = tile.getFrameMaterial(); + if (frame != null && ToolHelper.isTool(item, ToolClasses.CROWBAR)) { + tile.setFrameMaterial(null); + spawnAsEntity(worldIn, pos, MetaBlocks.FRAMES.get(frame).getItem(frame)); + ToolHelper.damageItem(item, playerIn); + ToolHelper.playToolSound(item, playerIn); + return true; + } + // pipe modification + if (isPipeTool(item)) { + PipeBlockEntity other = tile.getPipeNeighbor(facing, true); + + if (playerIn.isSneaking() && allowsBlocking()) { + ToolHelper.damageItem(item, playerIn); + ToolHelper.playToolSound(item, playerIn); + if (tile.isBlocked(facing)) unblockTile(tile, other, facing); + else blockTile(tile, other, facing); + } else { + if (tile.isConnected(facing)) { + ToolHelper.damageItem(item, playerIn); + ToolHelper.playToolSound(item, playerIn); + disconnectTile(tile, other, facing); + } else if (coverCheck(tile, other, facing)) { + ToolHelper.damageItem(item, playerIn); + ToolHelper.playToolSound(item, playerIn); + connectTile(tile, other, facing); + } else { + // if the covers disallow the connection, simply try to render a connection. + connectTile(tile, null, facing); + } + } + return true; + } + } + return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ); + } + + @Override + public void onBlockClicked(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull Player playerIn) { + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile != null) { + RayTraceAABB trace = collisionRayTrace(playerIn, worldIn, pos); + if (trace == null) { + super.onBlockClicked(worldIn, pos, playerIn); + return; + } + Direction facing = trace.sideHit; + Direction actualSide = CoverRayTracer.determineGridSideHit(trace); + if (actualSide != null) facing = actualSide; + Cover cover = tile.getCoverHolder().getCoverAtSide(facing); + if (cover != null) { + if (cover.onLeftClick(playerIn, trace)) return; + } + } + super.onBlockClicked(worldIn, pos, playerIn); + } + + /** + * Should be called to verify if a connection can be formed before + * {@link #connectTile(PipeBlockEntity, PipeBlockEntity, Direction)} is called. + * + * @return whether the connection is allowed. + */ + public static boolean coverCheck(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, + Direction facing) { + Cover tileCover = tile.getCoverHolder().getCoverAtSide(facing); + Cover acrossCover = tileAcross != null ? tileAcross.getCoverHolder().getCoverAtSide(facing.getOpposite()) : + null; + return (tileCover == null || tileCover.canPipePassThrough()) && + (acrossCover == null || acrossCover.canPipePassThrough()); + } + + public static void connectTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, + Direction facing) { + // abort connection if either tile refuses it. + if (!tile.canConnectTo(facing) || tileAcross != null && !tileAcross.canConnectTo(facing.getOpposite())) return; + + // if one of the pipes is larger than the other, render it closed. + tile.setConnected(facing, tileAcross != null && + tile.getStructure().getRenderThickness() > tileAcross.getStructure().getRenderThickness()); + if (tileAcross == null) return; + tileAcross.setConnected(facing.getOpposite(), + tileAcross.getStructure().getRenderThickness() > tile.getStructure().getRenderThickness()); + if (tile.getWorld().isRemote) return; + + boolean blocked1 = tile.isBlocked(facing); + boolean blocked2 = tileAcross.isBlocked(facing.getOpposite()); + + Map tile2Nodes = new Object2ObjectOpenHashMap<>(); + for (WorldPipeNetNode node : getNodesForTile(tileAcross)) { + tile2Nodes.put(node.getNet(), node); + } + + for (WorldPipeNetNode node : getNodesForTile(tile)) { + WorldPipeNet net = node.getNet(); + WorldPipeNetNode other = tile2Nodes.get(net); + if (other == null) continue; + if (!blocked1 && !blocked2) { + net.addEdge(node, other, true); + } else if (net.getGraph().isDirected()) { + if (!blocked1) net.addEdge(other, node, false); + else if (!blocked2) net.addEdge(node, other, false); + } + } + } + + public static void disconnectTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, + Direction facing) { + tile.setDisconnected(facing); + if (tileAcross == null) return; + tileAcross.setDisconnected(facing.getOpposite()); + if (tile.getWorld().isRemote) return; + + Map tile2Nodes = new Object2ObjectOpenHashMap<>(); + for (WorldPipeNetNode node : getNodesForTile(tileAcross)) { + tile2Nodes.put(node.getNet(), node); + } + + for (WorldPipeNetNode node : getNodesForTile(tile)) { + WorldPipeNet net = node.getNet(); + WorldPipeNetNode other = tile2Nodes.get(net); + if (other == null) continue; + net.removeEdge(node, other, true); + } + } + + public static void blockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, Direction facing) { + tile.setBlocked(facing); + if (tileAcross == null || tile.getWorld().isRemote) return; + + Map tile2Nodes = new Object2ObjectOpenHashMap<>(); + for (WorldPipeNetNode node : getNodesForTile(tileAcross)) { + tile2Nodes.put(node.getNet(), node); + } + + for (WorldPipeNetNode node : getNodesForTile(tile)) { + WorldPipeNet net = node.getNet(); + WorldPipeNetNode other = tile2Nodes.get(net); + if (other == null) continue; + net.removeEdge(other, node, false); + } + } + + public static void unblockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, + Direction facing) { + tile.setUnblocked(facing); + if (tileAcross == null || tile.getWorld().isRemote) return; + + Map tile2Nodes = new Object2ObjectOpenHashMap<>(); + for (WorldPipeNetNode node : getNodesForTile(tileAcross)) { + tile2Nodes.put(node.getNet(), node); + } + + for (WorldPipeNetNode node : getNodesForTile(tile)) { + WorldPipeNet net = node.getNet(); + WorldPipeNetNode other = tile2Nodes.get(net); + if (other == null) continue; + net.addEdge(other, node, false); + } + } + + protected boolean allowsBlocking() { + return true; + } + + public static Collection getNodesForTile(PipeBlockEntity tile) { + assert !tile.getWorld().isRemote; + return tile.getBlockType().getHandler(tile.getWorld(), tile.getPos()) + .getOrCreateFromNets(tile.getWorld(), tile.getPos(), tile.getStructure()); + } + + @Override + public void breakBlock(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull IBlockState state) { + super.breakBlock(worldIn, pos, state); + if (!worldIn.isRemote) { + getHandler(worldIn, pos).removeFromNets(worldIn, pos, getStructure()); + } + } + + @NotNull + protected abstract IPipeNetNodeHandler getHandler(IBlockAccess world, BlockPos pos); + + @NotNull + protected abstract IPipeNetNodeHandler getHandler(@NotNull ItemStack stack); + + // misc stuff // + + @Override + public void addInformation(@NotNull ItemStack stack, World worldIn, @NotNull List tooltip, + @NotNull ITooltipFlag flagIn) { + if (getStructure() instanceof IPipeChanneledStructure channeledStructure) { + if (channeledStructure.getChannelCount() > 1) + tooltip.add(I18n.format("gregtech.pipe.channels", channeledStructure.getChannelCount())); + } + getHandler(stack).addInformation(stack, worldIn, tooltip, flagIn, getStructure()); + if (TooltipHelper.isShiftDown()) { + tooltip.add(I18n.format(getConnectLangKey())); + tooltip.add(I18n.format("gregtech.tool_action.screwdriver.access_covers")); + tooltip.add(I18n.format("gregtech.tool_action.crowbar")); + } else { + tooltip.add(I18n.format("gregtech.tool_action.show_tooltips")); + } + } + + protected String getConnectLangKey() { + return "gregtech.tool_action.wrench.connect_and_block"; + } + + @Override + public void getDrops(@NotNull NonNullList drops, @NotNull IBlockAccess world, @NotNull BlockPos pos, + @NotNull IBlockState state, int fortune) { + PipeBlockEntity tile = getTileEntity(world, pos); + if (tile != null) tile.getDrops(drops, state); + } + + @Override + public boolean canCreatureSpawn(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos, + @NotNull EntityLiving.SpawnPlacementType type) { + return false; + } + + @Override + public void onEntityCollision(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull IBlockState state, + @NotNull Entity entityIn) { + if (worldIn.isRemote || !(entityIn instanceof EntityLivingBase living)) return; + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile != null && tile.getFrameMaterial() == null && tile.getOffsetTimer() % 10 == 0) { + TemperatureLogic logic = tile.getTemperatureLogic(); + if (logic != null) { + long tick = FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter(); + EntityDamageUtil.applyTemperatureDamage(living, logic.getTemperature(tick), 1f, 5); + } + } + } + + @Override + public boolean recolorBlock(@NotNull World world, @NotNull BlockPos pos, @NotNull Direction side, + @NotNull EnumDyeColor color) { + if (getStructure().isPaintable()) { + PipeBlockEntity tile = getTileEntity(world, pos); + if (tile != null && tile.getPaintingColor() != color.colorValue) { + tile.setPaintingColor(color.colorValue, false); + return true; + } + } + return false; + } + + @Override + public boolean canRenderInLayer(@NotNull IBlockState state, @NotNull BlockRenderLayer layer) { + // guaranteed cutout & bloom for covers + return layer == BlockRenderLayer.CUTOUT_MIPPED || layer == BloomEffectUtil.getEffectiveBloomLayer() || + getStructure().getModel().canRenderInLayer(layer); + } + + @Override + protected Pair getParticleTexture(World world, BlockPos blockPos) { + PipeBlockEntity tile = getTileEntity(world, blockPos); + if (tile != null) { + return getStructure().getModel().getParticleTexture(tile.getPaintingColor(), null); + } + return null; + } + + // collision boxes // + + @SuppressWarnings("deprecation") + @Override + public @NotNull AxisAlignedBB getSelectedBoundingBox(@NotNull IBlockState state, @NotNull World worldIn, + @NotNull BlockPos pos) { + RayTraceAABB trace = this.collisionRayTrace(GTUtility.getSP(), worldIn, pos); + return (trace == null || trace.getBB() == null ? FULL_BLOCK_AABB : trace.getBB()).offset(pos); + } + + @SuppressWarnings("deprecation") + @Override + public void addCollisionBoxToList(@NotNull IBlockState state, @NotNull World worldIn, @NotNull BlockPos pos, + @NotNull AxisAlignedBB entityBox, @NotNull List collidingBoxes, + @Nullable Entity entityIn, boolean isActualState) { + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile != null) { + tile.getCoverBoxes(bb -> addCollisionBoxToList(pos, entityBox, collidingBoxes, bb)); + if (tile.getFrameMaterial() != null) { + addCollisionBoxToList(pos, entityBox, collidingBoxes, BlockFrame.COLLISION_BOX); + } + for (AxisAlignedBB axisAlignedBB : getStructure().getPipeBoxes(tile)) { + addCollisionBoxToList(pos, entityBox, collidingBoxes, axisAlignedBB); + } + } else { + addCollisionBoxToList(pos, entityBox, collidingBoxes, FULL_BLOCK_AABB); + } + } + + @SuppressWarnings("deprecation") + @Nullable + @Override + public RayTraceResult collisionRayTrace(@NotNull IBlockState blockState, @NotNull World worldIn, + @NotNull BlockPos pos, + @NotNull Vec3d start, @NotNull Vec3d end) { + return collisionRayTrace(worldIn.isRemote ? GTUtility.getSP() : null, worldIn, pos, start, end); + } + + public @Nullable RayTraceAABB collisionRayTrace(@NotNull Player player, + @NotNull World world, @NotNull BlockPos pos) { + return collisionRayTrace(player, world, pos, RayTracer.getStartVec(player), RayTracer.getEndVec(player)); + } + + public @Nullable RayTraceAABB collisionRayTrace(@Nullable Player player, + @NotNull World worldIn, @NotNull BlockPos pos, + @NotNull Vec3d start, @NotNull Vec3d end) { + if (hasPipeCollisionChangingItem(worldIn, pos, player)) { + return RayTraceAABB.of(rayTrace(pos, start, end, FULL_BLOCK_AABB), FULL_BLOCK_AABB); + } + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile == null) { + return RayTraceAABB.of(rayTrace(pos, start, end, FULL_BLOCK_AABB), FULL_BLOCK_AABB); + } + RayTraceResult min = null; + AxisAlignedBB minbb = null; + double minDistSqrd = Double.MAX_VALUE; + List bbs = getStructure().getPipeBoxes(tile); + tile.getCoverBoxes(bbs::add); + if (tile.getFrameMaterial() != null) { + bbs.add(FULL_BLOCK_AABB); + } + for (AxisAlignedBB aabb : bbs) { + RayTraceResult result = rayTrace(pos, start, end, aabb); + if (result == null) continue; + double distSqrd = start.squareDistanceTo(result.hitVec); + if (distSqrd < minDistSqrd) { + min = result; + minbb = aabb; + minDistSqrd = distSqrd; + } + } + return RayTraceAABB.of(min, minbb); + } + + public boolean hasPipeCollisionChangingItem(IBlockAccess world, BlockPos pos, Entity entity) { + if (entity instanceof Player player) { + return hasPipeCollisionChangingItem(world, pos, player.getHeldItemMainhand()) || + hasPipeCollisionChangingItem(world, pos, player.getHeldItemOffhand()) || + entity.isSneaking() && isHoldingPipe(player); + } + return false; + } + + public boolean isHoldingPipe(Player player) { + return isPipeItem(player.getHeldItemMainhand()) || isPipeItem(player.getHeldItemOffhand()); + } + + public boolean isPipeItem(ItemStack stack) { + return stack.getItem() instanceof ItemPipeBlock block && this.getClass().isInstance(block.getBlock()); + } + + @Nullable + public static PipeBlock getBlockFromItem(@NotNull ItemStack stack) { + if (stack.getItem() instanceof ItemPipeBlock block) return block.getBlock(); + else return null; + } + + public boolean hasPipeCollisionChangingItem(IBlockAccess world, BlockPos pos, ItemStack stack) { + if (isPipeTool(stack)) return true; + + PipeBlockEntity tile = getTileEntity(world, pos); + if (tile == null) return false; + + PipeCoverHolder coverable = tile.getCoverHolder(); + final boolean hasAnyCover = coverable.hasAnyCover(); + + if (hasAnyCover && ToolHelper.isTool(stack, ToolClasses.SCREWDRIVER)) return true; + final boolean acceptsCovers = coverable.acceptsCovers(); + + return GTUtility.isCoverBehaviorItem(stack, () -> hasAnyCover, coverDef -> acceptsCovers); + } + + public boolean isPipeTool(@NotNull ItemStack stack) { + return ToolHelper.isTool(stack, getToolClass()); + } + + public String getToolClass() { + return ToolClasses.WRENCH; + } + + @SuppressWarnings("deprecation") + @Override + public @NotNull BlockFaceShape getBlockFaceShape(@NotNull IBlockAccess worldIn, @NotNull IBlockState state, + @NotNull BlockPos pos, @NotNull Direction face) { + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile != null) { + return tile.getCoverHolder().hasCover(face) ? BlockFaceShape.SOLID : + tile.isConnected(face) ? BlockFaceShape.CENTER : BlockFaceShape.UNDEFINED; + } + return super.getBlockFaceShape(worldIn, state, pos, face); + } + + // blockstate // + + @Override + public int getMetaFromState(@NotNull IBlockState state) { + return 0; + } + + @Override + protected @NotNull BlockStateContainer createBlockState() { + return constructState(new BlockStateContainer.Builder(this)) + .add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED) + .build(); + } + + protected @NotNull BlockStateContainer.Builder constructState(BlockStateContainer.@NotNull Builder builder) { + return builder.add(AbstractPipeModel.THICKNESS_PROPERTY).add(AbstractPipeModel.CLOSED_MASK_PROPERTY) + .add(AbstractPipeModel.BLOCKED_MASK_PROPERTY).add(AbstractPipeModel.COLOR_PROPERTY) + .add(AbstractPipeModel.FRAME_MATERIAL_PROPERTY).add(AbstractPipeModel.FRAME_MASK_PROPERTY) + .add(CoverRendererPackage.PROPERTY); + } + + @SuppressWarnings("deprecation") + @Override + public @NotNull IBlockState getActualState(@NotNull IBlockState state, @NotNull IBlockAccess worldIn, + @NotNull BlockPos pos) { + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile == null) return state; + state = writeConnectionMask(state, tile.getConnectionMask()); + return state.withProperty(FRAMED, tile.getFrameMaterial() != null); + } + + public static IBlockState writeConnectionMask(@NotNull IBlockState state, byte connectionMask) { + for (Direction facing : GTUtil.DIRECTIONS) { + state = state.withProperty(FACINGS.get(facing), GTUtility.evalMask(facing, connectionMask)); + } + return state; + } + + public static byte readConnectionMask(@NotNull IBlockState state) { + byte mask = 0; + for (Direction facing : GTUtil.DIRECTIONS) { + if (state.getValue(FACINGS.get(facing))) { + mask |= 1 << facing.ordinal(); + } + } + return mask; + } + + @Override + public @NotNull IBlockState getExtendedState(@NotNull IBlockState state, @NotNull IBlockAccess world, + @NotNull BlockPos pos) { + PipeBlockEntity tile = getTileEntity(world, pos); + if (tile == null) return state; + else return tile.getRenderInformation((IExtendedBlockState) state.getActualState(world, pos)); + } + + // tile entity // + + @Override + public final boolean hasTileEntity(@NotNull IBlockState state) { + return true; + } + + @Nullable + public PipeBlockEntity getTileEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { + if (GTUtility.arePosEqual(lastTilePos.get(), pos)) { + PipeBlockEntity tile = lastTile.get().get(); + if (tile != null && !tile.isInvalid()) return tile; + } + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof PipeBlockEntity pipe) { + lastTilePos.set(pos.toImmutable()); + lastTile.set(new WeakReference<>(pipe)); + return pipe; + } else return null; + } + + @Override + public final PipeBlockEntity createTileEntity(@NotNull World world, @NotNull IBlockState state) { + try { + // noinspection deprecation + return getTileClass(world, state).newInstance(); + } catch (Throwable ignored) { + return null; + } + } + + /** + * This may seem unnecessary, but it enforces empty constructors which are required due to + * {@link TileEntity#create(World, CompoundTag)} + */ + public Class getTileClass(@NotNull World world, @NotNull IBlockState state) { + return PipeBlockEntity.class; + } + + @Override + public void onNeighborChange(@NotNull IBlockAccess world, @NotNull BlockPos pos, @NotNull BlockPos neighbor) { + super.onNeighborChange(world, pos, neighbor); + Direction facing = GTUtility.getFacingToNeighbor(pos, neighbor); + if (facing == null) return; + PipeBlockEntity tile = getTileEntity(world, pos); + if (tile != null) tile.onNeighborChanged(facing); + } + + @Override + public int getLightValue(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos) { + PipeBlockEntity tile = getTileEntity(world, pos); + if (tile != null) { + TemperatureLogic temperatureLogic = tile.getTemperatureLogic(); + int temp = temperatureLogic == null ? 0 : temperatureLogic + .getTemperature(FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter()); + // max light at 5000 K + // min light at 500 K + if (temp >= 5000) { + return 15; + } + if (temp > 500) { + return (temp - 500) * 15 / (4500); + } + } + return 0; + } + + // cover compatibility // + + @SuppressWarnings("deprecation") + @Override + public void neighborChanged(@NotNull IBlockState state, @NotNull World worldIn, @NotNull BlockPos pos, + @NotNull Block blockIn, @NotNull BlockPos fromPos) { + PipeBlockEntity tile = getTileEntity(worldIn, pos); + if (tile != null) { + Direction facing = GTUtility.getFacingToNeighbor(pos, fromPos); + if (facing != null) tile.onNeighborChanged(facing); + tile.getCoverHolder().updateInputRedstoneSignals(); + } + } + + @Override + public boolean shouldCheckWeakPower(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos, + @NotNull Direction side) { + // The check in World::getRedstonePower in the vanilla code base is reversed. Setting this to false will + // actually cause getWeakPower to be called, rather than prevent it. + return false; + } + + @SuppressWarnings("deprecation") + @Override + public int getWeakPower(@NotNull IBlockState blockState, @NotNull IBlockAccess blockAccess, @NotNull BlockPos pos, + @NotNull Direction side) { + PipeBlockEntity tile = getTileEntity(blockAccess, pos); + return tile != null ? tile.getCoverHolder().getOutputRedstoneSignal(side) : 0; + } + + @Override + public boolean canConnectRedstone(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos, + Direction side) { + PipeBlockEntity tile = getTileEntity(world, pos); + return tile != null && tile.getCoverHolder().canConnectRedstone(side); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java new file mode 100644 index 0000000000..7ce659c34c --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -0,0 +1,140 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeMaterialTileEntity; +import gregtech.api.unification.material.Material; +import gregtech.api.unification.material.Materials; +import gregtech.api.unification.material.properties.PipeNetProperties; +import gregtech.api.unification.material.properties.PropertyKey; +import gregtech.api.unification.material.registry.MaterialRegistry; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.pipe.AbstractPipeModel; +import gregtech.common.ConfigHolder; + +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.Player; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; +import java.util.List; + +public abstract class PipeMaterialBlock extends PipeBlock { + + public final MaterialRegistry registry; + + public PipeMaterialBlock(IPipeMaterialStructure structure, MaterialRegistry registry) { + super(structure); + this.registry = registry; + } + + @Override + public void getSubBlocks(@NotNull CreativeTabs itemIn, @NotNull NonNullList items) { + for (Material material : registry) { + if (!getStructure().getOrePrefix().doGenerateItem(material)) continue; + PipeNetProperties properties = material.getProperty(PropertyKey.PIPENET_PROPERTIES); + if (properties != null && properties.generatesStructure(getStructure())) { + items.add(getItem(material)); + } + } + } + + @Override + public @NotNull ItemStack getPickBlock(@NotNull IBlockState state, @NotNull RayTraceResult target, + @NotNull World world, @NotNull BlockPos pos, @NotNull Player player) { + PipeMaterialTileEntity tile = getTileEntity(world, pos); + if (tile != null) return getItem(tile.getMaterial()); + else return super.getPickBlock(state, target, world, pos, player); + } + + @Override + public IPipeMaterialStructure getStructure() { + return (IPipeMaterialStructure) super.getStructure(); + } + + @NotNull + public ItemStack getItem(@NotNull Material material) { + return new ItemStack(this, 1, registry.getIDForObject(material)); + } + + @Nullable + public Material getMaterialForStack(@NotNull ItemStack stack) { + return registry.getObjectById(stack.getMetadata()); + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(IBlockAccess world, BlockPos pos) { + PipeMaterialTileEntity tile = getTileEntity(world, pos); + if (tile != null) return tile.getMaterial().getProperty(PropertyKey.PIPENET_PROPERTIES); + else return Materials.Aluminium.getProperty(PropertyKey.PIPENET_PROPERTIES); + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(@NotNull ItemStack stack) { + Material material = getMaterialForStack(stack); + if (material == null) material = Materials.Aluminium; + return material.getProperty(PropertyKey.PIPENET_PROPERTIES); + } + + @Override + public void addInformation(@NotNull ItemStack stack, World worldIn, @NotNull List tooltip, + @NotNull ITooltipFlag flagIn) { + super.addInformation(stack, worldIn, tooltip, flagIn); + if (ConfigHolder.misc.debug) { + Material material = getMaterialForStack(stack); + if (material != null) + tooltip.add("MetaItem Id: " + getStructure().getOrePrefix().name + material.toCamelCaseString()); + } + } + + // tile entity // + + @NotNull + @Override + protected BlockStateContainer.Builder constructState(BlockStateContainer.@NotNull Builder builder) { + return super.constructState(builder).add(AbstractPipeModel.MATERIAL_PROPERTY); + } + + @Override + public @Nullable PipeMaterialTileEntity getTileEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { + if (GTUtility.arePosEqual(lastTilePos.get(), pos)) { + PipeBlockEntity tile = lastTile.get().get(); + if (tile != null && !tile.isInvalid()) return (PipeMaterialTileEntity) tile; + } + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof PipeMaterialTileEntity pipe) { + lastTilePos.set(pos.toImmutable()); + lastTile.set(new WeakReference<>(pipe)); + return pipe; + } else return null; + } + + @Override + public Class getTileClass(@NotNull World world, @NotNull IBlockState state) { + return PipeMaterialTileEntity.class; + } + + @Override + protected Pair getParticleTexture(World world, BlockPos blockPos) { + PipeMaterialTileEntity tile = getTileEntity(world, blockPos); + if (tile != null) { + return getStructure().getModel().getParticleTexture(tile.getPaintingColor(), tile.getMaterial()); + } + return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java new file mode 100644 index 0000000000..8c3ca7c674 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java @@ -0,0 +1,35 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import net.minecraft.util.Direction; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.Nullable; + +/** + * A ray trace that additionally contains the {@link AxisAlignedBB} it hit. + */ +public class RayTraceAABB extends RayTraceResult { + + private final AxisAlignedBB bb; + + public RayTraceAABB(Type typeIn, Vec3d hitVecIn, Direction sideHitIn, BlockPos blockPosIn, AxisAlignedBB bb) { + super(typeIn, hitVecIn, sideHitIn, blockPosIn); + this.bb = bb; + } + + @Contract("null, _ -> null; !null, _ -> new") + public static RayTraceAABB of(@Nullable RayTraceResult result, AxisAlignedBB bb) { + if (result == null) return null; + if (result.typeOfHit == Type.ENTITY) + throw new IllegalArgumentException("Cannot create a RayTraceAABB for an entity hit!"); + return new RayTraceAABB(result.typeOfHit, result.hitVec, result.sideHit, result.getBlockPos(), bb); + } + + public AxisAlignedBB getBB() { + return bb; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IActivable.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IActivable.java new file mode 100644 index 0000000000..58d7666a0e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IActivable.java @@ -0,0 +1,8 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; + +public interface IActivable { + + void setActive(boolean active); + + boolean isActive(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java new file mode 100644 index 0000000000..7804a3555b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java @@ -0,0 +1,44 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; + +import com.gregtechceu.gtceu.api.capability.ICoverable; +import gregtech.api.cover.CoverableView; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Direction; +import net.minecraft.util.EnumParticleTypes; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumMap; +import java.util.function.Consumer; + +public interface IWorldPipeNetTile { + + // universal (mostly for active nodes) + + @NotNull + EnumMap getTargetsWithCapabilities(WorldPipeNetNode destination); + + @Nullable + TileEntity getTargetWithCapabilities(WorldPipeNetNode destination, Direction facing); + + PipeCapabilityWrapper getWrapperForNode(WorldPipeNetNode node); + + @NotNull + ICoverable getCoverHolder(); + + // fluid piping + + void spawnParticles(Direction direction, EnumParticleTypes particleType, int particleCount); + + void dealAreaDamage(int size, Consumer damageFunction); + + void playLossSound(); + + void visuallyExplode(); + + void setNeighborsToFire(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java new file mode 100644 index 0000000000..a5b9049afc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java @@ -0,0 +1,62 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; + +import gregtech.api.capability.GregtechDataCodes; +import gregtech.client.renderer.pipe.ActivablePipeModel; + +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.common.property.IExtendedBlockState; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.jetbrains.annotations.NotNull; + +public class PipeActivableBlockEntity extends PipeBlockEntity implements IActivable { + + private boolean active; + + @Override + public void setActive(boolean active) { + if (this.active != active) { + this.active = active; + writeCustomData(GregtechDataCodes.PIPE_ACTIVE, buf -> buf.writeBoolean(active)); + markDirty(); + } + } + + @Override + public boolean isActive() { + return active; + } + + @Override + @OnlyIn(Dist.CLIENT) + public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { + return super.getRenderInformation(state).withProperty(ActivablePipeModel.ACTIVE_PROPERTY, isActive()); + } + + @Override + public void receiveCustomData(int discriminator, @NotNull PacketBuffer buf) { + super.receiveCustomData(discriminator, buf); + if (discriminator == GregtechDataCodes.PIPE_ACTIVE) { + boolean active = buf.readBoolean(); + if (this.active != active) { + this.active = active; + scheduleRenderUpdate(); + } + } + } + + @Override + public void writeInitialSyncData(@NotNull PacketBuffer buf) { + buf.writeBoolean(active); + super.writeInitialSyncData(buf); + } + + @Override + public void receiveInitialSyncData(@NotNull PacketBuffer buf) { + active = buf.readBoolean(); + super.receiveInitialSyncData(buf); + } + + // do not save activeness to nbt, it should go away on world save & load. +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java new file mode 100644 index 0000000000..2667511086 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -0,0 +1,696 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; + +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; +import com.gregtechceu.gtceu.api.blockentity.NeighborCacheBlockEntity; +import com.gregtechceu.gtceu.api.capability.IToolable; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.cover.CoverBehavior; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicRegistry; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IInsulatable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; + +import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; +import com.gregtechceu.gtceu.api.machine.TickableSubscription; +import com.gregtechceu.gtceu.api.pipenet.PipeCoverContainer; +import com.gregtechceu.gtceu.common.data.GTBlocks; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; +import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; +import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; +import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; +import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; +import lombok.Getter; +import lombok.Setter; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Blocks; +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.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.common.capabilities.Capability; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumMap; +import java.util.List; +import java.util.Set; + +public class PipeBlockEntity extends NeighborCacheBlockEntity implements IWorldPipeNetTile, ITickSubscription, IEnhancedManaged, + IAsyncAutoSyncBlockEntity, IAutoPersistBlockEntity, IToolGridHighLight, IToolable { + + public static final int DEFAULT_COLOR = 0xFFFFFFFF; + + private final Int2ObjectOpenHashMap netLogicDatas = new Int2ObjectOpenHashMap<>(); + private final ObjectOpenHashSet listeners = new ObjectOpenHashSet<>(); + + // information that is only required for determining graph topology should be stored on the tile entity level, + // while information interacted with during graph traversal should be stored on the NetLogicData level. + + @Persisted + @DescSynced + private byte connectionMask; + @Persisted + @DescSynced + private byte renderMask; + @Persisted + @DescSynced + private byte blockedMask; + @Persisted + @DescSynced + private int paintingColor = -1; + + @Getter + @Setter + @DescSynced + private @Nullable Material frameMaterial; + + private final Set tickers = new ObjectOpenHashSet<>(); + + @Persisted + @DescSynced + @Getter + protected final PipeCoverContainer covers = new PipeCoverContainer(this); + private final Object2ObjectOpenHashMap, IPipeCapabilityObject> capabilities = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectOpenCustomHashMap netCapabilities = WorldPipeNet + .getSensitiveHashMap(); + + @Nullable + private TemperatureLogic temperatureLogic; + @OnlyIn(Dist.CLIENT) + @Nullable + private GTOverheatParticle overheatParticle; + + private final int offset = (int) (Math.random() * 20); + + private long nextDamageTime = 0; + private long nextSoundTime = 0; + + public PipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { + super(type, pos, blockState); + + } + + @Nullable + public PipeBlockEntity getPipeNeighbor(Direction facing, boolean allowChunkloading) { + BlockEntity tile = allowChunkloading ? getNeighbor(facing) : getNeighborNoChunkloading(facing); + if (tile instanceof PipeBlockEntity pipe) return pipe; + else return null; + } + + public void getDrops(@NotNull NonNullList drops, @NotNull BlockState state) { + drops.add(getMainDrop(state)); + if (getFrameMaterial() != null) + drops.add(GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, getFrameMaterial()).asStack()); + } + + @Override + public void validate() { + super.validate(); + scheduleRenderUpdate(); + } + + @Override + public void invalidate() { + super.invalidate(); + // TODO I hate this so much can someone please make it so that covers go through getDrops()? + getCoverHolder().dropAllCovers(); + } + + public ItemStack getMainDrop(@NotNull BlockState state) { + return new ItemStack(state.getBlock(), 1); + } + + public ItemStack getDrop() { + return new ItemStack(getBlockType(), 1, getBlockType().damageDropped(getBlockState())); + } + + public long getOffsetTimer() { + return Platform.getMinecraftServer().getTickCount() + offset; + } + + public void placedBy(ItemStack stack, Player player) {} + + public IPipeStructure getStructure() { + return getBlockType().getStructure(); + } + + // mask // + + public boolean canConnectTo(Direction facing) { + return this.getStructure().canConnectTo(facing, connectionMask); + } + + public void setConnected(Direction facing, boolean renderClosed) { + this.connectionMask |= 1 << facing.ordinal(); + updateActiveStatus(facing, false); + if (renderClosed) { + this.renderMask |= 1 << facing.ordinal(); + } else { + this.renderMask &= ~(1 << facing.ordinal()); + } + } + + public void setDisconnected(Direction facing) { + this.connectionMask &= ~(1 << facing.ordinal()); + this.renderMask &= ~(1 << facing.ordinal()); + updateActiveStatus(facing, false); + } + + public boolean isConnected(Direction facing) { + return (this.connectionMask & 1 << facing.ordinal()) > 0; + } + + public boolean isConnectedCoverAdjusted(Direction facing) { + CoverBehavior cover; + return ((this.connectionMask & 1 << facing.ordinal()) > 0) || + (cover = getCoverHolder().getCoverAtSide(facing)) != null && cover.forcePipeRenderConnection(); + } + + public boolean renderClosed(Direction facing) { + return (this.renderMask & 1 << facing.ordinal()) > 0; + } + + public byte getConnectionMask() { + return connectionMask; + } + + public void setBlocked(Direction facing) { + this.blockedMask |= (byte) (1 << facing.ordinal()); + } + + public void setUnblocked(Direction facing) { + this.blockedMask &= (byte) ~(1 << facing.ordinal()); + } + + public boolean isBlocked(Direction facing) { + return (this.blockedMask & 1 << facing.ordinal()) > 0; + } + + public byte getBlockedMask() { + return blockedMask; + } + + // paint // + + public int getPaintingColor() { + return isPainted() ? paintingColor : getDefaultPaintingColor(); + } + + public void setPaintingColor(int paintingColor, boolean alphaSensitive) { + if (!alphaSensitive) { + paintingColor |= 0xFF000000; + } + this.paintingColor = paintingColor; + } + + public boolean isPainted() { + return this.paintingColor != -1; + } + + public int getDefaultPaintingColor() { + return DEFAULT_COLOR; + } + + // ticking // + + public void addTicker(TickableSubscription ticker) { + this.tickers.add(ticker); + } + + public void update() { + this.tickers.forEach(TickableSubscription::run); + } + + @Override + public void onLoad() { + super.onLoad(); + initialize(); + } + + public void removeTicker(TickableSubscription ticker) { + this.tickers.remove(ticker); + } + + public boolean isTicking() { + return !tickers.isEmpty(); + } + + // activeness // + + @Override + public void onNeighborChanged(@NotNull Direction facing) { + super.onNeighborChanged(facing); + updateActiveStatus(facing, false); + } + + /** + * Returns a map of facings to tile entities that should have at least one of the required capabilities. + * + * @param node the node for this tile entity. Used to identify the capabilities to match. + * @return a map of facings to tile entities. + */ + public @NotNull EnumMap getTargetsWithCapabilities(WorldPipeNetNode node) { + PipeCapabilityWrapper wrapper = netCapabilities.get(node); + EnumMap caps = new EnumMap<>(Direction.class); + if (wrapper == null) return caps; + + for (Direction facing : GTUtil.DIRECTIONS) { + if (wrapper.isActive(facing)) { + BlockEntity tile = getNeighbor(facing); + if (tile == null) updateActiveStatus(facing, false); + else caps.put(facing, tile); + } + } + return caps; + } + + @Override + public @Nullable TileEntity getTargetWithCapabilities(WorldPipeNetNode node, Direction facing) { + PipeCapabilityWrapper wrapper = netCapabilities.get(node); + if (wrapper == null || !wrapper.isActive(facing)) return null; + else return getNeighbor(facing); + } + + @Override + public PipeCapabilityWrapper getWrapperForNode(WorldPipeNetNode node) { + return netCapabilities.get(node); + } + + /** + * Updates the pipe's active status based on the tile entity connected to the side. + * + * @param facing the side to check. Can be null, in which case all sides will be checked. + * @param canOpenConnection whether the pipe is allowed to open a new connection if it finds a tile it can connect + * to. + */ + public void updateActiveStatus(@Nullable Direction facing, boolean canOpenConnection) { + if (facing == null) { + for (Direction side : GTUtil.DIRECTIONS) { + updateActiveStatus(side, canOpenConnection); + } + return; + } + if (!this.isConnectedCoverAdjusted(facing) && !(canOpenConnection && canConnectTo(facing))) { + setAllIdle(facing); + return; + } + + BlockEntity tile = getNeighbor(facing); + if (tile == null || tile instanceof PipeBlockEntity) { + setAllIdle(facing); + return; + } + + boolean oneActive = false; + for (var netCapability : netCapabilities.entrySet()) { + for (Capability cap : netCapability.getValue().capabilities) { + if (tile.getCapability(cap, facing.getOpposite()).isPresent()) { + oneActive = true; + netCapability.getValue().setActive(facing); + break; + } + } + } + if (canOpenConnection && oneActive) this.setConnected(facing, false); + } + + private void setAllIdle(Direction facing) { + for (var netCapability : netCapabilities.entrySet()) { + netCapability.getValue().setIdle(facing); + } + } + + // capability // + + private void addCapabilities(IPipeCapabilityObject[] capabilities) { + for (IPipeCapabilityObject capabilityObject : capabilities) { + capabilityObject.setTile(this); + for (Capability capability : capabilityObject.getCapabilities()) { + this.capabilities.put(capability, capabilityObject); + } + } + } + + public T getCapabilityCoverQuery(@NotNull Capability capability, @Nullable Direction facing) { + // covers have access to the capability objects no matter the connection status + IPipeCapabilityObject object = capabilities.get(capability); + return object == null ? null : object.getCapabilityForSide(capability, facing); + } + + @Override + public boolean hasCapability(@NotNull Capability capability, Direction facing) { + return getCapability(capability, facing) != null; + } + + @Override + public LazyOptional getCapability(@NotNull Capability capability, @Nullable Direction facing) { + if (capability == GTCapability.CAPABILITY_COVERABLE) { + return GTCapability.CAPABILITY_COVERABLE.orEmpty(capability, LazyOptional.of(this::getCovers)); + } + T pipeCapability; + IPipeCapabilityObject object = capabilities.get(capability); + if (object == null || (pipeCapability = object.getCapabilityForSide(capability, facing)) == null) + pipeCapability = super.getCapability(capability, facing); + + CoverBehavior cover = facing == null ? null : getCoverHolder().getCoverAtSide(facing); + if (cover == null) { + if (facing == null || isConnected(facing)) { + return pipeCapability; + } + return null; + } + + T coverCapability = cover.getCapability(capability, pipeCapability); + if (coverCapability == pipeCapability) { + if (isConnectedCoverAdjusted(facing)) { + return pipeCapability; + } + return null; + } + return coverCapability; + } + + // data sync management // + + public NetLogicData getNetLogicData(int networkID) { + return netLogicDatas.get(networkID); + } + + @Override + public @NotNull PipeBlock getBlockType() { + return (PipeBlock) super.getBlockType(); + } + + @Override + public void setWorld(@NotNull World worldIn) { + if (worldIn == this.getWorld()) return; + super.setWorld(worldIn); + } + + protected void initialize() { + if (!getWorld().isRemote) { + this.netLogicDatas.clear(); + this.capabilities.clear(); + this.netCapabilities.clear(); + this.listeners.forEach(NetLogicData.LogicDataListener::invalidate); + this.listeners.clear(); + boolean firstNode = true; + for (WorldPipeNetNode node : PipeBlock.getNodesForTile(this)) { + this.addCapabilities(node.getNet().getNewCapabilityObjects(node)); + this.netCapabilities.put(node, new PipeCapabilityWrapper(this, node)); + int networkID = node.getNet().getNetworkID(); + netLogicDatas.put(networkID, node.getData()); + var listener = node.getData().createListener( + (e, r, f) -> writeCustomData(UPDATE_PIPE_LOGIC, buf -> { + buf.writeVarInt(networkID); + buf.writeString(e.getName()); + buf.writeBoolean(r); + buf.writeBoolean(f); + if (!r) { + e.encode(buf, f); + } + })); + this.listeners.add(listener); + node.getData().addListener(listener); + if (firstNode) { + firstNode = false; + this.temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + } + // TODO + // this and updateActiveStatus() theoretically only need to be called when loading old world data; + // is there a way to detect that and skip if so? + node.getNet().updatePredication(node, this); + } + this.netLogicDatas.trim(); + this.listeners.trim(); + this.capabilities.trim(); + this.netCapabilities.trim(); + updateActiveStatus(null, false); + } + } + + @Override + public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { + buf.writeVarInt(netLogicDatas.size()); + for (var entry : netLogicDatas.entrySet()) { + buf.writeVarInt(entry.getKey()); + entry.getValue().encode(buf); + } + } + + @Override + public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { + if (level.isClientSide) { + netLogicDatas.clear(); + int count = buf.readVarInt(); + for (int i = 0; i < count; i++) { + int networkID = buf.readVarInt(); + NetLogicData data = new NetLogicData(); + data.decode(buf); + netLogicDatas.put(networkID, data); + } + } + scheduleRenderUpdate(); + } + + @Override + public void receiveCustomData(int discriminator, @NotNull PacketBuffer buf) { + if (discriminator == UPDATE_PIPE_LOGIC) { + // extra check just to make sure we don't affect actual net data with our writes + if (world.isRemote) { + int networkID = buf.readVarInt(); + String identifier = buf.readString(255); + boolean removed = buf.readBoolean(); + boolean fullChange = buf.readBoolean(); + if (removed) { + this.netLogicDatas.computeIfPresent(networkID, (k, v) -> v.removeLogicEntry(identifier)); + } else { + if (fullChange) { + NetLogicEntry logic = NetLogicRegistry.getSupplierErroring(identifier).get(); + logic.decode(buf, true); + this.netLogicDatas.compute(networkID, (k, v) -> { + if (v == null) v = new NetLogicData(); + v.setLogicEntry(logic); + return v; + }); + } else { + NetLogicData data = this.netLogicDatas.get(networkID); + if (data != null) { + NetLogicEntry entry = data.getLogicEntryNullable(identifier); + if (entry != null) entry.decode(buf, false); + data.markLogicEntryAsUpdated(entry, false); + } else return; + } + if (identifier.equals(TemperatureLogic.INSTANCE.getName())) { + TemperatureLogic tempLogic = this.netLogicDatas.get(networkID) + .getLogicEntryNullable(TemperatureLogic.INSTANCE); + if (tempLogic != null) updateTemperatureLogic(tempLogic); + } + } + } + } else if (discriminator == UPDATE_CONNECTIONS) { + this.connectionMask = buf.readByte(); + this.renderMask = buf.readByte(); + scheduleRenderUpdate(); + } else if (discriminator == UPDATE_BLOCKED_CONNECTIONS) { + this.blockedMask = buf.readByte(); + scheduleRenderUpdate(); + } else if (discriminator == UPDATE_FRAME_MATERIAL) { + String name = buf.readString(255); + if (name.equals("")) this.frameMaterial = null; + else this.frameMaterial = GregTechAPI.materialManager.getMaterial(name); + scheduleRenderUpdate(); + } else if (discriminator == UPDATE_PAINT) { + this.paintingColor = buf.readInt(); + scheduleRenderUpdate(); + } else { + this.getCoverHolder().readCustomData(discriminator, buf); + } + } + + // particle // + + public void updateTemperatureLogic(@NotNull TemperatureLogic logic) { + if (overheatParticle == null || !overheatParticle.isAlive()) { + long tick = FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter(); + int temp = logic.getTemperature(tick); + if (temp > GTOverheatParticle.TEMPERATURE_CUTOFF) { + IPipeStructure structure = this.getStructure(); + overheatParticle = new GTOverheatParticle(this, logic, structure.getPipeBoxes(this), + structure instanceof IInsulatable i && i.isInsulated()); + GTParticleManager.INSTANCE.addEffect(overheatParticle); + } + } else { + overheatParticle.setTemperatureLogic(logic); + } + } + + public @Nullable TemperatureLogic getTemperatureLogic() { + return temperatureLogic; + } + + @OnlyIn(Dist.CLIENT) + public void killOverheatParticle() { + if (overheatParticle != null) { + overheatParticle.setExpired(); + overheatParticle = null; + } + } + + @OnlyIn(Dist.CLIENT) + public boolean isOverheatParticleAlive() { + return overheatParticle != null && overheatParticle.isAlive(); + } + + @Override + public void spawnParticles(Direction direction, EnumParticleTypes particleType, int particleCount) { + if (getWorld() instanceof WorldServer server) { + server.spawnParticle(particleType, + getPos().getX() + 0.5, + getPos().getY() + 0.5, + getPos().getZ() + 0.5, + particleCount, + direction.getXOffset() * 0.2 + GTValues.RNG.nextDouble() * 0.1, + direction.getYOffset() * 0.2 + GTValues.RNG.nextDouble() * 0.1, + direction.getZOffset() * 0.2 + GTValues.RNG.nextDouble() * 0.1, + 0.1); + } + } + + // misc overrides // + + @Override + public World world() { + return getWorld(); + } + + @Override + public BlockPos pos() { + return getPos(); + } + + @Override + public void notifyBlockUpdate() { + getWorld().notifyNeighborsOfStateChange(getPos(), getBlockType(), true); + } + + @SuppressWarnings("ConstantConditions") // yes this CAN actually be null + @Override + public void markDirty() { + if (getWorld() != null && getPos() != null) { + getWorld().markChunkDirty(getPos(), this); + } + } + + @Override + public void markAsDirty() { + markDirty(); + // this most notably gets called when the covers of a pipe get updated, aka the edge predicates need syncing. + for (var node : this.netCapabilities.keySet()) { + node.getNet().updatePredication(node, this); + } + } + + public static @Nullable PipeBlockEntity getTileNoLoading(BlockPos pos, int dimension) { + World world = DimensionManager.getWorld(dimension); + if (world == null || !world.isBlockLoaded(pos)) return null; + + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof PipeBlockEntity pipe) return pipe; + else return null; + } + + /** + * Note - the block corresponding to this tile entity must register any new unlisted properties to the default + * state. + */ + @OnlyIn(Dist.CLIENT) + @MustBeInvokedByOverriders + public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { + byte frameMask = 0; + byte connectionMask = this.connectionMask; + for (Direction facing : GTUtil.DIRECTIONS) { + Cover cover = getCoverHolder().getCoverAtSide(facing); + if (cover != null) { + frameMask |= 1 << facing.ordinal(); + if (cover.forcePipeRenderConnection()) connectionMask |= 1 << facing.ordinal(); + } + } + frameMask = (byte) ~frameMask; + return state.withProperty(AbstractPipeModel.THICKNESS_PROPERTY, this.getStructure().getRenderThickness()) + .withProperty(AbstractPipeModel.CLOSED_MASK_PROPERTY, renderMask) + .withProperty(AbstractPipeModel.BLOCKED_MASK_PROPERTY, blockedMask) + .withProperty(AbstractPipeModel.COLOR_PROPERTY, getPaintingColor()) + .withProperty(AbstractPipeModel.FRAME_MATERIAL_PROPERTY, frameMaterial) + .withProperty(AbstractPipeModel.FRAME_MASK_PROPERTY, frameMask) + .withProperty(CoverRendererPackage.PROPERTY, getCoverHolder().createPackage()); + } + + public void getCoverBoxes(Consumer consumer) { + for (Direction facing : GTUtil.DIRECTIONS) { + if (getCoverHolder().hasCover(facing)) { + consumer.accept(CoverRendererBuilder.PLATE_AABBS.get(facing)); + } + } + } + + @Override + public void dealAreaDamage(int size, Consumer damageFunction) { + long timer = getOffsetTimer(); + if (timer >= this.nextDamageTime) { + List entities = getWorld().getEntitiesWithinAABB(EntityLivingBase.class, + new AxisAlignedBB(getPos()).grow(size)); + entities.forEach(damageFunction); + this.nextDamageTime = timer + 20; + } + } + + public void playLossSound() { + long timer = getOffsetTimer(); + if (timer >= this.nextSoundTime) { + getWorld().playSound(null, pos, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 1.0F, 1.0F); + this.nextSoundTime = timer + 20; + } + } + + public void visuallyExplode() { + getWorld().createExplosion(null, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, + 1.0f + GTValues.RNG.nextFloat(), false); + } + + public void setNeighborsToFire() { + for (Direction side : GTUtil.DIRECTIONS) { + if (!GTValues.RNG.nextBoolean()) continue; + BlockPos blockPos = getPos().offset(side); + IBlockState blockState = getWorld().getBlockState(blockPos); + if (blockState.getBlock().isAir(blockState, getWorld(), blockPos) || + blockState.getBlock().isFlammable(getWorld(), blockPos, side.getOpposite())) { + getWorld().setBlockState(blockPos, Blocks.FIRE.getDefaultState()); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCapabilityWrapper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCapabilityWrapper.java new file mode 100644 index 0000000000..9425f5ce65 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCapabilityWrapper.java @@ -0,0 +1,51 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; + +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.Capability; + +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +public class PipeCapabilityWrapper { + + private byte activeMask; + private final PipeBlockEntity owner; + private final WorldPipeNetNode node; + public final Capability[] capabilities; + + public PipeCapabilityWrapper(PipeBlockEntity owner, @NotNull WorldPipeNetNode node) { + this.owner = owner; + this.node = node; + this.capabilities = node.getNet().getTargetCapabilities(); + } + + public boolean supports(Capability capability) { + for (Capability cap : capabilities) { + if (Objects.equals(cap, capability)) return true; + } + return false; + } + + public void setActive(@NotNull Direction facing) { + if (!isActive(facing)) { + this.activeMask |= (byte) (1 << facing.ordinal()); + this.node.setActive(this.activeMask > 0); + this.owner.notifyBlockUpdate(); + } + } + + public void setIdle(@NotNull Direction facing) { + if (isActive(facing)) { + this.activeMask &= (byte) ~(1 << facing.ordinal()); + this.node.setActive(this.activeMask > 0); + this.owner.notifyBlockUpdate(); + } + } + + public boolean isActive(@NotNull Direction facing) { + return (this.activeMask & 1 << facing.ordinal()) > 0; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java new file mode 100644 index 0000000000..cea616e282 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -0,0 +1,300 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; + +import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; +import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.api.cover.CoverBehavior; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; + +import com.gregtechceu.gtceu.api.machine.TickableSubscription; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.INBTSerializable; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumMap; +import java.util.EnumSet; + +public class PipeCoverHolder implements ICoverable, INBTSerializable { + + private final PipeBlockEntity holder; + private final EnumMap covers = new EnumMap<>(Direction.class); + private final EnumSet tickingCovers = EnumSet.noneOf(Direction.class); + private final int[] sidedRedstoneInput = new int[6]; + + public PipeCoverHolder(PipeBlockEntity holder) { + this.holder = holder; + } + + protected final void addCoverSilent(@NotNull Direction side, @NotNull CoverBehavior cover) { + // we checked before if the side already has a cover + this.covers.put(side, cover); + if (cover instanceof ITickSubscription) { + tickingCovers.add(side); + holder.addTicker(new TickableSubscription(this::update)); + } + } + + @Override + public final void addCover(@NotNull Direction side, @NotNull CoverBehavior cover) { + addCoverSilent(side, cover); + if (!getLevel().isRemote) { + // do not sync or handle logic on client side + CoverSaveHandler.writeCoverPlacement(this, COVER_ATTACHED_PIPE, side, cover); + if (holder.isConnected(side) && !cover.canPipePassThrough()) { + PipeBlock.disconnectTile(holder, holder.getPipeNeighbor(side, true), side); + } + } + + holder.notifyBlockUpdate(); + holder.markAsDirty(); + } + + @Override + public final void removeCover(@NotNull Direction side) { + Cover cover = getCoverAtSide(side); + if (cover == null) return; + + dropCover(side); + covers.remove(side); + tickingCovers.remove(side); + if (tickingCovers.isEmpty()) holder.removeTicker(this); + writeCustomData(COVER_REMOVED_PIPE, buffer -> buffer.writeByte(side.getIndex())); + holder.notifyBlockUpdate(); + holder.markAsDirty(); + } + + @Override + public @NotNull ItemStack getStackForm() { + return holder.getDrop(); + } + + public void onLoad() { + for (Direction side : GTUtil.DIRECTIONS) { + this.sidedRedstoneInput[side.getIndex()] = GTUtility.getRedstonePower(getLevel(), getPos(), side); + } + } + + @Override + public final int getInputRedstoneSignal(@NotNull Direction side, boolean ignoreCover) { + if (!ignoreCover && getCoverAtSide(side) != null) { + return 0; // covers block input redstone signal for machine + } + return sidedRedstoneInput[side.getIndex()]; + } + + public void updateInputRedstoneSignals() { + for (Direction side : GTUtil.DIRECTIONS) { + int redstoneValue = GTUtility.getRedstonePower(getLevel(), getPos(), side); + int currentValue = sidedRedstoneInput[side.getIndex()]; + if (redstoneValue != currentValue) { + this.sidedRedstoneInput[side.getIndex()] = redstoneValue; + Cover cover = getCoverAtSide(side); + if (cover != null) { + cover.onRedstoneInputSignalChange(redstoneValue); + } + } + } + } + + @Override + public void notifyBlockUpdate() { + holder.notifyBlockUpdate(); + } + + @Override + public void scheduleRenderUpdate() { + BlockPos pos = getPos(); + getLevel().markBlockRangeForRenderUpdate( + pos.getX() - 1, pos.getY() - 1, pos.getZ() - 1, + pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1); + } + + @Override + public double getCoverPlateThickness() { + float thickness = holder.getBlockType().getStructure().getRenderThickness(); + // no cover plate for pipes >= 1 block thick + if (thickness >= 1) return 0; + + // If the available space for the cover is less than the regular cover plate thickness, use that + + // need to divide by 2 because thickness is centered on the block, so the space is half on each side of the pipe + return Math.min(1.0 / 16.0, (1.0 - thickness) / 2); + } + + @Override + public boolean shouldRenderCoverBackSides() { + return false; + } + + @Override + public int getPaintingColorForRendering() { + return ConfigHolder.client.defaultPaintingColor; + } + + @Override + public boolean canPlaceCoverOnSide(@NotNull Direction side) { + return holder.canConnectTo(side); + } + + @Override + public final boolean acceptsCovers() { + return covers.size() < GTUtil.DIRECTIONS.length; + } + + public boolean canConnectRedstone(@Nullable Direction side) { + // so far null side means either upwards or downwards redstone wire connection + // so check both top cover and bottom cover + if (side == null) { + return canConnectRedstone(Direction.UP) || + canConnectRedstone(Direction.DOWN); + } + Cover cover = getCoverAtSide(side); + return cover != null && cover.canConnectRedstone(); + } + + public int getOutputRedstoneSignal(@Nullable Direction side) { + if (side == null) { + return getHighestOutputRedstoneSignal(); + } + Cover cover = getCoverAtSide(side); + return cover == null ? 0 : cover.getRedstoneSignalOutput(); + } + + public int getHighestOutputRedstoneSignal() { + int highestSignal = 0; + for (Direction side : GTUtil.DIRECTIONS) { + Cover cover = getCoverAtSide(side); + if (cover == null) continue; + highestSignal = Math.max(highestSignal, cover.getRedstoneSignalOutput()); + } + return highestSignal; + } + + @Override + public void update() { + if (!getLevel().isRemote) { + updateCovers(); + } + } + + @Override + public void writeCoverData(@NotNull Cover cover, int discriminator, @NotNull Consumer<@NotNull PacketBuffer> buf) { + writeCustomData(UPDATE_COVER_DATA_PIPE, buffer -> { + buffer.writeByte(cover.getAttachedSide().getIndex()); + buffer.writeVarInt(discriminator); + buf.accept(buffer); + }); + } + + public void writeInitialSyncData(PacketBuffer buf) { + CoverSaveHandler.writeInitialSyncData(buf, this); + } + + public void readInitialSyncData(PacketBuffer buf) { + CoverSaveHandler.receiveInitialSyncData(buf, this); + } + + @Override + public void writeCustomData(int dataId, @NotNull Consumer writer) { + holder.writeCustomData(dataId, writer); + } + + public void readCustomData(int dataId, PacketBuffer buf) { + if (dataId == COVER_ATTACHED_PIPE) { + CoverSaveHandler.readCoverPlacement(buf, this); + } else if (dataId == COVER_REMOVED_PIPE) { + // cover removed event + Direction placementSide = GTUtil.DIRECTIONS[buf.readByte()]; + this.covers.remove(placementSide); + this.tickingCovers.remove(placementSide); + if (this.tickingCovers.isEmpty()) holder.removeTicker(this); + holder.scheduleRenderUpdate(); + } else if (dataId == UPDATE_COVER_DATA_PIPE) { + // cover custom data received + Direction coverSide = GTUtil.DIRECTIONS[buf.readByte()]; + Cover cover = getCoverAtSide(coverSide); + int internalId = buf.readVarInt(); + if (cover != null) { + cover.readCustomData(internalId, buf); + } + } + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + CoverSaveHandler.writeCoverNBT(tag, this); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + CoverSaveHandler.readCoverNBT(nbt, this, this::addCoverSilent); + } + + @Override + public Level getLevel() { + return holder.getLevel(); + } + + @Override + public BlockPos getPos() { + return holder.getBlockPos(); + } + + @Override + public @Nullable BlockEntity getNeighbor(@NotNull Direction facing) { + return holder.getNeighbor(facing); + } + + @Override + public long getOffsetTimer() { + return holder.getOffsetTimer(); + } + + @Nullable + @Override + public CoverBehavior getCoverAtSide(@NotNull Direction side) { + return covers.get(side); + } + + @Override + public boolean hasAnyCover() { + return !covers.isEmpty(); + } + + @Override + public void markDirty() { + holder.markAsDirty(); + } + + @Override + public boolean isValid() { + return !holder.isInvalid(); + } + + @Override + public T getCapability(@NotNull Capability capability, Direction side) { + return holder.getCapabilityCoverQuery(capability, side); + } + + @OnlyIn(Dist.CLIENT) + public CoverRendererPackage createPackage() { + if (covers.isEmpty()) return CoverRendererPackage.EMPTY; + CoverRendererPackage rendererPackage = new CoverRendererPackage(shouldRenderCoverBackSides()); + for (var cover : covers.entrySet()) { + rendererPackage.addRenderer(cover.getValue().getRenderer(), cover.getKey()); + } + return rendererPackage; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java new file mode 100644 index 0000000000..b3e68b921b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java @@ -0,0 +1,79 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; + +import com.gregtechceu.gtceu.common.data.GTMaterials; +import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; +import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +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; + +import net.minecraftforge.client.model.data.ModelData; +import org.jetbrains.annotations.NotNull; + +public class PipeMaterialTileEntity extends PipeBlockEntity { + + @Persisted + @DescSynced + private Material material; + + public PipeMaterialTileEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { + super(type, pos, blockState); + } + + @Override + protected void initialize() { + // prevent initialization when we don't know our material; + // this specifically happens right after we have been + // placed and placedBy() has yet to be called. + if (material != null) super.initialize(); + } + + @Override + public void placedBy(ItemStack stack, Player player) { + super.placedBy(stack, player); + setMaterial(getBlockType().getMaterialForStack(stack)); + initialize(); + } + + @Override + public @NotNull PipeMaterialBlock getBlockType() { + return (PipeMaterialBlock) super.getBlockType(); + } + + public void setMaterial(Material material) { + this.material = material; + } + + public Material getMaterial() { + if (material == null) return GTMaterials.Aluminium; + return material; + } + + @Override + public ItemStack getMainDrop(@NotNull BlockState state) { + return getBlockType().getItem(getMaterial()); + } + + @Override + public int getDefaultPaintingColor() { + return GTUtility.convertRGBtoARGB(getMaterial().getMaterialRGB()); + } + + @Override + @OnlyIn(Dist.CLIENT) + public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { + return super.getRenderInformation(state).withProperty(AbstractPipeModel.MATERIAL_PROPERTY, getMaterial()); + } + + @Override + public @NotNull ModelData getModelData() { + return super.getModelData(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java new file mode 100644 index 0000000000..8c8977b51e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java @@ -0,0 +1,51 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.predicate; + +import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.nbt.NBTTagByte; + +import org.jetbrains.annotations.NotNull; + +public final class BlockedPredicate extends EdgePredicate { + + public static final BlockedPredicate INSTANCE = new BlockedPredicate(); + + private BlockedPredicate() { + super("Blocked"); + } + + @Override + @Deprecated + public @NotNull BlockedPredicate getNew() { + return INSTANCE; + } + + @Override + public NBTTagByte serializeNBT() { + return new NBTTagByte((byte) 0); + } + + @Override + public void deserializeNBT(NBTTagByte nbt) {} + + @Override + public boolean andy() { + return true; + } + + @Override + public boolean test(IPredicateTestObject object) { + return false; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof BlockedPredicate; + } + + @Override + public int hashCode() { + return 0; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java new file mode 100644 index 0000000000..9e9e24809a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java @@ -0,0 +1,101 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.predicate; + +import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import gregtech.common.covers.filter.BaseFilterContainer; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompoundTag; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +public final class FilterPredicate extends EdgePredicate { + + public static final FilterPredicate INSTANCE = new FilterPredicate(); + + private @Nullable BaseFilterContainer sourceFilter; + private @Nullable BaseFilterContainer targetFilter; + + private FilterPredicate() { + super("FluidFilter"); + } + + public void setSourceFilter(@Nullable BaseFilterContainer sourceFilter) { + this.sourceFilter = sourceFilter; + } + + public void setTargetFilter(@Nullable BaseFilterContainer targetFilter) { + this.targetFilter = targetFilter; + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + if (sourceFilter != null) tag.setTag("Source", sourceFilter.serializeNBT()); + if (targetFilter != null) tag.setTag("Target", targetFilter.serializeNBT()); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + if (nbt.hasKey("Source")) { + sourceFilter = new GenericFilterContainer(); + sourceFilter.deserializeNBT(nbt.getCompoundTag("Source")); + } else sourceFilter = null; + if (nbt.hasKey("Target")) { + targetFilter = new GenericFilterContainer(); + targetFilter.deserializeNBT(nbt.getCompoundTag("Target")); + } else targetFilter = null; + } + + @Override + public boolean andy() { + return true; + } + + @Override + public @NotNull FilterPredicate getNew() { + return new FilterPredicate(); + } + + @Override + public boolean test(IPredicateTestObject object) { + Object test = object.recombine(); + if (sourceFilter != null && !sourceFilter.test(test)) return false; + return targetFilter == null || targetFilter.test(test); + } + + private static class GenericFilterContainer extends BaseFilterContainer { + + protected GenericFilterContainer() { + super(() -> {}); + } + + @Override + protected boolean isItemValid(ItemStack stack) { + return true; + } + + @Override + protected String getFilterName() { + return ""; + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FilterPredicate predicate = (FilterPredicate) o; + return Objects.equals(sourceFilter, predicate.sourceFilter) && + Objects.equals(targetFilter, predicate.targetFilter); + } + + @Override + public int hashCode() { + return Objects.hash(sourceFilter, targetFilter); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java new file mode 100644 index 0000000000..a7c59b7048 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.transfer; + +import net.minecraft.util.IStringSerializable; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public abstract class TransferControl implements IStringSerializable { + + private final String name; + + public TransferControl(@NotNull String name) { + this.name = name; + } + + @Override + public @NotNull String getName() { + return name; + } + + public abstract @NotNull T get(@Nullable Object potentialHolder); + + public abstract @NotNull T getNoPassage(); + + public T cast(Object o) { + return (T) o; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControlProvider.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControlProvider.java new file mode 100644 index 0000000000..e7e4949239 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControlProvider.java @@ -0,0 +1,8 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.transfer; + +import org.jetbrains.annotations.Nullable; + +public interface TransferControlProvider { + + @Nullable T getControllerForControl(TransferControl control); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java new file mode 100644 index 0000000000..211397557d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java @@ -0,0 +1,73 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCapabilityWrapper; +import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinData; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Direction; +import net.minecraftforge.common.capabilities.Capability; + +import org.apache.commons.lang3.mutable.MutableByte; +import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.WeakHashMap; + +public abstract class AbstractTileRoundRobinData implements IRoundRobinData { + + private final MutableByte pointer = new MutableByte(); + + // I'm sorry but a weak Object2Byte map doesn't exist + private final Map simulatorMap = new WeakHashMap<>(); + + @Override + @MustBeInvokedByOverriders + public void resetIfFinished(WorldPipeNetNode node, @Nullable SimulatorKey simulator) { + if (!hasNextInternalDestination(node, simulator)) getPointer(simulator).setValue(0); + } + + public @NotNull MutableByte getPointer(@Nullable SimulatorKey simulator) { + if (simulator == null) return pointer; + MutableByte value = simulatorMap.get(simulator); + if (value == null) { + value = new MutableByte(); + simulatorMap.put(simulator, value); + } + return value; + } + + public final boolean pointerFinished(@Nullable SimulatorKey simulator) { + return pointerFinished(getPointer(simulator)); + } + + public final boolean pointerFinished(@NotNull MutableByte pointer) { + return pointer.byteValue() >= GTUtil.DIRECTIONS.length; + } + + public final Direction getPointerFacing(SimulatorKey simulator) { + MutableByte pointer = getPointer(simulator); + if (pointerFinished(pointer)) throw new IllegalStateException("Pointer is finished!"); + return GTUtil.DIRECTIONS[pointer.byteValue()]; + } + + public boolean hasCapabilityAtPointer(@NotNull Capability capability, WorldPipeNetNode node, + @Nullable SimulatorKey simulator) { + return getCapabilityAtPointer(capability, node, simulator) != null; + } + + @Nullable + public E getCapabilityAtPointer(@NotNull Capability capability, WorldPipeNetNode node, + @Nullable SimulatorKey simulator) { + if (pointerFinished(simulator)) return null; + PipeCapabilityWrapper wrapper = node.getTileEntity().getWrapperForNode(node); + Direction pointer = getPointerFacing(simulator); + + if (!wrapper.isActive(pointer) || !wrapper.supports(capability)) return null; + TileEntity target = node.getTileEntity().getTargetWithCapabilities(node, pointer); + return target == null ? null : target.getCapability(capability, pointer.getOpposite()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java new file mode 100644 index 0000000000..665c00be32 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java @@ -0,0 +1,41 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; + +import net.minecraftforge.common.capabilities.Capability; + +import org.apache.commons.lang3.mutable.MutableByte; +import org.jetbrains.annotations.Nullable; + +public class SimpleTileRoundRobinData extends AbstractTileRoundRobinData { + + private final Capability cap; + + public SimpleTileRoundRobinData(Capability capability) { + this.cap = capability; + } + + @Override + public boolean hasNextInternalDestination(WorldPipeNetNode node, @Nullable SimulatorKey simulator) { + MutableByte pointer = getPointer(simulator); + byte val = pointer.byteValue(); + progressToNextInternalDestination(node, simulator); + boolean hasNext = !pointerFinished(pointer); + pointer.setValue(val); + return hasNext; + } + + @Override + public void progressToNextInternalDestination(WorldPipeNetNode node, @Nullable SimulatorKey simulator) { + MutableByte pointer = getPointer(simulator); + pointer.increment(); + while (!pointerFinished(pointer) && !hasCapabilityAtPointer(cap, node, simulator)) { + pointer.increment(); + } + } + + public @Nullable T getAtPointer(WorldPipeNetNode node, @Nullable SimulatorKey simulator) { + return getCapabilityAtPointer(cap, node, simulator); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java new file mode 100644 index 0000000000..7787371c3a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java @@ -0,0 +1,62 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate; + +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.nbt.Tag; +import net.minecraft.util.StringRepresentable; +import net.minecraftforge.common.util.INBTSerializable; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Note - all extenders of this class are suggested to be final, in order to avoid unexpected + * {@link #union(EdgePredicate)} behavior. + */ +public abstract class EdgePredicate, N extends Tag> + implements INBTSerializable, StringRepresentable { + + private final @NotNull String name; + + public EdgePredicate(@NotNull String name) { + this.name = name; + NetPredicateRegistry.register(this); + } + + @Override + public final @NotNull String getSerializedName() { + return name; + } + + public void deserializeNBTNaive(Tag nbt) { + deserializeNBT((N) nbt); + } + + /** + * Whether this predicate should behave in "and" fashion with other predicates.
+ *
+ * For example, if a predicate handler has 2 and-y predicates and 3 or-y predicates, + * the effective result of evaluation will be:
+ * (andy1) && (andy2) && (ory1 || ory2 || ory3) + */ + public abstract boolean andy(); + + @NotNull + public abstract T getNew(); + + public abstract boolean test(IPredicateTestObject object); + + /** + * Returns null if the operation is not supported. + */ + @Nullable + public T union(EdgePredicate other) { + return null; + } + + /** + * {@link Object#equals(Object)} should always have a good implementation for the sake of sameness checks. + */ + @Override + public abstract boolean equals(Object obj); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java new file mode 100644 index 0000000000..633732b9ef --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java @@ -0,0 +1,117 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate; + +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.util.StringRepresentable; +import net.minecraftforge.common.util.INBTSerializable; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.function.Predicate; + +/** + * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on predicates, + * making a predicate class return two different names is a valid way to register multiple instances. + */ +public final class EdgePredicateHandler implements INBTSerializable, Predicate { + + private final Map> predicateSet; + + public EdgePredicateHandler() { + predicateSet = new Object2ObjectOpenHashMap<>(); + } + + /** + * If the {@link EdgePredicate#union(EdgePredicate)} operation is not supported for this predicate, + * nothing happens if a predicate is already present. + */ + public EdgePredicateHandler mergePredicate(@NotNull EdgePredicate predicate) { + EdgePredicate current = predicateSet.get(predicate.getSerializedName()); + if (current == null) return setPredicate(predicate); + + if (predicate.getClass().isInstance(current)) { + predicate = current.union(predicate); + if (predicate == null) return this; + } + return setPredicate(predicate); + } + + /** + * Do not modify the returned value + */ + public Map> getPredicateSet() { + return predicateSet; + } + + public EdgePredicateHandler setPredicate(@NotNull EdgePredicate predicate) { + predicateSet.put(predicate.getSerializedName(), predicate); + return this; + } + + public EdgePredicateHandler removePredicate(@NotNull EdgePredicate predicate) { + return removePredicate(predicate.getSerializedName()); + } + + public EdgePredicateHandler removePredicate(String key) { + predicateSet.remove(key); + return this; + } + + public boolean hasPredicate(@NotNull EdgePredicate predicate) { + return predicateSet.containsKey(predicate.getSerializedName()); + } + + public boolean hasPredicate(String key) { + return predicateSet.containsKey(key); + } + + public void clearPredicates() { + this.predicateSet.clear(); + } + + public boolean shouldIgnore() { + return predicateSet.isEmpty(); + } + + @Override + public boolean test(IPredicateTestObject iPredicateTestObject) { + if (shouldIgnore()) return true; + boolean result = false; + for (EdgePredicate predicate : predicateSet.values()) { + // TODO predicate 'categories' or 'affinities' that determine order of operations with and-y and or-y + // behavior? + boolean test = predicate.test(iPredicateTestObject); + if (predicate.andy() && !test) return false; + else result |= test; + } + return result; + } + + @Override + public ListTag serializeNBT() { + ListTag list = new ListTag(); + for (EdgePredicate entry : predicateSet.values()) { + CompoundTag tag = new CompoundTag(); + tag.put("Tag", entry.serializeNBT()); + tag.putString("Name", entry.getSerializedName()); + list.add(tag); + } + return list; + } + + @Override + public void deserializeNBT(ListTag nbt) { + for (int i = 0; i < nbt.size(); i++) { + CompoundTag tag = nbt.getCompound(i); + String key = tag.getString("Name"); + EdgePredicate entry = this.predicateSet.get(key); + if (entry == null) entry = NetPredicateRegistry.getSupplierNotNull(key).get(); + if (entry == null) continue; + entry.deserializeNBTNaive(tag.get("Tag")); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java new file mode 100644 index 0000000000..7c74e704f3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java @@ -0,0 +1,36 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.function.Supplier; + +public final class NetPredicateRegistry { + + private static final Map>> REGISTRY = new Object2ObjectOpenHashMap<>(); + + static void register(@NotNull EdgePredicate predicate) { + REGISTRY.putIfAbsent(predicate.getName(), predicate::getNew); + } + + public static @Nullable Supplier<@NotNull EdgePredicate> getSupplierNullable(String name) { + return REGISTRY.get(name); + } + + public static @NotNull Supplier<@Nullable EdgePredicate> getSupplierNotNull(String name) { + return REGISTRY.getOrDefault(name, () -> null); + } + + public static @NotNull Supplier> getSupplierErroring(String name) { + Supplier> supplier = REGISTRY.get(name); + if (supplier == null) throwNonexistenceError(); + return supplier; + } + + public static void throwNonexistenceError() { + throw new RuntimeException("Could not find a matching supplier for an encoded EdgePredicate. " + + "This suggests that the server and client have different GT versions or modifications."); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java new file mode 100644 index 0000000000..993bf3730b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java @@ -0,0 +1,55 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate.test; + +import net.minecraft.nbt.CompoundTag; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; +import java.util.function.Predicate; + +public final class FluidTestObject implements IPredicateTestObject, Predicate { + + public final Fluid fluid; + public final CompoundTag tag; + + private final int hash; + + public FluidTestObject(@NotNull FluidStack stack) { + this.fluid = stack.getFluid(); + this.tag = stack.tag; + this.hash = Objects.hash(fluid, tag); + } + + @Override + @Contract(" -> new") + public @NotNull FluidStack recombine() { + return new FluidStack(fluid, 1, tag); + } + + @Contract("_ -> new") + public @NotNull FluidStack recombine(int amount) { + return new FluidStack(fluid, amount, tag); + } + + @Override + public boolean test(@Nullable FluidStack stack) { + return stack != null && stack.getFluid() == fluid && Objects.equals(tag, stack.tag); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FluidTestObject that = (FluidTestObject) o; + return Objects.equals(fluid, that.fluid) && Objects.equals(tag, that.tag); + } + + @Override + public int hashCode() { + return hash; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/IPredicateTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/IPredicateTestObject.java new file mode 100644 index 0000000000..ad1ae98835 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/IPredicateTestObject.java @@ -0,0 +1,13 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate.test; + +import org.jetbrains.annotations.UnknownNullability; + +public interface IPredicateTestObject { + + IPredicateTestObject INSTANCE = new IPredicateTestObject() {}; + + @UnknownNullability + default Object recombine() { + return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java new file mode 100644 index 0000000000..5f8f52f477 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java @@ -0,0 +1,69 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate.test; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompoundTag; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; +import java.util.function.Predicate; + +public class ItemTestObject implements IPredicateTestObject, Predicate { + + public final Item item; + public final int meta; + public final CompoundTag tag; + + public final int stackLimit; + + private final int hash; + + public ItemTestObject(@NotNull ItemStack stack) { + item = stack.getItem(); + meta = stack.getMetadata(); + tag = stack.getTagCompound(); + stackLimit = stack.getMaxStackSize(); + this.hash = Objects.hash(item, meta, tag); + } + + @Override + @Contract(" -> new") + public ItemStack recombine() { + return new ItemStack(item, 1, meta, tag); + } + + @Contract("_ -> new") + public ItemStack recombine(int amount) { + assert amount <= getStackLimit() && amount > 0; + return new ItemStack(item, amount, meta, tag); + } + + @Override + public boolean test(@NotNull ItemStack stack) { + if (this.stackLimit == stack.getMaxStackSize() && this.item == stack.getItem() && + this.meta == stack.getMetadata()) { + CompoundTag other = stack.getTagCompound(); + return Objects.equals(this.tag, other); + } + return false; + } + + public int getStackLimit() { + return stackLimit; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ItemTestObject that = (ItemTestObject) o; + return meta == that.meta && Objects.equals(item, that.item) && Objects.equals(tag, that.tag); + } + + @Override + public int hashCode() { + return hash; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java new file mode 100644 index 0000000000..70f43ce973 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java @@ -0,0 +1,126 @@ +package com.gregtechceu.gtceu.api.graphnet.servernet; + +import com.gregtechceu.gtceu.api.graphnet.GraphNetBacker; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; + +import net.minecraft.core.GlobalPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.saveddata.SavedData; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Function; + +/** + * Unused demonstration net that would allow for edges bridging dimensions inside the graph representation. + */ +@SuppressWarnings("unused") +public abstract class ServerNet extends SavedData implements IGraphNet { + + protected final GraphNetBacker backer; + + /* + public static ServerNet get(String name, ServerLevel level, Function graphBuilder, + AlgorithmBuilder... algorithmBuilder) { + return level.getDataStorage().computeIfAbsent(tag -> new ServerNet(tag, graphBuilder, algorithmBuilder), () -> new ServerNet(graphBuilder, algorithmBuilder), name); + } + + public static ServerNet get(String name, ServerLevel level, boolean directed, AlgorithmBuilder... algorithmBuilders) { + return get(name, level, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), + algorithmBuilders); + } + */ + + public ServerNet(Function graphBuilder, + AlgorithmBuilder... algorithmBuilders) { + this.backer = new GraphNetBacker(this, graphBuilder.apply(this), algorithmBuilders); + } + + public ServerNet(CompoundTag tag, Function graphBuilder, + AlgorithmBuilder... algorithmBuilders) { + this.backer = new GraphNetBacker(this, graphBuilder.apply(this), algorithmBuilders); + } + + @Override + public void addNode(@NotNull NetNode node) { + nodeClassCheck(node); + this.backer.addNode(node); + } + + public @Nullable ServerNetNode getNode(@NotNull GlobalPos equivalencyData) { + return (ServerNetNode) getNode((Object) equivalencyData); + } + + @Override + public @Nullable NetNode getNode(@NotNull Object equivalencyData) { + return backer.getNode(equivalencyData); + } + + @Override + public void removeNode(@NotNull NetNode node) { + nodeClassCheck(node); + this.backer.removeNode(node); + } + + @Override + public NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays) { + nodeClassCheck(source); + nodeClassCheck(target); + double weight = source.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue() + + target.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue(); + NetEdge edge = backer.addEdge(source, target, weight); + if (bothWays) { + if (this.getGraph().isDirected()) { + backer.addEdge(target, source, weight); + } + return null; + } else return edge; + } + + @Override + public @Nullable NetEdge getEdge(@NotNull NetNode source, @NotNull NetNode target) { + nodeClassCheck(source); + nodeClassCheck(target); + return backer.getEdge(source, target); + } + + @Override + public void removeEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays) { + nodeClassCheck(source); + nodeClassCheck(target); + this.backer.removeEdge(source, target); + if (bothWays && this.getGraph().isDirected()) { + this.backer.removeEdge(target, source); + } + } + + public void load(@NotNull CompoundTag nbt) { + backer.readFromNBT(nbt); + } + + @Override + public @NotNull CompoundTag save(@NotNull CompoundTag compound) { + return backer.writeToNBT(compound); + } + + @Override + public GraphNetBacker getBacker() { + return backer; + } + + @Override + public Class getNodeClass() { + return ServerNetNode.class; + } + + @Override + public @NotNull ServerNetNode getNewNode() { + return new ServerNetNode(this); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java new file mode 100644 index 0000000000..0ec9957140 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java @@ -0,0 +1,37 @@ +package com.gregtechceu.gtceu.api.graphnet.servernet; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import gregtech.api.util.DimensionPos; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.util.math.BlockPos; + +public class ServerNetNode extends NetNode { + + private DimensionPos pos; + + public ServerNetNode(IGraphNet net) { + super(net); + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = super.serializeNBT(); + tag.setLong("Pos", pos.getPos().toLong()); + tag.setInteger("Dim", pos.getDimension()); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + super.deserializeNBT(nbt); + BlockPos pos = BlockPos.fromLong(nbt.getLong("Pos")); + this.pos = new DimensionPos(pos, nbt.getInteger("Dim")); + } + + @Override + public DimensionPos getEquivalencyData() { + return pos; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java new file mode 100644 index 0000000000..d3798c3a48 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java @@ -0,0 +1,45 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.Nullable; + +public abstract class AbstractTraverseData> implements ITraverseData { + + private final IGraphNet net; + private final IPredicateTestObject testObject; + private final SimulatorKey simulator; + private final long queryTick; + + public AbstractTraverseData(IGraphNet net, IPredicateTestObject testObject, SimulatorKey simulator, + long queryTick) { + this.net = net; + this.testObject = testObject; + this.simulator = simulator; + this.queryTick = queryTick; + } + + @Override + public IGraphNet getGraphNet() { + return net; + } + + @Override + public IPredicateTestObject getTestObject() { + return testObject; + } + + @Override + public @Nullable SimulatorKey getSimulatorKey() { + return simulator; + } + + @Override + public long getQueryTick() { + return queryTick; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/DistributorHelper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/DistributorHelper.java new file mode 100644 index 0000000000..fc859e18e8 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/DistributorHelper.java @@ -0,0 +1,24 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +public class DistributorHelper { + + private final long maximum; + private long consumption; + + public DistributorHelper(long maximum, long consumption) { + this.maximum = maximum; + this.consumption = consumption; + } + + public void addConsumption(long consumption) { + this.consumption += consumption; + } + + public boolean supportsMult(long mult) { + return this.maximum >= this.consumption * mult; + } + + public long withMult(long mult) { + return this.consumption * mult; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java new file mode 100644 index 0000000000..c205edb835 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java @@ -0,0 +1,23 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; + +import org.jetbrains.annotations.NotNull; + +public interface IEqualizableTraverseData> extends ITraverseData { + + int getDestinationsAtNode(@NotNull N node); + + /** + * Whether a path should be skipped before running the collection process on it. + * The return of {@link ITraverseData#prepareForPathWalk(INetPath, long)} will be ignored during traversal. + */ + boolean shouldSkipPath(@NotNull P path); + + /** + * Should return how much flow the destination with the smallest maximum allowed flow among destinations at + * this node requires. + */ + long getMaxFlowToLeastDestination(@NotNull N destination); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinData.java new file mode 100644 index 0000000000..51600bfe0b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinData.java @@ -0,0 +1,32 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; + +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public interface IRoundRobinData { + + /** + * Called to notify this {@link IRoundRobinData} to reset its internals to prepare for iteration over internal + * destinations. If this object has not finished progressing over its internal destinations, this should do nothing. + */ + void resetIfFinished(N node, @Nullable SimulatorKey simulator); + + /** + * Similar to {@link Iterator#hasNext()}, this method determines whether there is another internal destination in + * this {@link IRoundRobinData} to finalize at. When false is returned, the RR traversal will move on from + * this {@link IRoundRobinData} + * + * @return whether another internal destination is present + */ + boolean hasNextInternalDestination(N node, @Nullable SimulatorKey simulator); + + /** + * Similar to {@link Iterator#next()}, this is called to notify this {@link IRoundRobinData} that it should + * progress to the next internal destination. + */ + void progressToNextInternalDestination(N node, @Nullable SimulatorKey simulator); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinTraverseData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinTraverseData.java new file mode 100644 index 0000000000..7a984466ed --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IRoundRobinTraverseData.java @@ -0,0 +1,52 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayDeque; + +public interface IRoundRobinTraverseData, N extends NetNode, P extends INetPath> + extends ITraverseData { + + /** + * The traversal cache must be cached and persistent between traversals, + * but not modified by anything external to {@link TraverseHelpers}. + * The traversal cache is (hopefully) modified deterministically between simulated and nonsimulated transfers, but + * remember that modification during simulation must not be reflected on the cache used for nonsimulation. + * The easiest way to accomplish this is to provide a cloned {@link ArrayDeque} during simulated transfers. + * + * @return the traversal cache. + */ + @NotNull + Object2ObjectLinkedOpenHashMap getTraversalCache(); + + /** + * Whether a path should be skipped before checking it against the round robin cache. + * The return of {@link ITraverseData#prepareForPathWalk(INetPath, long)} will be ignored during traversal. + */ + boolean shouldSkipPath(@NotNull P path); + + /** + * @return The {@link IRoundRobinData} for the particular destination. Will be mutated; should then be referenced + * in {@link ITraverseData#finalizeAtDestination(NetNode, long)} to do proper round robin within the + * destination. + */ + @NotNull + T createRRData(@NotNull N destination); + + /** + * Called in preference to {@link ITraverseData#finalizeAtDestination(NetNode, long)} to provide the round robin + * data for the destination. + */ + long finalizeAtDestination(@NotNull T data, @NotNull N destination, long flowReachingDestination); + + /** + * @deprecated use {@link #finalizeAtDestination(IRoundRobinData, NetNode, long)} instead. + */ + @Override + @Deprecated + long finalizeAtDestination(@NotNull N destination, long flowReachingDestination); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseData.java new file mode 100644 index 0000000000..152d3f7b77 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseData.java @@ -0,0 +1,78 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; + +import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface ITraverseData> { + + IGraphNet getGraphNet(); + + IPredicateTestObject getTestObject(); + + @Nullable + SimulatorKey getSimulatorKey(); + + long getQueryTick(); + + /** + * Called before walking the next path. Should reset per-path logics to prepare. + * + * @param path the next path + * @param flow how much flow can be provided to the path. + * @return whether the path should be skipped + */ + boolean prepareForPathWalk(@NotNull P path, long flow); + + /** + * Reports that the traverse is traversing to a node, for additional logic to be run. + * + * @param node the node being traversed + * @param flowReachingNode the flow that has reached this node. + * @return the loss operator for the node. + */ + ReversibleLossOperator traverseToNode(@NotNull N node, long flowReachingNode); + + /** + * Reports that the traverse has finished a path walk, for finalization. + * + * @param destination the active node the path terminated at. + * @param flowReachingDestination the flow that reached the destination + * @return the amount of flow that should be consumed, before walking the next path. + */ + long finalizeAtDestination(@NotNull N destination, long flowReachingDestination); + + /** + * Allows for reporting a smaller capacity along an edge than it actually has. Do not report a larger capacity + * than the actual edge or things will break. + * + * @param edge the edge to get capacity for. + * @return a non-negative capacity that is less than or equal to the true capacity of the edge. + */ + default long getFlowLimit(@NotNull AbstractNetFlowEdge edge) { + return edge.getFlowLimit(this.getTestObject(), this.getGraphNet(), this.getQueryTick(), this.getSimulatorKey()); + } + + /** + * Allows for consuming more than just the edge flow limits on a consumption event. Must always consume the correct + * amount of edge flow or things will break. + * + * @param edge the edge to consume along. + * @param targetNode the target node of the edge. + * @param consumption the amount to consume from the edge's flow limit. + */ + @MustBeInvokedByOverriders + default void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNode, + long consumption) { + edge.consumeFlowLimit(this.getTestObject(), this.getGraphNet(), consumption, this.getQueryTick(), + this.getSimulatorKey()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseGuideProvider.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseGuideProvider.java new file mode 100644 index 0000000000..c4692f1bef --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/ITraverseGuideProvider.java @@ -0,0 +1,15 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import org.jetbrains.annotations.Nullable; + +public interface ITraverseGuideProvider, T extends IPredicateTestObject> { + + @Nullable + > TraverseGuide getGuide( + TraverseDataProvider provider, T testObject, + long flow, boolean simulate); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java new file mode 100644 index 0000000000..63f2ef9222 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java @@ -0,0 +1,15 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import net.minecraft.util.Direction; +import net.minecraft.util.math.BlockPos; + +@FunctionalInterface +public interface TraverseDataProvider, T extends IPredicateTestObject> { + + D of(IGraphNet net, T testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseGuide.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseGuide.java new file mode 100644 index 0000000000..c161835ac3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseGuide.java @@ -0,0 +1,46 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; + +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; +import java.util.function.LongConsumer; +import java.util.function.Supplier; + +public class TraverseGuide, T extends ITraverseData> { + + private final T data; + private final Supplier> pathsSupplier; + private final long flow; + private final LongConsumer consumptionReport; + + public TraverseGuide(T data, Supplier> pathsSupplier, long flow, + @Nullable LongConsumer consumptionReport) { + this.data = data; + this.pathsSupplier = pathsSupplier; + this.flow = flow; + this.consumptionReport = consumptionReport; + } + + public void reportConsumedFlow(long consumedFlow) { + if (consumptionReport != null) consumptionReport.accept(consumedFlow); + } + + public T getData() { + return data; + } + + public Supplier> getPathsSupplier() { + return pathsSupplier; + } + + public Iterator

getPaths() { + return pathsSupplier.get(); + } + + public long getFlow() { + return flow; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java new file mode 100644 index 0000000000..7d8fc8b343 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java @@ -0,0 +1,484 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.FlowConsumptionStack; +import gregtech.api.util.GTUtility; + +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jgrapht.alg.util.Pair; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.LongUnaryOperator; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public final class TraverseHelpers { + + private TraverseHelpers() {} + + /** + * Provides logic for traversing a flow net in a 'flood' manner; + * specifically, find the lowest weight path, fill it to capacity, find the next lowest weight path, etc. + * Requires dynamic weights to function properly. + * + * @param data the traversal data. + * @param paths the paths to traverse. + * @param flowIn the flow to traverse with. + * @return the consumed flow. + */ + public static , + D extends ITraverseData> long traverseFlood( + @NotNull D data, + @NotNull Iterator

paths, + long flowIn) { + boolean simulate = data.getSimulatorKey() != null; + long availableFlow = flowIn; + pathloop: + while (paths.hasNext()) { + List pathTraverseCalls = simulate ? null : new ObjectArrayList<>(); + long pathFlow = availableFlow; + P path = paths.next(); + if (data.prepareForPathWalk(path, pathFlow)) continue; + + List nodes = path.getOrderedNodes(); + List edges = path.getOrderedEdges(); + assert nodes.size() == edges.size() + 1; + + FlowConsumptionStack stack = new FlowConsumptionStack(data.traverseToNode(nodes.get(0), pathFlow)); + pathFlow = stack.applyLatestLossFunction(pathFlow); + + for (int i = 0; i < edges.size(); i++) { + E edge = edges.get(i); + N sourceNode = nodes.get(i); + N targetNode = nodes.get(i + 1); + + if (targetNode.traverse(data.getQueryTick(), true)) { + if (!simulate) { + pathTraverseCalls.add(() -> targetNode.traverse(data.getQueryTick(), false)); + } + } else continue pathloop; + + pathFlow = Math.min(data.getFlowLimit(edge), pathFlow); + stack.add(flow -> data.consumeFlowLimit(edge, targetNode, flow), + data.traverseToNode(targetNode, pathFlow)); + pathFlow = stack.applyLatestLossFunction(pathFlow); + + if (pathFlow <= 0) continue pathloop; + } + + long accepted = data.finalizeAtDestination(nodes.get(nodes.size() - 1), pathFlow); + if (!simulate) pathTraverseCalls.forEach(Runnable::run); + availableFlow -= stack.consumeWithEndValue(accepted); + + if (availableFlow <= 0) break; + } + + return flowIn - availableFlow; + } + + /** + * Provides logic for traversing a net that simply finds the lowest weight path that it can traverse, + * and then traverses it. Optionally supports flow, in which case overflows will be reported + * and paths will be iterated over until flow or paths are exhausted. + * + * @param data the traversal data. + * @param paths the paths to traverse. + * @param overflowListener will be provided with a node and incoming overflow once a path is walked + * and the final overflows are calculated. If null, no overflow logic will be calculated. + * @param flowIn the flow to traverse with. + * @return the consumed flow. + */ + public static , + D extends ITraverseData> long traverseDumb( + @NotNull D data, + @NotNull Iterator

paths, + @Nullable BiConsumer overflowListener, + long flowIn) { + boolean simulate = data.getSimulatorKey() != null; + boolean isFlow = overflowListener != null; + long availableFlow = isFlow ? flowIn : 0; + pathloop: + while (paths.hasNext()) { + List pathTraverseCalls = simulate ? null : new ObjectArrayList<>(); + long pathFlow = isFlow ? availableFlow : 1; + P path = paths.next(); + if (data.prepareForPathWalk(path, pathFlow)) continue; + + List nodes = path.getOrderedNodes(); + List edges = path.getOrderedEdges(); + + List overflowReporters = isFlow ? new ObjectArrayList<>() : null; + assert nodes.size() == edges.size() + 1; + + FlowConsumptionStack stack = isFlow ? + new FlowConsumptionStack(data.traverseToNode(nodes.get(0), pathFlow)) : null; + if (isFlow) pathFlow = stack.applyLatestLossFunction(pathFlow); + + for (int i = 0; i < edges.size(); i++) { + E edge = edges.get(i); + N sourceNode = nodes.get(i); + N targetNode = nodes.get(i + 1); + + if (targetNode.traverse(data.getQueryTick(), true)) { + if (!simulate) { + pathTraverseCalls.add(() -> targetNode.traverse(data.getQueryTick(), false)); + } + } else continue pathloop; + + if (isFlow) { + AbstractNetFlowEdge flowEdge = (AbstractNetFlowEdge) edge; + long limit = data.getFlowLimit(flowEdge); + long overflow = pathFlow - limit; + if (overflow > 0) { + pathFlow = limit; + overflowReporters.add(reduction -> { + long finalOverflow = overflow - reduction; + if (finalOverflow > 0) { + overflowListener.accept(targetNode, finalOverflow); + return finalOverflow; + } + return 0; + }); + } + stack.add(flow -> data.consumeFlowLimit(flowEdge, targetNode, flow), + data.traverseToNode(targetNode, pathFlow)); + pathFlow = stack.applyLatestLossFunction(pathFlow); + } + } + long accepted = data.finalizeAtDestination(nodes.get(edges.size()), pathFlow); + long unaccepted = pathFlow - accepted; + if (isFlow) { + availableFlow -= stack.consumeWithEndValue(accepted) + + overflowReporters.stream().mapToLong(u -> u.applyAsLong(unaccepted)).sum(); + } + if (!simulate) pathTraverseCalls.forEach(Runnable::run); + + if (availableFlow <= 0) break; + } + + return flowIn - availableFlow; + } + + /** + * Provides logic for traversing a flow net in an equal distribution manner. Operates in the following stages: + *
+ *
+ * Stage One (collection) -- collect paths into a list while iterating, gathering a map of edges to flow info. + * Get numbers for what is needed to provide 1 flow per node destination per path, ignoring potential loss. + * If a path cannot be traversed, it is either trimmed or we abort based on {@code strict}. + *
+ *
+ * Stage Two (scaling) -- scale up the mult with a binary search until we get the largest mult where no edge + * capacities are exceeded. If this mult is 0, abort and return 0. + *
+ *
+ * Stage Three (traversal) -- traverse the collected paths and perform consumption and flow, using the multiplier + * from stage two. + * + * @param data the traversal data. + * @param paths the paths to traverse. + * @param flowIn the flow to traverse with. + * @param strict whether to abort if one of the destination paths cannot be traversed due to node restrictions, + * not edge restrictions. + * @return the consumed flow. + */ + public static , + D extends IEqualizableTraverseData> long traverseEqualDistribution( + @NotNull D data, + @NotNull Iterator

paths, + long flowIn, + boolean strict) { + // collection + Map, DistributorHelper> distributorHelperMap = new Object2ObjectOpenHashMap<>(); + Object2IntOpenHashMap

desiredMap = new Object2IntOpenHashMap<>(); + int totalDesired = 0; + long maxMult = flowIn; + pathsloop: + while (paths.hasNext()) { + P path = paths.next(); + if (data.shouldSkipPath(path)) continue; + + List nodes = path.getOrderedNodes(); + List edges = path.getOrderedEdges(); + assert nodes.size() == edges.size() + 1; + for (N node : nodes) { + if (!node.traverse(data.getQueryTick(), true)) { + if (strict) return 0; + else continue pathsloop; + } + } + N dest = nodes.get(nodes.size() - 1); + int desired = data.getDestinationsAtNode(dest); + totalDesired += desired; + desiredMap.put(path, desired); + maxMult = Math.min(maxMult, data.getMaxFlowToLeastDestination(dest)); + for (int i = 0; i < edges.size(); i++) { + E edge = edges.get(i); + N targetNode = nodes.get(i + 1); + distributorHelperMap.compute(Pair.of(edge, targetNode), (k, v) -> { + if (v == null) { + v = new DistributorHelper(k.getFirst().getFlowLimit(data.getTestObject(), + data.getGraphNet(), data.getQueryTick(), data.getSimulatorKey()), desired); + return v; + } else { + v.addConsumption(desired); + return v; + } + }); + } + } + if (totalDesired == 0) return 0; + maxMult = Math.min(maxMult, flowIn / totalDesired); + // scaling + long mult = GTUtility.binarySearch(0, maxMult, l -> { + for (DistributorHelper helper : distributorHelperMap.values()) { + if (!helper.supportsMult(l)) return false; + } + return true; + }, false); + if (mult == 0) return 0; + // traversal + boolean simulate = data.getSimulatorKey() != null; + long availableFlow = flowIn; + pathloop: + for (var entry : desiredMap.object2IntEntrySet()) { + List pathTraverseCalls = simulate ? null : new ObjectArrayList<>(); + long pathFlow = entry.getIntValue() * mult; + P path = entry.getKey(); + + // no skipping paths at this stage + data.prepareForPathWalk(path, pathFlow); + + List nodes = path.getOrderedNodes(); + List edges = path.getOrderedEdges(); + assert nodes.size() == edges.size() + 1; + + FlowConsumptionStack stack = new FlowConsumptionStack(data.traverseToNode(nodes.get(0), pathFlow)); + pathFlow = stack.applyLatestLossFunction(pathFlow); + + for (int i = 0; i < edges.size(); i++) { + E edge = edges.get(i); + N sourceNode = nodes.get(i); + N targetNode = nodes.get(i + 1); + + if (targetNode.traverse(data.getQueryTick(), true)) { + if (!simulate) { + pathTraverseCalls.add(() -> targetNode.traverse(data.getQueryTick(), false)); + } + } else continue pathloop; + + pathFlow = Math.min(data.getFlowLimit(edge), pathFlow); + stack.add(flow -> data.consumeFlowLimit(edge, targetNode, flow), + data.traverseToNode(targetNode, pathFlow)); + pathFlow = stack.applyLatestLossFunction(pathFlow); + + if (pathFlow <= 0) continue pathloop; + } + + long accepted = data.finalizeAtDestination(nodes.get(nodes.size() - 1), pathFlow); + if (!simulate) pathTraverseCalls.forEach(Runnable::run); + availableFlow -= stack.consumeWithEndValue(accepted); + + if (availableFlow <= 0) break; + } + + return flowIn - availableFlow; + } + + /** + * Provides logic for traversing a flow net in an equal distribution manner within a dynamic weights context. + * Calls {@link #traverseEqualDistribution(IEqualizableTraverseData, Iterator, long, boolean)} repeatedly, using a + * fresh + * collection of paths from the {@code pathsSupplier} until + * {@link #traverseEqualDistribution(IEqualizableTraverseData, Iterator, long, boolean)} returns 0 or 100 iterations + * are + * performed. + * + * @param data the traversal data. + * @param pathsSupplier the supplier for a fresh set of paths. + * @param flowIn the flow to traverse with. + * @param strict whether to abort if one of the destination paths cannot be traversed due to node + * restrictions, + * not edge restrictions. + * @return the consumed flow. + */ + public static , + D extends IEqualizableTraverseData> long traverseEqualDistribution( + @NotNull D data, + @NotNull Supplier> pathsSupplier, + long flowIn, + boolean strict) { + long availableFlow = flowIn; + byte iterationCount = 0; + while (iterationCount <= 100) { + iterationCount++; + Iterator

paths = pathsSupplier.get(); + long flow = traverseEqualDistribution(data, paths, availableFlow, strict); + if (flow == 0) break; + else availableFlow -= flow; + } + + return flowIn - availableFlow; + } + + /** + * Provides logic for traversing a flow net in a round robin manner. This implementation merely ensures that + * destinations will be walked to in a predictable manner through the use of a cache, any balancing must + * be done on the {@link ITraverseData}'s end. + * + * @param data the traversal data. + * @param paths the paths to traverse. + * @param flowIn the flow to traverse with. + * @param strict whether to abort if one of the destination paths cannot be traversed due to node restrictions, + * not edge restrictions. + * @return the consumed flow. + */ + public static , N extends NetNode, E extends AbstractNetFlowEdge, + P extends INetPath, D extends IRoundRobinTraverseData> long traverseRoundRobin( + @NotNull D data, + @NotNull Iterator

paths, + long flowIn, + boolean strict) { + long availableFlow = flowIn; + Object2ObjectLinkedOpenHashMap cache = data.getTraversalCache(); + Predicate invalidityCheck = null; + + Map skippedPaths = new Object2ObjectOpenHashMap<>(); + while (paths.hasNext()) { + P path = paths.next(); + if (data.shouldSkipPath(path)) continue; + N destinationNode = path.getTargetNode(); + if (invalidityCheck == null) { + invalidityCheck = d -> { + if (d == null) return false; + NetNode node = destinationNode.getNet().getNode(d); + return node == null || !node.isActive(); + }; + } + Object destIdentifier = destinationNode.getEquivalencyData(); + Object nextUp = cache.isEmpty() ? null : cache.firstKey(); + // filter out invalid equivalency data + while (invalidityCheck.test(nextUp)) { + cache.removeFirst(); + nextUp = cache.isEmpty() ? null : cache.firstKey(); + } + if (destIdentifier.equals(nextUp)) { + // keep iterating over paths in order to collect destinations into the cache + if (availableFlow <= 0) continue; + // path is next up in the ordering, we can traverse. + T rr = cache.get(destIdentifier); + long accepted = rrTraverse(data, path, rr, availableFlow, strict); + if (!rr.hasNextInternalDestination(destinationNode, data.getSimulatorKey())) { + cache.getAndMoveToLast(destIdentifier); + } + if (accepted == -1) return flowIn - availableFlow; + else availableFlow -= accepted; + } else { + // this path isn't the next one up, skip it unless it's a completely new destination. + if (cache.containsKey(destIdentifier)) { + // keep iterating over paths in order to collect destinations into the cache + if (availableFlow <= 0) continue; + skippedPaths.put(destIdentifier, path); + } else { + // keep iterating over paths in order to collect destinations into the cache + if (availableFlow <= 0) { + cache.putAndMoveToFirst(destIdentifier, data.createRRData(destinationNode)); + continue; + } + T rr = data.createRRData(destinationNode); + long accepted = rrTraverse(data, path, rr, availableFlow, strict); + if (rr.hasNextInternalDestination(destinationNode, data.getSimulatorKey())) { + cache.putAndMoveToFirst(destIdentifier, rr); + } else { + cache.putAndMoveToLast(destIdentifier, rr); + } + if (accepted == -1) return flowIn - availableFlow; + else availableFlow -= accepted; + } + } + } + // finally, try and work through skipped paths + while (availableFlow > 0) { + Object nextUp = cache.isEmpty() ? null : cache.firstKey(); + if (nextUp == null) break; + P path = skippedPaths.get(nextUp); + if (path == null) break; + assert invalidityCheck != null; // skipped paths would be empty if invalidity check is null + if (invalidityCheck.test(nextUp)) { + cache.removeFirst(); + continue; + } + T rr = data.createRRData(path.getTargetNode()); + long accepted = rrTraverse(data, path, rr, availableFlow, strict); + if (!rr.hasNextInternalDestination(path.getTargetNode(), data.getSimulatorKey())) { + cache.getAndMoveToLast(nextUp); + } + if (accepted == -1) return flowIn - availableFlow; + else availableFlow -= accepted; + } + + return flowIn - availableFlow; + } + + private static , N extends NetNode, E extends AbstractNetFlowEdge, + P extends INetPath, D extends ITraverseData & IRoundRobinTraverseData> long rrTraverse( + @NotNull D data, + @NotNull P path, + @NotNull T rr, + long flowIn, + boolean strict) { + boolean simulate = data.getSimulatorKey() != null; + List pathTraverseCalls = simulate ? null : new ObjectArrayList<>(); + long pathFlow = flowIn; + + data.prepareForPathWalk(path, pathFlow); + + List nodes = path.getOrderedNodes(); + List edges = path.getOrderedEdges(); + assert nodes.size() == edges.size() + 1; + + FlowConsumptionStack stack = new FlowConsumptionStack(data.traverseToNode(nodes.get(0), pathFlow)); + pathFlow = stack.applyLatestLossFunction(pathFlow); + + for (int i = 0; i < edges.size(); i++) { + E edge = edges.get(i); + N sourceNode = nodes.get(i); + N targetNode = nodes.get(i + 1); + + if (targetNode.traverse(data.getQueryTick(), true)) { + if (!simulate) { + pathTraverseCalls.add(() -> targetNode.traverse(data.getQueryTick(), false)); + } + } else return strict ? -1 : 0; + + pathFlow = Math.min(data.getFlowLimit(edge), pathFlow); + stack.add(flow -> data.consumeFlowLimit(edge, targetNode, flow), + data.traverseToNode(targetNode, pathFlow)); + pathFlow = stack.applyLatestLossFunction(pathFlow); + + if (pathFlow <= 0) return 0; + } + N dest = nodes.get(nodes.size() - 1); + rr.resetIfFinished(dest, data.getSimulatorKey()); + long accepted = 0; + while (rr.hasNextInternalDestination(dest, data.getSimulatorKey())) { + rr.progressToNextInternalDestination(dest, data.getSimulatorKey()); + accepted += data.finalizeAtDestination(rr, dest, pathFlow - accepted); + if (accepted == pathFlow) break; + } + if (!simulate) pathTraverseCalls.forEach(Runnable::run); + + return stack.consumeWithEndValue(accepted); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompleteLossOperator.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompleteLossOperator.java new file mode 100644 index 0000000000..0da8a9e548 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompleteLossOperator.java @@ -0,0 +1,18 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse.util; + +public class CompleteLossOperator implements ReversibleLossOperator { + + public static final CompleteLossOperator INSTANCE = new CompleteLossOperator(); + + private CompleteLossOperator() {} + + @Override + public double applyLoss(double value) { + return 0; + } + + @Override + public double undoLoss(double value) { + return 0; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompositeLossOperator.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompositeLossOperator.java new file mode 100644 index 0000000000..37c683cd81 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/CompositeLossOperator.java @@ -0,0 +1,22 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse.util; + +public class CompositeLossOperator implements ReversibleLossOperator { + + private final ReversibleLossOperator first; + private final ReversibleLossOperator second; + + public CompositeLossOperator(ReversibleLossOperator first, ReversibleLossOperator second) { + this.first = first; + this.second = second; + } + + @Override + public double applyLoss(double value) { + return second.applyLoss(first.applyLoss(value)); + } + + @Override + public double undoLoss(double value) { + return first.undoLoss(second.undoLoss(value)); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlatLossOperator.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlatLossOperator.java new file mode 100644 index 0000000000..49e5483864 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlatLossOperator.java @@ -0,0 +1,21 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse.util; + +public class FlatLossOperator implements ReversibleLossOperator { + + private final double loss; + + public FlatLossOperator(double loss) { + assert loss > 0; + this.loss = loss; + } + + @Override + public double applyLoss(double value) { + return value - loss; + } + + @Override + public double undoLoss(double value) { + return value + loss; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlowConsumptionStack.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlowConsumptionStack.java new file mode 100644 index 0000000000..d5247e5455 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/FlowConsumptionStack.java @@ -0,0 +1,49 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse.util; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; +import java.util.function.LongConsumer; + +public class FlowConsumptionStack { + + private final List flowConsumers = new ObjectArrayList<>(); + + private final List operators = new ObjectArrayList<>(); + + private final ReversibleLossOperator initialOperator; + + public FlowConsumptionStack() { + this.initialOperator = ReversibleLossOperator.IDENTITY; + } + + public FlowConsumptionStack(ReversibleLossOperator initialOperator) { + this.initialOperator = initialOperator; + } + + public long applyLatestLossFunction(long value) { + if (operators.isEmpty()) return (long) Math.floor(initialOperator.applyLoss(value)); + else return (long) Math.floor(operators.get(operators.size() - 1).applyLoss(value)); + } + + public void add(LongConsumer flowConsumer, ReversibleLossOperator postLoss) { + flowConsumers.add(flowConsumer); + operators.add(postLoss); + } + + /** + * Walks backwards along the loss operators and applies consumption to flow consumers. + * + * @param endValue the target end value + * @return the value that needs to be pushed into the start of the stack to achieve the end value. + */ + public long consumeWithEndValue(long endValue) { + double value = endValue; + for (int i = operators.size() - 1; i >= 0; i--) { + ReversibleLossOperator operator = operators.get(i); + value = operator.undoLoss(value); + flowConsumers.get(i).accept((long) Math.ceil(value)); + } + return (long) Math.ceil(initialOperator.undoLoss(value)); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/MultLossOperator.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/MultLossOperator.java new file mode 100644 index 0000000000..a111af4119 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/MultLossOperator.java @@ -0,0 +1,34 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse.util; + +public class MultLossOperator implements ReversibleLossOperator { + + public static final MultLossOperator[] TENTHS = new MultLossOperator[10]; + + public static final MultLossOperator[] EIGHTHS = new MultLossOperator[8]; + + static { + for (int i = 1; i < 10; i++) { + TENTHS[i] = new MultLossOperator(0.1d * i); + } + for (int i = 1; i < 8; i++) { + EIGHTHS[i] = new MultLossOperator(0.125d * i); + } + } + + private final double mult; + + public MultLossOperator(double mult) { + assert mult > 0 && mult <= 1; + this.mult = mult; + } + + @Override + public double applyLoss(double value) { + return value * mult; + } + + @Override + public double undoLoss(double value) { + return value / mult; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/ReversibleLossOperator.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/ReversibleLossOperator.java new file mode 100644 index 0000000000..006919e28f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/util/ReversibleLossOperator.java @@ -0,0 +1,21 @@ +package com.gregtechceu.gtceu.api.graphnet.traverse.util; + +public interface ReversibleLossOperator { + + ReversibleLossOperator IDENTITY = new ReversibleLossOperator() { + + @Override + public double applyLoss(double value) { + return value; + } + + @Override + public double undoLoss(double value) { + return value; + } + }; + + double applyLoss(double value); + + double undoLoss(double value); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java new file mode 100644 index 0000000000..a2d4fcb6b4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -0,0 +1,152 @@ +package com.gregtechceu.gtceu.api.graphnet.worldnet; + +import com.gregtechceu.gtceu.api.graphnet.GraphNetBacker; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import com.gregtechceu.gtceu.api.graphnet.graph.NetDirectedGraph; +import com.gregtechceu.gtceu.api.graphnet.graph.NetUndirectedGraph; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.path.GenericGraphNetPath; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + +import lombok.Getter; +import lombok.Setter; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.storage.WorldSavedData; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; +import java.util.function.Function; + +public abstract class WorldNet extends WorldSavedData implements IGraphNet, GenericGraphNetPath.Provider { + + protected final GraphNetBacker backer; + @Getter + @Setter + private Level level; + private ResourceKey fallbackDimension; + + public WorldNet(String name, @NotNull Function graphBuilder, + AlgorithmBuilder... algorithmBuilders) { + super(name); + this.backer = new GraphNetBacker(this, graphBuilder.apply(this), algorithmBuilders); + } + + public WorldNet(String name, boolean directed, AlgorithmBuilder... algorithmBuilders) { + this(name, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), + algorithmBuilders); + } + + @Override + public Iterator getPaths(NetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + nodeClassCheck(node); + return backer.getPaths(node, 0, GenericGraphNetPath.MAPPER, testObject, simulator, queryTick); + } + + @NotNull + public WorldNetNode getOrCreateNode(@NotNull BlockPos pos) { + WorldNetNode node = getNode(pos); + if (node != null) return node; + node = getNewNode(); + node.setPos(pos); + addNode(node); + return node; + } + + @Override + public void addNode(@NotNull NetNode node) { + nodeClassCheck(node); + this.backer.addNode(node); + } + + public @Nullable WorldNetNode getNode(@NotNull BlockPos equivalencyData) { + return (WorldNetNode) getNode((Object) equivalencyData); + } + + @Override + public @Nullable NetNode getNode(@NotNull Object equivalencyData) { + return backer.getNode(equivalencyData); + } + + @Override + public void removeNode(@NotNull NetNode node) { + nodeClassCheck(node); + this.backer.removeNode(node); + } + + @Override + public NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays) { + nodeClassCheck(source); + nodeClassCheck(target); + double weight = source.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue() + + target.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue(); + NetEdge edge = backer.addEdge(source, target, weight); + if (bothWays) { + if (this.getGraph().isDirected()) { + backer.addEdge(target, source, weight); + } + return null; + } else return edge; + } + + @Override + public @Nullable NetEdge getEdge(@NotNull NetNode source, @NotNull NetNode target) { + nodeClassCheck(source); + nodeClassCheck(target); + return backer.getEdge(source, target); + } + + @Override + public void removeEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays) { + nodeClassCheck(source); + nodeClassCheck(target); + this.backer.removeEdge(source, target); + if (bothWays && this.getGraph().isDirected()) { + this.backer.removeEdge(target, source); + } + } + + protected ResourceKey getDimension() { + if (level == null) return fallbackDimension; + else return level.dimension(); + } + + public void load(@NotNull CompoundTag nbt) { + fallbackDimension = ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("Dimension"))); + backer.readFromNBT(nbt); + } + + public @NotNull CompoundTag save(@NotNull CompoundTag compound) { + compound.putString("Dimension", getDimension().location().toString()); + return backer.writeToNBT(compound); + } + + @Override + public GraphNetBacker getBacker() { + return backer; + } + + @Override + public Class getNodeClass() { + return WorldNetNode.class; + } + + @Override + public @NotNull WorldNetNode getNewNode() { + return new WorldNetNode(this); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNetNode.java new file mode 100644 index 0000000000..cce387e1d9 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNetNode.java @@ -0,0 +1,45 @@ +package com.gregtechceu.gtceu.api.graphnet.worldnet; + +import com.gregtechceu.gtceu.api.graphnet.NetNode; + +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; + +import org.jetbrains.annotations.NotNull; + +public class WorldNetNode extends NetNode { + + private BlockPos pos; + + public WorldNetNode(WorldNet net) { + super(net); + } + + @Override + public @NotNull WorldNet getNet() { + return (WorldNet) super.getNet(); + } + + public WorldNetNode setPos(BlockPos pos) { + this.pos = pos; + return this; + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = super.serializeNBT(); + tag.putLong("Pos", pos.asLong()); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + super.deserializeNBT(nbt); + this.setPos(BlockPos.of(nbt.getLong("Pos"))); + } + + @Override + public BlockPos getEquivalencyData() { + return pos; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java index 03bf79b543..22b20bc8b5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java @@ -137,7 +137,7 @@ public void entityInside(BlockState state, Level level, BlockPos pos, Entity ent entityLiving.hurt(GTDamageTypes.ELECTRIC.source(level), damageAmount); if (entityLiving instanceof ServerPlayer) { // TODO advancments - // AdvancementTriggers.ELECTROCUTION_DEATH.trigger((EntityPlayerMP) entityLiving); + // AdvancementTriggers.ELECTROCUTION_DEATH.trigger((PlayerMP) entityLiving); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/EntityDamageUtil.java b/src/main/java/com/gregtechceu/gtceu/utils/EntityDamageUtil.java index c84a436752..a29a54e367 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/EntityDamageUtil.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/EntityDamageUtil.java @@ -83,7 +83,7 @@ public static void applyFrostDamage(@NotNull LivingEntity entity, int damage) { entity.hurt(entity.damageSources().freeze(), damage); // TODO advancements // if (entity instanceof ServerPlayer) { - // AdvancementTriggers.COLD_DEATH.trigger((EntityPlayerMP) entity); + // AdvancementTriggers.COLD_DEATH.trigger((PlayerMP) entity); // } } @@ -102,6 +102,6 @@ public static void applyChemicalDamage(@NotNull LivingEntity entity, int damage) entity.hurt(GTDamageTypes.CHEMICAL.source(entity.level()), damage); entity.addEffect(new MobEffectInstance(MobEffects.POISON, damage * 100, 1)); // TODO advancements - // if (entity instanceof ServerPlayer) AdvancementTriggers.CHEMICAL_DEATH.trigger((EntityPlayerMP) entity); + // if (entity instanceof ServerPlayer) AdvancementTriggers.CHEMICAL_DEATH.trigger((PlayerMP) entity); } } From a42e55f5bf07aa9ab9b8301063a4a3f5a816c22e Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Wed, 21 Aug 2024 15:03:42 +0300 Subject: [PATCH 02/70] stuff --- .../gtceu/api/cover/CoverDefinition.java | 4 +- .../api/graphnet/logic/NetLogicEntry.java | 5 +- .../graphnet/pipenet/IPipeNetNodeHandler.java | 22 +- .../api/graphnet/pipenet/WorldPipeNet.java | 2 +- .../graphnet/pipenet/WorldPipeNetNode.java | 10 +- .../logic/EdgeCoverReferenceLogic.java | 10 +- .../pipenet/logic/TemperatureLogic.java | 63 +- .../logic/TemperatureLossFunction.java | 17 +- .../graphnet/pipenet/physical/IBurnable.java | 14 +- .../graphnet/pipenet/physical/IFreezable.java | 12 +- .../physical/IPipeCapabilityObject.java | 4 +- .../physical/IPipeMaterialStructure.java | 4 +- .../physical/block/ItemMaterialPipeBlock.java | 32 - .../pipenet/physical/block/ItemPipeBlock.java | 51 -- .../physical/block/MaterialPipeBlockItem.java | 36 ++ .../physical/block/PipeActivableBlock.java | 10 +- .../pipenet/physical/block/PipeBlock.java | 576 +++++++----------- .../pipenet/physical/block/PipeBlockItem.java | 47 ++ .../physical/block/PipeMaterialBlock.java | 128 ++-- .../pipenet/physical/block/RayTraceAABB.java | 35 -- .../physical/tile/IWorldPipeNetTile.java | 6 +- .../physical/tile/PipeBlockEntity.java | 120 +++- .../physical/tile/PipeCoverHolder.java | 65 +- .../physical/tile/PipeMaterialTileEntity.java | 4 +- .../traverse/AbstractTileRoundRobinData.java | 6 +- .../gtceu/api/pattern/BlockPattern.java | 2 +- .../gtceu/api/pattern/MultiblockState.java | 2 +- .../gtceu/api/pattern/Predicates.java | 2 +- .../pattern/predicates/SimplePredicate.java | 2 +- .../common/block/KineticMachineBlock.java | 6 +- .../blockentity/ItemPipeBlockEntity.java | 2 +- .../gtceu/common/data/GTRecipes.java | 4 +- .../multiblock/electric/CleanroomMachine.java | 28 +- .../research/ResearchStationMachine.java | 4 +- .../CleaningMaintenanceHatchPartMachine.java | 4 +- .../part/MaintenanceHatchPartMachine.java | 4 +- .../multiblock/part/ObjectHolderMachine.java | 4 +- .../machine/trait/miner/SteamMinerLogic.java | 6 +- .../longdistance/LDItemEndpointMachine.java | 4 +- .../gtceu/core/mixins/LevelMixin.java | 2 +- .../core/mixins/ServerChunkProviderMixin.java | 2 +- .../gtceu/data/lang/LangHandler.java | 2 +- .../data/recipe/misc/CreateRecipeLoader.java | 2 +- .../recipe/misc/MetaTileEntityLoader.java | 2 +- .../MetaTileEntityMachineRecipeLoader.java | 2 +- .../jade/provider/RecipeLogicProvider.java | 2 +- .../top/provider/RecipeLogicInfoProvider.java | 2 +- 47 files changed, 635 insertions(+), 738 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java index 30fb5b9177..7e05c81908 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java @@ -32,7 +32,7 @@ public CoverDefinition(ResourceLocation id, CoverBehaviourProvider behaviorCreat this.coverRenderer = coverRenderer; } - public CoverBehavior createCoverBehavior(ICoverable metaTileEntity, Direction side) { - return behaviorCreator.create(this, metaTileEntity, side); + public CoverBehavior createCoverBehavior(ICoverable metaBlockEntity, Direction side) { + return behaviorCreator.create(this, metaBlockEntity, side); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java index 8040301964..4f4f3e669e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.graphnet.NetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.lowdragmc.lowdraglib.networking.IPacket; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.StringRepresentable; @@ -17,7 +18,7 @@ * {@link #union(NetLogicEntry)} behavior. */ public abstract class NetLogicEntry, N extends Tag> - implements INBTSerializable, StringRepresentable { + implements INBTSerializable, StringRepresentable, IPacket { private final @NotNull String name; @@ -105,6 +106,7 @@ public boolean shouldEncode() { return true; } + @Override public final void encode(FriendlyByteBuf buf) { encode(buf, true); } @@ -115,6 +117,7 @@ public final void encode(FriendlyByteBuf buf) { */ public abstract void encode(FriendlyByteBuf buf, boolean fullChange); + @Override public final void decode(FriendlyByteBuf buf) { decode(buf, true); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java index bac3755c1a..2a14200ee9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java @@ -2,11 +2,13 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -15,14 +17,14 @@ public interface IPipeNetNodeHandler { @NotNull - Collection getOrCreateFromNets(World world, BlockPos pos, IPipeStructure structure); + Collection getOrCreateFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure); @NotNull - Collection getFromNets(World world, BlockPos pos, IPipeStructure structure); + Collection getFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure); - void removeFromNets(World world, BlockPos pos, IPipeStructure structure); + void removeFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure); - void addInformation(@NotNull ItemStack stack, World worldIn, @NotNull List tooltip, - @NotNull ITooltipFlag flagIn, + void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeStructure structure); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index c1a839ae47..ade342a614 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -172,7 +172,7 @@ public void synchronizeNode(WorldPipeNetNode node) { }); } - public static String getDataID(final String baseID, final World world) { + public static String getDataID(final String baseID, final Level world) { if (world == null || world.isRemote) throw new RuntimeException("WorldPipeNets should only be created on the server!"); int dimension = world.provider.getDimension(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java index ac81ae79ef..ef292d7bfe 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -26,8 +26,8 @@ public WorldPipeNetNode(WorldPipeNet net) { super(net); } - public @NotNull IWorldPipeNetTile getTileEntity() { - IWorldPipeNetTile tile = getTileEntity(true); + public @NotNull IWorldPipeNetTile getBlockEntity() { + IWorldPipeNetTile tile = getBlockEntity(true); if (tile == null) { // something went very wrong, return the fallback to prevent NPEs and remove us from the net. getNet().removeNode(this); @@ -37,11 +37,11 @@ public WorldPipeNetNode(WorldPipeNet net) { } @Nullable - public IWorldPipeNetTile getTileEntityNoLoading() { - return getTileEntity(false); + public IWorldPipeNetTile getBlockEntityNoLoading() { + return getBlockEntity(false); } - private IWorldPipeNetTile getTileEntity(boolean allowLoading) { + private IWorldPipeNetTile getBlockEntity(boolean allowLoading) { if (tileReference != null) { IWorldPipeNetTile tile = tileReference.get(); if (tile != null) return tile; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java index 46c68c8780..ab7e2ba899 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java @@ -7,7 +7,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.network.PacketBuffer; -import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.BlockEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -52,10 +52,10 @@ public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @Not if (coverSource == null) return null; Cover ref = coverSource.get(); if (ref == null) { - World world = DimensionManager.getWorld(coverSourcePos.getDimension()); + Level world = DimensionManager.getWorld(coverSourcePos.getDimension()); if (world == null || !world.isBlockLoaded(coverSourcePos.getPos())) return null; - TileEntity tile = world.getTileEntity(coverSourcePos.getPos()); + BlockEntity tile = world.getBlockEntity(coverSourcePos.getPos()); if (tile instanceof PipeBlockEntity pipe) { Cover cover = pipe.getCoverHolder().getCoverAtSide(coverSourcePos.getFacing()); if (cover != null) { @@ -81,10 +81,10 @@ public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @Not if (coverTarget == null) return null; Cover ref = coverTarget.get(); if (ref == null) { - World world = DimensionManager.getWorld(coverTargetPos.getDimension()); + Level world = DimensionManager.getWorld(coverTargetPos.getDimension()); if (world == null || !world.isBlockLoaded(coverTargetPos.getPos())) return null; - TileEntity tile = world.getTileEntity(coverTargetPos.getPos()); + BlockEntity tile = world.getBlockEntity(coverTargetPos.getPos()); if (tile instanceof PipeBlockEntity pipe) { Cover cover = pipe.getCoverHolder().getCoverAtSide(coverTargetPos.getFacing()); if (cover != null) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index 338d8410dc..962b0c4a88 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -10,15 +10,12 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; import com.gregtechceu.gtceu.api.graphnet.traverse.util.CompleteLossOperator; import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; -import gregtech.client.particle.GTOverheatParticle; - -import net.minecraft.block.state.IBlockState; +import com.lowdragmc.lowdraglib.Platform; +import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.common.FMLCommonHandler; - +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -118,31 +115,31 @@ public NodeLossResult getLossResult(long tick) { int temp = getTemperature(tick); if (isUnderMinimum(temp)) { return new NodeLossResult(n -> { - World world = n.getNet().getLevel(); + Level world = n.getNet().getLevel(); BlockPos pos = n.getEquivalencyData(); - IBlockState state = world.getBlockState(pos); + BlockState state = world.getBlockState(pos); if (state.getBlock() instanceof IFreezable freezable) { freezable.fullyFreeze(state, world, pos); } else { - world.setBlockToAir(pos); + world.removeBlock(pos, false); } }, CompleteLossOperator.INSTANCE); } else if (isOverMaximum(temp)) { return new NodeLossResult(n -> { - World world = n.getNet().getLevel(); + Level world = n.getNet().getLevel(); BlockPos pos = n.getEquivalencyData(); - IBlockState state = world.getBlockState(pos); + BlockState state = world.getBlockState(pos); if (state.getBlock() instanceof IBurnable burnable) { burnable.fullyBurn(state, world, pos); } else { - world.setBlockToAir(pos); + world.removeBlock(pos, false); } }, CompleteLossOperator.INSTANCE); } else if (isOverPartialBurnThreshold(temp)) { return new NodeLossResult(n -> { - World world = n.getNet().getLevel(); + Level world = n.getNet().getLevel(); BlockPos pos = n.getEquivalencyData(); - IBlockState state = world.getBlockState(pos); + BlockState state = world.getBlockState(pos); if (state.getBlock() instanceof IBurnable burnable) { burnable.partialBurn(state, world, pos); } @@ -271,31 +268,31 @@ public void merge(NetNode otherOwner, NetLogicEntry unknown) { @Override public CompoundTag serializeNBT() { CompoundTag tag = new CompoundTag(); - tag.setFloat("ThermalEnergy", this.energy); - tag.setInteger("TemperatureMax", this.temperatureMaximum); - tag.setInteger("TemperatureMin", this.temperatureMinimum); - tag.setInteger("ThermalMass", this.thermalMass); - tag.setTag("RestorationFunction", this.temperatureLossFunction.serializeNBT()); - tag.setInteger("FunctionPrio", this.functionPriority); - if (partialBurnTemperature != null) tag.setInteger("PartialBurn", partialBurnTemperature); + tag.putFloat("ThermalEnergy", this.energy); + tag.putInt("TemperatureMax", this.temperatureMaximum); + tag.putInt("TemperatureMin", this.temperatureMinimum); + tag.putInt("ThermalMass", this.thermalMass); + tag.put("RestorationFunction", this.temperatureLossFunction.serializeNBT()); + tag.putInt("FunctionPrio", this.functionPriority); + if (partialBurnTemperature != null) tag.putInt("PartialBurn", partialBurnTemperature); return tag; } @Override public void deserializeNBT(CompoundTag nbt) { this.energy = nbt.getFloat("ThermalEnergy"); - this.temperatureMaximum = nbt.getInteger("TemperatureMax"); - this.temperatureMinimum = nbt.getInteger("TemperatureMin"); - this.thermalMass = nbt.getInteger("ThermalMass"); - this.temperatureLossFunction = new TemperatureLossFunction(nbt.getCompoundTag("RestorationFunction")); - this.functionPriority = nbt.getInteger("FunctionPrio"); - if (nbt.hasKey("PartialBurn")) { - this.partialBurnTemperature = nbt.getInteger("PartialBurn"); + this.temperatureMaximum = nbt.getInt("TemperatureMax"); + this.temperatureMinimum = nbt.getInt("TemperatureMin"); + this.thermalMass = nbt.getInt("ThermalMass"); + this.temperatureLossFunction = new TemperatureLossFunction(nbt.getCompound("RestorationFunction")); + this.functionPriority = nbt.getInt("FunctionPrio"); + if (nbt.contains("PartialBurn")) { + this.partialBurnTemperature = nbt.getInt("PartialBurn"); } else this.partialBurnTemperature = null; } @Override - public void encode(PacketBuffer buf, boolean fullChange) { + public void encode(FriendlyByteBuf buf, boolean fullChange) { buf.writeFloat(this.energy); if (fullChange) { buf.writeVarInt(this.temperatureMaximum); @@ -311,8 +308,8 @@ public void encode(PacketBuffer buf, boolean fullChange) { } @Override - public void decode(PacketBuffer buf, boolean fullChange) { - this.lastRestorationTick = FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter(); + public void decode(FriendlyByteBuf buf, boolean fullChange) { + this.lastRestorationTick = Platform.getMinecraftServer().getTickCount(); this.energy = buf.readFloat(); if (fullChange) { this.temperatureMaximum = buf.readVarInt(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java index 0709b6a9a8..6a98a05cb0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java @@ -1,9 +1,8 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; -import gregtech.api.network.IPacket; - +import com.lowdragmc.lowdraglib.networking.IPacket; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.PacketBuffer; +import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.common.util.INBTSerializable; import it.unimi.dsi.fastutil.floats.Float2ObjectArrayMap; @@ -60,28 +59,28 @@ public static TemperatureLossFunction getOrCreatePipe(float factor) { @Override public CompoundTag serializeNBT() { CompoundTag tag = new CompoundTag(); - tag.setInteger("Ordinal", function.ordinal()); - tag.setFloat("X", factorX); - if (factorY != 0) tag.setFloat("Y", factorY); + tag.putInt("Ordinal", function.ordinal()); + tag.putFloat("X", factorX); + if (factorY != 0) tag.putFloat("Y", factorY); return tag; } @Override public void deserializeNBT(CompoundTag nbt) { - function = EnumLossFunction.values()[nbt.getInteger("Ordinal")]; + function = EnumLossFunction.values()[nbt.getInt("Ordinal")]; factorX = nbt.getFloat("X"); factorY = nbt.getFloat("Y"); } @Override - public void encode(PacketBuffer buf) { + public void encode(FriendlyByteBuf buf) { buf.writeVarInt(function.ordinal()); buf.writeFloat(factorX); buf.writeFloat(factorY); } @Override - public void decode(PacketBuffer buf) { + public void decode(FriendlyByteBuf buf) { function = EnumLossFunction.values()[buf.readVarInt()]; factorX = buf.readFloat(); factorY = buf.readFloat(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java index 9438bc3d2f..6a622a24cf 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java @@ -1,9 +1,9 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; public interface IBurnable { @@ -11,13 +11,13 @@ public interface IBurnable { * Called when the block should be partially burned.
* Allows for partial burns with reference to temperature logic, used in insulated cables for example. */ - default void partialBurn(IBlockState state, World world, BlockPos pos) {} + default void partialBurn(BlockState state, Level world, BlockPos pos) {} /** * Called when the block should be fully burned. */ - default void fullyBurn(IBlockState state, World world, BlockPos pos) { + default void fullyBurn(BlockState state, Level world, BlockPos pos) { assert Blocks.FIRE != null; - world.setBlockState(pos, Blocks.FIRE.getDefaultState()); + world.setBlockAndUpdate(pos, Blocks.FIRE.defaultBlockState()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java index a23f1c3f16..f97200d0d5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IFreezable.java @@ -1,17 +1,17 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; public interface IFreezable { /** * Called when the block should be fully frozen. */ - default void fullyFreeze(IBlockState state, World world, BlockPos pos) { + default void fullyFreeze(BlockState state, Level world, BlockPos pos) { assert Blocks.FROSTED_ICE != null; - world.setBlockState(pos, Blocks.FROSTED_ICE.getDefaultState()); + world.setBlockAndUpdate(pos, Blocks.FROSTED_ICE.defaultBlockState()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java index d57ed7312e..a9f52e7492 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java @@ -2,9 +2,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import net.minecraft.core.Direction; import net.minecraft.util.Direction; import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; import org.jetbrains.annotations.Nullable; public interface IPipeCapabilityObject { @@ -13,5 +15,5 @@ public interface IPipeCapabilityObject { Capability[] getCapabilities(); - T getCapabilityForSide(Capability capability, @Nullable Direction facing); + LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java index 605027d4a6..e1d1ca323e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java @@ -1,8 +1,8 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; -import gregtech.api.unification.ore.OrePrefix; +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; public interface IPipeMaterialStructure extends IPipeStructure { - OrePrefix getOrePrefix(); + TagPrefix getTagPrefix(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java deleted file mode 100644 index d9b3819484..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemMaterialPipeBlock.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; - -import gregtech.api.unification.material.Material; - -import net.minecraft.item.ItemStack; - -import org.jetbrains.annotations.NotNull; - -public class ItemMaterialPipeBlock extends ItemPipeBlock { - - public ItemMaterialPipeBlock(PipeMaterialBlock block) { - super(block); - setHasSubtypes(true); - } - - @Override - public int getMetadata(int damage) { - return damage; - } - - @Override - public @NotNull PipeMaterialBlock getBlock() { - return (PipeMaterialBlock) super.getBlock(); - } - - @NotNull - @Override - public String getItemStackDisplayName(@NotNull ItemStack stack) { - Material material = getBlock().getMaterialForStack(stack); - return material == null ? "unnamed" : getBlock().getStructure().getOrePrefix().getLocalNameForItem(material); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java deleted file mode 100644 index 4da96e50b4..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ItemPipeBlock.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; - -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import gregtech.common.items.MetaItems; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.Player; -import net.minecraft.item.EnumDyeColor; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Direction; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import org.jetbrains.annotations.NotNull; - -public class ItemPipeBlock extends ItemBlock { - - public ItemPipeBlock(PipeBlock block) { - super(block); - } - - @Override - public @NotNull PipeBlock getBlock() { - return (PipeBlock) super.getBlock(); - } - - @Override - public boolean placeBlockAt(@NotNull ItemStack stack, @NotNull Player player, @NotNull World world, - @NotNull BlockPos pos, @NotNull Direction side, - float hitX, float hitY, float hitZ, @NotNull IBlockState newState) { - if (super.placeBlockAt(stack, player, world, pos, side, hitX, hitY, hitZ, newState)) { - ItemStack offhand = player.getHeldItemOffhand(); - for (int i = 0; i < EnumDyeColor.values().length; i++) { - if (offhand.isItemEqual(MetaItems.SPRAY_CAN_DYES[i].getStackForm())) { - MetaItems.SPRAY_CAN_DYES[i].getBehaviours().get(0).onItemUse(player, world, - pos, EnumHand.OFF_HAND, Direction.UP, 0, 0, 0); - break; - } - } - - PipeBlockEntity tile = getBlock().getTileEntity(world, pos); - if (tile != null) { - tile.placedBy(stack, player); - getBlock().doPlacementLogic(tile, side.getOpposite()); - } - return true; - } else return false; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java new file mode 100644 index 0000000000..b0411066a5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -0,0 +1,36 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import gregtech.api.unification.material.Material; + +import net.minecraft.item.ItemStack; + +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.NotNull; + +public class MaterialPipeBlockItem extends PipeBlockItem { + + public MaterialPipeBlockItem(Item.Properties properties, PipeMaterialBlock block) { + super(block, properties); + } + + @Override + public @NotNull PipeMaterialBlock getBlock() { + return (PipeMaterialBlock) super.getBlock(); + } + + @Override + public Component getName(ItemStack stack) { + Material material = getBlock().getMaterialForStack(stack); + return material == null ? "unnamed" : getBlock().getStructure().getTagPrefix().getLocalNameForItem(material); + } + + @NotNull + @Override + public String getItemStackDisplayName(@NotNull ItemStack stack) { + Material material = getBlock().getMaterialForStack(stack); + return material == null ? "unnamed" : getBlock().getStructure().getTagPrefix().getLocalNameForItem(material); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java index 2a91fb81fa..c87e69eb46 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java @@ -7,8 +7,8 @@ import gregtech.client.renderer.pipe.ActivablePipeModel; import net.minecraft.block.state.BlockStateContainer; -import net.minecraft.block.state.IBlockState; -import net.minecraft.tileentity.TileEntity; +import net.minecraft.block.state.BlockState; +import net.minecraft.tileentity.BlockEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -30,17 +30,17 @@ public PipeActivableBlock(IPipeStructure structure) { } @Override - public Class getTileClass(@NotNull World world, @NotNull IBlockState state) { + public Class getTileClass(@NotNull Level world, @NotNull BlockState state) { return PipeActivableBlockEntity.class; } @Override - public @Nullable PipeActivableBlockEntity getTileEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { + public @Nullable PipeActivableBlockEntity getBlockEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { if (GTUtility.arePosEqual(lastTilePos.get(), pos)) { PipeBlockEntity tile = lastTile.get().get(); if (tile != null && !tile.isInvalid()) return (PipeActivableBlockEntity) tile; } - TileEntity tile = world.getTileEntity(pos); + BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof PipeActivableBlockEntity pipe) { lastTilePos.set(pos.toImmutable()); lastTile.set(new WeakReference<>(pipe)); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index be5f62b220..dff20c31cb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -1,86 +1,79 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import gregtech.api.block.BuiltInRenderBlock; -import gregtech.api.cover.Cover; -import gregtech.api.cover.CoverRayTracer; +import com.gregtechceu.gtceu.api.block.MaterialBlock; +import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.api.cover.CoverBehavior; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeChanneledStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCoverHolder; -import gregtech.api.items.toolitem.ToolClasses; -import gregtech.api.items.toolitem.ToolHelper; -import gregtech.api.unification.material.Material; -import gregtech.api.util.EntityDamageUtil; -import gregtech.api.util.GTUtility; -import gregtech.client.renderer.pipe.AbstractPipeModel; -import gregtech.client.renderer.pipe.cover.CoverRendererPackage; -import gregtech.client.utils.BloomEffectUtil; -import gregtech.client.utils.TooltipHelper; -import gregtech.common.ConfigHolder; -import gregtech.common.blocks.BlockFrame; -import gregtech.common.blocks.MetaBlocks; - -import net.minecraft.block.Block; -import net.minecraft.block.SoundType; -import net.minecraft.block.properties.PropertyBool; -import net.minecraft.block.state.BlockFaceShape; -import net.minecraft.block.state.BlockStateContainer; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.I18n; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLiving; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.Player; -import net.minecraft.item.EnumDyeColor; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.BlockRenderLayer; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.Direction; -import net.minecraft.util.EnumHand; -import net.minecraft.util.NonNullList; -import net.minecraft.util.SoundCategory; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraftforge.common.property.IExtendedBlockState; -import net.minecraftforge.fml.common.FMLCommonHandler; - -import codechicken.lib.raytracer.RayTracer; +import com.gregtechceu.gtceu.api.item.tool.GTToolType; +import com.gregtechceu.gtceu.api.item.tool.ToolHelper; +import com.gregtechceu.gtceu.common.data.GTBlocks; +import com.gregtechceu.gtceu.config.ConfigHolder; +import com.gregtechceu.gtceu.utils.EntityDamageUtil; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.client.renderer.IBlockRendererProvider; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import org.apache.commons.lang3.tuple.Pair; +import lombok.Getter; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.SpawnPlacements; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BooleanProperty; +import net.minecraft.world.level.storage.loot.LootParams; +import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; +import org.apache.commons.lang3.mutable.MutableObject; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.ref.WeakReference; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; +import java.util.*; -public abstract class PipeBlock extends BuiltInRenderBlock { +public abstract class PipeBlock extends Block implements EntityBlock, IBlockRendererProvider { - public static final PropertyBool NORTH = PropertyBool.create("north"); - public static final PropertyBool EAST = PropertyBool.create("east"); - public static final PropertyBool SOUTH = PropertyBool.create("south"); - public static final PropertyBool WEST = PropertyBool.create("west"); - public static final PropertyBool UP = PropertyBool.create("up"); - public static final PropertyBool DOWN = PropertyBool.create("down"); + public static final BooleanProperty NORTH = BooleanProperty.create("north"); + public static final BooleanProperty EAST = BooleanProperty.create("east"); + public static final BooleanProperty SOUTH = BooleanProperty.create("south"); + public static final BooleanProperty WEST = BooleanProperty.create("west"); + public static final BooleanProperty UP = BooleanProperty.create("up"); + public static final BooleanProperty DOWN = BooleanProperty.create("down"); - public static final EnumMap FACINGS = buildFacings(); + public static final EnumMap FACINGS = buildFacings(); - private static @NotNull EnumMap buildFacings() { - EnumMap map = new EnumMap<>(Direction.class); + private static @NotNull EnumMap buildFacings() { + EnumMap map = new EnumMap<>(Direction.class); map.put(Direction.NORTH, NORTH); map.put(Direction.EAST, EAST); map.put(Direction.SOUTH, SOUTH); @@ -90,18 +83,20 @@ public abstract class PipeBlock extends BuiltInRenderBlock { return map; } - public static final PropertyBool FRAMED = PropertyBool.create("framed"); + public static final BooleanProperty FRAMED = BooleanProperty.create("framed"); // do not touch these two unless you know what you are doing protected final ThreadLocal lastTilePos = ThreadLocal.withInitial(() -> new BlockPos(0, 0, 0)); protected final ThreadLocal> lastTile = ThreadLocal .withInitial(() -> new WeakReference<>(null)); + @Getter private final IPipeStructure structure; - public PipeBlock(IPipeStructure structure) { - super(net.minecraft.block.material.Material.IRON); + public PipeBlock(BlockBehaviour.Properties properties, IPipeStructure structure) { + super(properties); this.structure = structure; + /* setTranslationKey(structure.getName()); setSoundType(SoundType.METAL); setHardness(2.0f); @@ -109,24 +104,21 @@ public PipeBlock(IPipeStructure structure) { setResistance(3.0f); setLightOpacity(1); disableStats(); - } - - public IPipeStructure getStructure() { - return structure; + */ } // net logic // public void doPlacementLogic(PipeBlockEntity tile, Direction placedBlockSearchSide) { for (Direction facing : GTUtil.DIRECTIONS) { - TileEntity neighbor = tile.getNeighbor(facing); + BlockEntity neighbor = tile.getNeighbor(facing); if (neighbor instanceof PipeBlockEntity other) { // first check -- does the other tile have a cover that would prevent connection - Cover cover = other.getCoverHolder().getCoverAtSide(facing.getOpposite()); + CoverBehavior cover = other.getCoverHolder().getCoverAtSide(facing.getOpposite()); if (cover != null && !cover.canPipePassThrough()) continue; // second check -- connect to matching mark pipes if side matches or config allows. if (tile.getPaintingColor() == other.getPaintingColor() && (facing == placedBlockSearchSide || - !ConfigHolder.machines.gt6StylePipesCables)) { + !ConfigHolder.INSTANCE.machines.gt6StylePipesCables)) { if (coverCheck(tile, other, facing)) connectTile(tile, other, facing); continue; } @@ -142,113 +134,106 @@ public void doPlacementLogic(PipeBlockEntity tile, Direction placedBlockSearchSi } @Override - public boolean onBlockActivated(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull IBlockState state, - @NotNull Player playerIn, @NotNull EnumHand hand, @NotNull Direction facing, - float hitX, float hitY, float hitZ) { - ItemStack item = playerIn.getHeldItem(hand); - PipeBlockEntity tile = getTileEntity(worldIn, pos); + public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + ItemStack item = player.getItemInHand(hand); + PipeBlockEntity tile = getBlockEntity(level, pos); if (tile != null) { if (tile.getFrameMaterial() == null) { - BlockFrame frame = BlockFrame.getFrameBlockFromItem(item); + MaterialBlock frame = (MaterialBlock) ((BlockItem) item.getItem()).getBlock(); if (frame != null) { - tile.setFrameMaterial(frame.getGtMaterial(item)); - SoundType type = frame.getSoundType(item); - worldIn.playSound(playerIn, pos, type.getPlaceSound(), SoundCategory.BLOCKS, + tile.setFrameMaterial(frame.material); + SoundType type = frame.getSoundType(frame.defaultBlockState()); + level.playSound(player, pos, type.getPlaceSound(), SoundSource.BLOCKS, (type.getVolume() + 1.0F) / 2.0F, type.getPitch() * 0.8F); - if (!playerIn.capabilities.isCreativeMode) { + if (!player.isCreative()) { item.shrink(1); } - return true; + return InteractionResult.SUCCESS; } } - RayTraceAABB trace = collisionRayTrace(playerIn, worldIn, pos); - if (trace == null) - return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ); - - Direction actualSide = CoverRayTracer.determineGridSideHit(trace); + Direction facing = hit.getDirection(); + Direction actualSide = ICoverable.determineGridSideHit(hit); if (actualSide != null) facing = actualSide; - + // cover comes first - PipeCoverHolder coverable = tile.getCoverHolder(); - Cover cover = coverable.getCoverAtSide(facing); + ICoverable coverable = tile.getCoverHolder(); + CoverBehavior cover = coverable.getCoverAtSide(facing); if (cover != null) { - if (ToolHelper.isTool(item, ToolClasses.SCREWDRIVER)) { - EnumActionResult result = cover.onScrewdriverClick(playerIn, hand, trace); - if (result != EnumActionResult.PASS) { - if (result == EnumActionResult.SUCCESS) { - ToolHelper.damageItem(item, playerIn); - ToolHelper.playToolSound(item, playerIn); - return true; + if (ToolHelper.isTool(item, GTToolType.SCREWDRIVER)) { + InteractionResult result = cover.onScrewdriverClick(player, hand, hit); + if (result != InteractionResult.PASS) { + if (result == InteractionResult.SUCCESS) { + ToolHelper.damageItem(item, player); + ToolHelper.playToolSound(GTToolType.SCREWDRIVER, (ServerPlayer) player); + return InteractionResult.SUCCESS; } - return false; + return InteractionResult.PASS; } } - if (ToolHelper.isTool(item, ToolClasses.SOFT_MALLET)) { - EnumActionResult result = cover.onSoftMalletClick(playerIn, hand, trace); - if (result != EnumActionResult.PASS) { - if (result == EnumActionResult.SUCCESS) { - ToolHelper.damageItem(item, playerIn); - ToolHelper.playToolSound(item, playerIn); - return true; + if (ToolHelper.isTool(item, GTToolType.SOFT_MALLET)) { + InteractionResult result = cover.onSoftMalletClick(player, hand, hit); + if (result != InteractionResult.PASS) { + if (result == InteractionResult.SUCCESS) { + ToolHelper.damageItem(item, player); + ToolHelper.playToolSound(GTToolType.SOFT_MALLET, (ServerPlayer) player); + return InteractionResult.SUCCESS; } - return false; + return InteractionResult.PASS; } } - EnumActionResult result = cover.onRightClick(playerIn, hand, trace); - if (result == EnumActionResult.SUCCESS) return true; + //InteractionResult result = cover.onRightClick(player, hand, trace); + //if (result == EnumActionResult.SUCCESS) return true; // allow crowbar to run even if the right click returns a failure - if (ToolHelper.isTool(item, ToolClasses.CROWBAR)) { - coverable.removeCover(facing); - ToolHelper.damageItem(item, playerIn); - ToolHelper.playToolSound(item, playerIn); - return true; + if (ToolHelper.isTool(item, GTToolType.CROWBAR)) { + coverable.removeCover(facing, player); + ToolHelper.damageItem(item, player); + ToolHelper.playToolSound(GTToolType.CROWBAR, (ServerPlayer) player); + return InteractionResult.SUCCESS; } - - if (result == EnumActionResult.FAIL) return false; } // frame removal Material frame = tile.getFrameMaterial(); - if (frame != null && ToolHelper.isTool(item, ToolClasses.CROWBAR)) { + if (frame != null && ToolHelper.isTool(item, GTToolType.CROWBAR)) { tile.setFrameMaterial(null); - spawnAsEntity(worldIn, pos, MetaBlocks.FRAMES.get(frame).getItem(frame)); - ToolHelper.damageItem(item, playerIn); - ToolHelper.playToolSound(item, playerIn); - return true; + popResource(level, pos, GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, frame).asStack()); + ToolHelper.damageItem(item, player); + ToolHelper.playToolSound(GTToolType.CROWBAR, (ServerPlayer) player); + return InteractionResult.SUCCESS; } // pipe modification if (isPipeTool(item)) { PipeBlockEntity other = tile.getPipeNeighbor(facing, true); - if (playerIn.isSneaking() && allowsBlocking()) { - ToolHelper.damageItem(item, playerIn); - ToolHelper.playToolSound(item, playerIn); + if (player.isShiftKeyDown() && allowsBlocking()) { + ToolHelper.damageItem(item, player); + ToolHelper.playToolSound(GTToolType.WRENCH, (ServerPlayer) player); if (tile.isBlocked(facing)) unblockTile(tile, other, facing); else blockTile(tile, other, facing); } else { if (tile.isConnected(facing)) { - ToolHelper.damageItem(item, playerIn); - ToolHelper.playToolSound(item, playerIn); + ToolHelper.damageItem(item, player); + ToolHelper.playToolSound(item, player); disconnectTile(tile, other, facing); } else if (coverCheck(tile, other, facing)) { - ToolHelper.damageItem(item, playerIn); - ToolHelper.playToolSound(item, playerIn); + ToolHelper.damageItem(item, player); + ToolHelper.playToolSound(item, player); connectTile(tile, other, facing); } else { // if the covers disallow the connection, simply try to render a connection. connectTile(tile, null, facing); } } - return true; + return InteractionResult.SUCCESS; } } - return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ); + return super.use(state, level, pos, player, hand, hit); } - +/* @Override - public void onBlockClicked(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull Player playerIn) { - PipeBlockEntity tile = getTileEntity(worldIn, pos); + public void onBlockClicked(@NotNull Level worldIn, @NotNull BlockPos pos, @NotNull Player playerIn) { + PipeBlockEntity tile = getBlockEntity(worldIn, pos); if (tile != null) { RayTraceAABB trace = collisionRayTrace(playerIn, worldIn, pos); if (trace == null) { @@ -265,7 +250,7 @@ public void onBlockClicked(@NotNull World worldIn, @NotNull BlockPos pos, @NotNu } super.onBlockClicked(worldIn, pos, playerIn); } - +*/ /** * Should be called to verify if a connection can be formed before * {@link #connectTile(PipeBlockEntity, PipeBlockEntity, Direction)} is called. @@ -274,8 +259,8 @@ public void onBlockClicked(@NotNull World worldIn, @NotNull BlockPos pos, @NotNu */ public static boolean coverCheck(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, Direction facing) { - Cover tileCover = tile.getCoverHolder().getCoverAtSide(facing); - Cover acrossCover = tileAcross != null ? tileAcross.getCoverHolder().getCoverAtSide(facing.getOpposite()) : + CoverBehavior tileCover = tile.getCoverHolder().getCoverAtSide(facing); + CoverBehavior acrossCover = tileAcross != null ? tileAcross.getCoverHolder().getCoverAtSide(facing.getOpposite()) : null; return (tileCover == null || tileCover.canPipePassThrough()) && (acrossCover == null || acrossCover.canPipePassThrough()); @@ -292,7 +277,7 @@ public static void connectTile(@NotNull PipeBlockEntity tile, @Nullable PipeBloc if (tileAcross == null) return; tileAcross.setConnected(facing.getOpposite(), tileAcross.getStructure().getRenderThickness() > tile.getStructure().getRenderThickness()); - if (tile.getWorld().isRemote) return; + if (tile.getLevel().isClientSide) return; boolean blocked1 = tile.isBlocked(facing); boolean blocked2 = tileAcross.isBlocked(facing.getOpposite()); @@ -320,7 +305,7 @@ public static void disconnectTile(@NotNull PipeBlockEntity tile, @Nullable PipeB tile.setDisconnected(facing); if (tileAcross == null) return; tileAcross.setDisconnected(facing.getOpposite()); - if (tile.getWorld().isRemote) return; + if (tile.getLevel().isClientSide) return; Map tile2Nodes = new Object2ObjectOpenHashMap<>(); for (WorldPipeNetNode node : getNodesForTile(tileAcross)) { @@ -337,7 +322,7 @@ public static void disconnectTile(@NotNull PipeBlockEntity tile, @Nullable PipeB public static void blockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, Direction facing) { tile.setBlocked(facing); - if (tileAcross == null || tile.getWorld().isRemote) return; + if (tileAcross == null || tile.getLevel().isClientSide) return; Map tile2Nodes = new Object2ObjectOpenHashMap<>(); for (WorldPipeNetNode node : getNodesForTile(tileAcross)) { @@ -355,7 +340,7 @@ public static void blockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockE public static void unblockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, Direction facing) { tile.setUnblocked(facing); - if (tileAcross == null || tile.getWorld().isRemote) return; + if (tileAcross == null || tile.getLevel().isClientSide) return; Map tile2Nodes = new Object2ObjectOpenHashMap<>(); for (WorldPipeNetNode node : getNodesForTile(tileAcross)) { @@ -375,41 +360,41 @@ protected boolean allowsBlocking() { } public static Collection getNodesForTile(PipeBlockEntity tile) { - assert !tile.getWorld().isRemote; - return tile.getBlockType().getHandler(tile.getWorld(), tile.getPos()) - .getOrCreateFromNets(tile.getWorld(), tile.getPos(), tile.getStructure()); + assert !tile.getLevel().isClientSide; + return tile.getBlockType().getHandler(tile.getLevel(), tile.getBlockPos()) + .getOrCreateFromNets(tile.getLevel(), tile.getBlockPos(), tile.getStructure()); } @Override - public void breakBlock(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull IBlockState state) { - super.breakBlock(worldIn, pos, state); - if (!worldIn.isRemote) { - getHandler(worldIn, pos).removeFromNets(worldIn, pos, getStructure()); + public void destroy(LevelAccessor level, BlockPos pos, BlockState state) { + super.destroy(level, pos, state); + if (!level.isClientSide()) { + getHandler(level, pos).removeFromNets(level, pos, getStructure()); } } @NotNull - protected abstract IPipeNetNodeHandler getHandler(IBlockAccess world, BlockPos pos); + protected abstract IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos); @NotNull protected abstract IPipeNetNodeHandler getHandler(@NotNull ItemStack stack); // misc stuff // + @Override - public void addInformation(@NotNull ItemStack stack, World worldIn, @NotNull List tooltip, - @NotNull ITooltipFlag flagIn) { + public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag) { if (getStructure() instanceof IPipeChanneledStructure channeledStructure) { if (channeledStructure.getChannelCount() > 1) - tooltip.add(I18n.format("gregtech.pipe.channels", channeledStructure.getChannelCount())); + tooltip.add(Component.translatable("gtceu.pipe.channels", channeledStructure.getChannelCount())); } - getHandler(stack).addInformation(stack, worldIn, tooltip, flagIn, getStructure()); - if (TooltipHelper.isShiftDown()) { - tooltip.add(I18n.format(getConnectLangKey())); - tooltip.add(I18n.format("gregtech.tool_action.screwdriver.access_covers")); - tooltip.add(I18n.format("gregtech.tool_action.crowbar")); + getHandler(stack).addInformation(stack, level, tooltip, flag, getStructure()); + if (GTUtil.isShiftDown()) { + tooltip.add(Component.translatable(getConnectLangKey())); + tooltip.add(Component.translatable("gtceu.tool_action.screwdriver.access_covers")); + tooltip.add(Component.translatable("gtceu.tool_action.crowbar")); } else { - tooltip.add(I18n.format("gregtech.tool_action.show_tooltips")); + tooltip.add(Component.translatable("gtceu.tool_action.show_tooltips")); } } @@ -418,37 +403,40 @@ protected String getConnectLangKey() { } @Override - public void getDrops(@NotNull NonNullList drops, @NotNull IBlockAccess world, @NotNull BlockPos pos, - @NotNull IBlockState state, int fortune) { - PipeBlockEntity tile = getTileEntity(world, pos); - if (tile != null) tile.getDrops(drops, state); + public List getDrops(BlockState state, LootParams.Builder builder) { + var context = builder.withParameter(LootContextParams.BLOCK_STATE, state).create(LootContextParamSets.BLOCK); + BlockEntity tileEntity = context.getParamOrNull(LootContextParams.BLOCK_ENTITY); + List drops = new ArrayList<>(super.getDrops(state, builder)); + if (tileEntity instanceof PipeBlockEntity pipeTile) { + pipeTile.getDrops(drops, state); + } + return drops; } @Override - public boolean canCreatureSpawn(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos, - @NotNull EntityLiving.SpawnPlacementType type) { + public boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacements.Type type, EntityType entityType) { return false; } @Override - public void onEntityCollision(@NotNull World worldIn, @NotNull BlockPos pos, @NotNull IBlockState state, - @NotNull Entity entityIn) { - if (worldIn.isRemote || !(entityIn instanceof EntityLivingBase living)) return; - PipeBlockEntity tile = getTileEntity(worldIn, pos); + public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { + if (level.isClientSide || !(entity instanceof LivingEntity living)) return; + PipeBlockEntity tile = getBlockEntity(level, pos); if (tile != null && tile.getFrameMaterial() == null && tile.getOffsetTimer() % 10 == 0) { TemperatureLogic logic = tile.getTemperatureLogic(); if (logic != null) { - long tick = FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter(); + long tick = Platform.getMinecraftServer().getTickCount(); EntityDamageUtil.applyTemperatureDamage(living, logic.getTemperature(tick), 1f, 5); } } } + /* TODO fix @Override - public boolean recolorBlock(@NotNull World world, @NotNull BlockPos pos, @NotNull Direction side, + public boolean recolorBlock(@NotNull Level world, @NotNull BlockPos pos, @NotNull Direction side, @NotNull EnumDyeColor color) { if (getStructure().isPaintable()) { - PipeBlockEntity tile = getTileEntity(world, pos); + PipeBlockEntity tile = getBlockEntity(world, pos); if (tile != null && tile.getPaintingColor() != color.colorValue) { tile.setPaintingColor(color.colorValue, false); return true; @@ -456,266 +444,148 @@ public boolean recolorBlock(@NotNull World world, @NotNull BlockPos pos, @NotNul } return false; } - - @Override - public boolean canRenderInLayer(@NotNull IBlockState state, @NotNull BlockRenderLayer layer) { - // guaranteed cutout & bloom for covers - return layer == BlockRenderLayer.CUTOUT_MIPPED || layer == BloomEffectUtil.getEffectiveBloomLayer() || - getStructure().getModel().canRenderInLayer(layer); - } - - @Override - protected Pair getParticleTexture(World world, BlockPos blockPos) { - PipeBlockEntity tile = getTileEntity(world, blockPos); - if (tile != null) { - return getStructure().getModel().getParticleTexture(tile.getPaintingColor(), null); - } - return null; - } + */ // collision boxes // - @SuppressWarnings("deprecation") - @Override - public @NotNull AxisAlignedBB getSelectedBoundingBox(@NotNull IBlockState state, @NotNull World worldIn, - @NotNull BlockPos pos) { - RayTraceAABB trace = this.collisionRayTrace(GTUtility.getSP(), worldIn, pos); - return (trace == null || trace.getBB() == null ? FULL_BLOCK_AABB : trace.getBB()).offset(pos); - } - @SuppressWarnings("deprecation") @Override - public void addCollisionBoxToList(@NotNull IBlockState state, @NotNull World worldIn, @NotNull BlockPos pos, - @NotNull AxisAlignedBB entityBox, @NotNull List collidingBoxes, - @Nullable Entity entityIn, boolean isActualState) { - PipeBlockEntity tile = getTileEntity(worldIn, pos); + public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { + MutableObject shape = new MutableObject<>(Shapes.empty()); + PipeBlockEntity tile = getBlockEntity(level, pos); if (tile != null) { - tile.getCoverBoxes(bb -> addCollisionBoxToList(pos, entityBox, collidingBoxes, bb)); + tile.getCoverBoxes(bb -> shape.setValue(Shapes.or(shape.getValue(), bb))); if (tile.getFrameMaterial() != null) { - addCollisionBoxToList(pos, entityBox, collidingBoxes, BlockFrame.COLLISION_BOX); - } - for (AxisAlignedBB axisAlignedBB : getStructure().getPipeBoxes(tile)) { - addCollisionBoxToList(pos, entityBox, collidingBoxes, axisAlignedBB); + shape.setValue(Shapes.or(shape.getValue(), Shapes.block())); } + shape.setValue(Shapes.or(shape.getValue(), getStructure().getPipeBoxes(tile))); } else { - addCollisionBoxToList(pos, entityBox, collidingBoxes, FULL_BLOCK_AABB); + shape.setValue(Shapes.block()); } + return shape.getValue(); } - @SuppressWarnings("deprecation") - @Nullable - @Override - public RayTraceResult collisionRayTrace(@NotNull IBlockState blockState, @NotNull World worldIn, - @NotNull BlockPos pos, - @NotNull Vec3d start, @NotNull Vec3d end) { - return collisionRayTrace(worldIn.isRemote ? GTUtility.getSP() : null, worldIn, pos, start, end); - } - - public @Nullable RayTraceAABB collisionRayTrace(@NotNull Player player, - @NotNull World world, @NotNull BlockPos pos) { - return collisionRayTrace(player, world, pos, RayTracer.getStartVec(player), RayTracer.getEndVec(player)); - } - - public @Nullable RayTraceAABB collisionRayTrace(@Nullable Player player, - @NotNull World worldIn, @NotNull BlockPos pos, - @NotNull Vec3d start, @NotNull Vec3d end) { - if (hasPipeCollisionChangingItem(worldIn, pos, player)) { - return RayTraceAABB.of(rayTrace(pos, start, end, FULL_BLOCK_AABB), FULL_BLOCK_AABB); - } - PipeBlockEntity tile = getTileEntity(worldIn, pos); - if (tile == null) { - return RayTraceAABB.of(rayTrace(pos, start, end, FULL_BLOCK_AABB), FULL_BLOCK_AABB); - } - RayTraceResult min = null; - AxisAlignedBB minbb = null; - double minDistSqrd = Double.MAX_VALUE; - List bbs = getStructure().getPipeBoxes(tile); - tile.getCoverBoxes(bbs::add); - if (tile.getFrameMaterial() != null) { - bbs.add(FULL_BLOCK_AABB); - } - for (AxisAlignedBB aabb : bbs) { - RayTraceResult result = rayTrace(pos, start, end, aabb); - if (result == null) continue; - double distSqrd = start.squareDistanceTo(result.hitVec); - if (distSqrd < minDistSqrd) { - min = result; - minbb = aabb; - minDistSqrd = distSqrd; - } - } - return RayTraceAABB.of(min, minbb); - } - - public boolean hasPipeCollisionChangingItem(IBlockAccess world, BlockPos pos, Entity entity) { + public boolean hasPipeCollisionChangingItem(BlockGetter world, BlockPos pos, Entity entity) { if (entity instanceof Player player) { - return hasPipeCollisionChangingItem(world, pos, player.getHeldItemMainhand()) || - hasPipeCollisionChangingItem(world, pos, player.getHeldItemOffhand()) || - entity.isSneaking() && isHoldingPipe(player); + return hasPipeCollisionChangingItem(world, pos, player.getMainHandItem()) || + hasPipeCollisionChangingItem(world, pos, player.getOffhandItem()) || + entity.isShiftKeyDown() && isHoldingPipe(player); } return false; } public boolean isHoldingPipe(Player player) { - return isPipeItem(player.getHeldItemMainhand()) || isPipeItem(player.getHeldItemOffhand()); + return isPipeItem(player.getMainHandItem()) || isPipeItem(player.getOffhandItem()); } public boolean isPipeItem(ItemStack stack) { - return stack.getItem() instanceof ItemPipeBlock block && this.getClass().isInstance(block.getBlock()); + return stack.getItem() instanceof PipeBlockItem block && this.getClass().isInstance(block.getBlock()); } @Nullable public static PipeBlock getBlockFromItem(@NotNull ItemStack stack) { - if (stack.getItem() instanceof ItemPipeBlock block) return block.getBlock(); + if (stack.getItem() instanceof PipeBlockItem block) return block.getBlock(); else return null; } - public boolean hasPipeCollisionChangingItem(IBlockAccess world, BlockPos pos, ItemStack stack) { + public boolean hasPipeCollisionChangingItem(BlockGetter world, BlockPos pos, ItemStack stack) { if (isPipeTool(stack)) return true; - PipeBlockEntity tile = getTileEntity(world, pos); + PipeBlockEntity tile = getBlockEntity(world, pos); if (tile == null) return false; PipeCoverHolder coverable = tile.getCoverHolder(); final boolean hasAnyCover = coverable.hasAnyCover(); - if (hasAnyCover && ToolHelper.isTool(stack, ToolClasses.SCREWDRIVER)) return true; + if (hasAnyCover && ToolHelper.isTool(stack, GTToolType.SCREWDRIVER)) return true; final boolean acceptsCovers = coverable.acceptsCovers(); - return GTUtility.isCoverBehaviorItem(stack, () -> hasAnyCover, coverDef -> acceptsCovers); + return GTUtil.isCoverBehaviorItem(stack, () -> hasAnyCover, coverDef -> acceptsCovers); } public boolean isPipeTool(@NotNull ItemStack stack) { return ToolHelper.isTool(stack, getToolClass()); } - public String getToolClass() { - return ToolClasses.WRENCH; - } - - @SuppressWarnings("deprecation") - @Override - public @NotNull BlockFaceShape getBlockFaceShape(@NotNull IBlockAccess worldIn, @NotNull IBlockState state, - @NotNull BlockPos pos, @NotNull Direction face) { - PipeBlockEntity tile = getTileEntity(worldIn, pos); - if (tile != null) { - return tile.getCoverHolder().hasCover(face) ? BlockFaceShape.SOLID : - tile.isConnected(face) ? BlockFaceShape.CENTER : BlockFaceShape.UNDEFINED; - } - return super.getBlockFaceShape(worldIn, state, pos, face); + public GTToolType getToolClass() { + return GTToolType.WRENCH; } // blockstate // - @Override - public int getMetaFromState(@NotNull IBlockState state) { - return 0; - } @Override - protected @NotNull BlockStateContainer createBlockState() { - return constructState(new BlockStateContainer.Builder(this)) - .add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED) - .build(); + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + constructState(builder).add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED); } - protected @NotNull BlockStateContainer.Builder constructState(BlockStateContainer.@NotNull Builder builder) { + protected @NotNull StateDefinition.Builder constructState(StateDefinition.Builder builder) { return builder.add(AbstractPipeModel.THICKNESS_PROPERTY).add(AbstractPipeModel.CLOSED_MASK_PROPERTY) .add(AbstractPipeModel.BLOCKED_MASK_PROPERTY).add(AbstractPipeModel.COLOR_PROPERTY) .add(AbstractPipeModel.FRAME_MATERIAL_PROPERTY).add(AbstractPipeModel.FRAME_MASK_PROPERTY) .add(CoverRendererPackage.PROPERTY); } - @SuppressWarnings("deprecation") - @Override - public @NotNull IBlockState getActualState(@NotNull IBlockState state, @NotNull IBlockAccess worldIn, - @NotNull BlockPos pos) { - PipeBlockEntity tile = getTileEntity(worldIn, pos); - if (tile == null) return state; - state = writeConnectionMask(state, tile.getConnectionMask()); - return state.withProperty(FRAMED, tile.getFrameMaterial() != null); - } - - public static IBlockState writeConnectionMask(@NotNull IBlockState state, byte connectionMask) { + public static BlockState writeConnectionMask(@NotNull BlockState state, byte connectionMask) { for (Direction facing : GTUtil.DIRECTIONS) { - state = state.withProperty(FACINGS.get(facing), GTUtility.evalMask(facing, connectionMask)); + state = state.setValue(FACINGS.get(facing), GTUtil.evalMask(facing, connectionMask)); } return state; } - public static byte readConnectionMask(@NotNull IBlockState state) { + public static byte readConnectionMask(@NotNull BlockState state) { byte mask = 0; for (Direction facing : GTUtil.DIRECTIONS) { if (state.getValue(FACINGS.get(facing))) { - mask |= 1 << facing.ordinal(); + mask |= (byte) (1 << facing.ordinal()); } } return mask; } - @Override - public @NotNull IBlockState getExtendedState(@NotNull IBlockState state, @NotNull IBlockAccess world, - @NotNull BlockPos pos) { - PipeBlockEntity tile = getTileEntity(world, pos); - if (tile == null) return state; - else return tile.getRenderInformation((IExtendedBlockState) state.getActualState(world, pos)); - } - // tile entity // @Override - public final boolean hasTileEntity(@NotNull IBlockState state) { + public final boolean hasBlockEntity(@NotNull BlockState state) { return true; } @Nullable - public PipeBlockEntity getTileEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { - if (GTUtility.arePosEqual(lastTilePos.get(), pos)) { + public PipeBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull BlockPos pos) { + if (lastTilePos.get().equals(pos)) { PipeBlockEntity tile = lastTile.get().get(); - if (tile != null && !tile.isInvalid()) return tile; + if (tile != null && !tile.isRemoved()) return tile; } - TileEntity tile = world.getTileEntity(pos); + BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof PipeBlockEntity pipe) { - lastTilePos.set(pos.toImmutable()); + lastTilePos.set(pos.immutable()); lastTile.set(new WeakReference<>(pipe)); return pipe; } else return null; } + @Nullable @Override - public final PipeBlockEntity createTileEntity(@NotNull World world, @NotNull IBlockState state) { - try { - // noinspection deprecation - return getTileClass(world, state).newInstance(); - } catch (Throwable ignored) { - return null; - } - } - - /** - * This may seem unnecessary, but it enforces empty constructors which are required due to - * {@link TileEntity#create(World, CompoundTag)} - */ - public Class getTileClass(@NotNull World world, @NotNull IBlockState state) { - return PipeBlockEntity.class; + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new PipeBlockEntity(/*TODO block entity type*/, pos, state); } @Override - public void onNeighborChange(@NotNull IBlockAccess world, @NotNull BlockPos pos, @NotNull BlockPos neighbor) { - super.onNeighborChange(world, pos, neighbor); - Direction facing = GTUtility.getFacingToNeighbor(pos, neighbor); + public void onNeighborChange(BlockState state, LevelReader level, BlockPos pos, BlockPos neighbor) { + super.onNeighborChange(state, level, pos, neighbor); + Direction facing = GTUtil.getFacingToNeighbor(pos, neighbor); if (facing == null) return; - PipeBlockEntity tile = getTileEntity(world, pos); + PipeBlockEntity tile = getBlockEntity(level, pos); if (tile != null) tile.onNeighborChanged(facing); } @Override - public int getLightValue(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos) { - PipeBlockEntity tile = getTileEntity(world, pos); + public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) { + PipeBlockEntity tile = getBlockEntity(level, pos); if (tile != null) { TemperatureLogic temperatureLogic = tile.getTemperatureLogic(); int temp = temperatureLogic == null ? 0 : temperatureLogic - .getTemperature(FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter()); + .getTemperature(Platform.getMinecraftServer().getTickCount()); // max light at 5000 K // min light at 500 K if (temp >= 5000) { @@ -730,38 +600,36 @@ public int getLightValue(@NotNull IBlockState state, @NotNull IBlockAccess world // cover compatibility // - @SuppressWarnings("deprecation") + @Override - public void neighborChanged(@NotNull IBlockState state, @NotNull World worldIn, @NotNull BlockPos pos, - @NotNull Block blockIn, @NotNull BlockPos fromPos) { - PipeBlockEntity tile = getTileEntity(worldIn, pos); + public void neighborChanged(BlockState state, Level level, BlockPos pos, + Block neighborBlock, BlockPos neighborPos, boolean movedByPiston) { + PipeBlockEntity tile = getBlockEntity(level, pos); if (tile != null) { - Direction facing = GTUtility.getFacingToNeighbor(pos, fromPos); + Direction facing = GTUtil.getFacingToNeighbor(pos, neighborPos); if (facing != null) tile.onNeighborChanged(facing); - tile.getCoverHolder().updateInputRedstoneSignals(); + // TODO redstone + // tile.getCoverHolder().notifyBlockUpdate(); } } @Override - public boolean shouldCheckWeakPower(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos, - @NotNull Direction side) { + public boolean shouldCheckWeakPower(BlockState state, SignalGetter level, BlockPos pos, Direction side) { // The check in World::getRedstonePower in the vanilla code base is reversed. Setting this to false will // actually cause getWeakPower to be called, rather than prevent it. - return false; + return true; } - @SuppressWarnings("deprecation") @Override - public int getWeakPower(@NotNull IBlockState blockState, @NotNull IBlockAccess blockAccess, @NotNull BlockPos pos, - @NotNull Direction side) { - PipeBlockEntity tile = getTileEntity(blockAccess, pos); - return tile != null ? tile.getCoverHolder().getOutputRedstoneSignal(side) : 0; + public int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { + PipeBlockEntity tile = getBlockEntity(level, pos); + return tile != null ? tile.getCoverHolder().getOutputRedstoneSignal(direction) : 0; } @Override - public boolean canConnectRedstone(@NotNull IBlockState state, @NotNull IBlockAccess world, @NotNull BlockPos pos, - Direction side) { - PipeBlockEntity tile = getTileEntity(world, pos); - return tile != null && tile.getCoverHolder().canConnectRedstone(side); + public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, + @Nullable Direction direction) { + PipeBlockEntity tile = getBlockEntity(level, pos); + return tile != null && tile.getCoverHolder().canConnectRedstone(direction); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java new file mode 100644 index 0000000000..aab49900ca --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java @@ -0,0 +1,47 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.item.component.IInteractionItem; +import com.gregtechceu.gtceu.common.data.GTItems; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.NotNull; + +public class PipeBlockItem extends BlockItem { + + public PipeBlockItem(PipeBlock block, Item.Properties properties) { + super(block, properties); + } + + @Override + public @NotNull PipeBlock getBlock() { + return (PipeBlock) super.getBlock(); + } + + @Override + protected boolean placeBlock(BlockPlaceContext context, BlockState state) { + if (super.placeBlock(context, state)) { + ItemStack offhand = context.getPlayer().getOffhandItem(); + for (int i = 0; i < DyeColor.values().length; i++) { + if (offhand.is(GTItems.SPRAY_CAN_DYES[i].get())) { + ((IInteractionItem) GTItems.SPRAY_CAN_DYES[i].get().getComponents().get(0)).use( + GTItems.SPRAY_CAN_DYES[i].get(), context.getLevel(), + context.getPlayer(), InteractionHand.OFF_HAND); + break; + } + } + + PipeBlockEntity tile = getBlock().getBlockEntity(context.getLevel(), context.getClickedPos()); + if (tile != null) { + tile.placedBy(context.getItemInHand(), context.getPlayer()); + getBlock().doPlacementLogic(tile, context.getClickedFace().getOpposite()); + } + return true; + } else return false; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index 7ce659c34c..3793023a87 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -1,32 +1,24 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeMaterialTileEntity; -import gregtech.api.unification.material.Material; -import gregtech.api.unification.material.Materials; -import gregtech.api.unification.material.properties.PipeNetProperties; -import gregtech.api.unification.material.properties.PropertyKey; -import gregtech.api.unification.material.registry.MaterialRegistry; -import gregtech.api.util.GTUtility; -import gregtech.client.renderer.pipe.AbstractPipeModel; -import gregtech.common.ConfigHolder; - -import net.minecraft.block.state.BlockStateContainer; -import net.minecraft.block.state.IBlockState; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeMaterialBlockEntity; +import com.gregtechceu.gtceu.common.data.GTMaterials; +import com.gregtechceu.gtceu.config.ConfigHolder; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.Player; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.NonNullList; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -36,30 +28,11 @@ public abstract class PipeMaterialBlock extends PipeBlock { - public final MaterialRegistry registry; - - public PipeMaterialBlock(IPipeMaterialStructure structure, MaterialRegistry registry) { - super(structure); - this.registry = registry; - } + public final Material material; - @Override - public void getSubBlocks(@NotNull CreativeTabs itemIn, @NotNull NonNullList items) { - for (Material material : registry) { - if (!getStructure().getOrePrefix().doGenerateItem(material)) continue; - PipeNetProperties properties = material.getProperty(PropertyKey.PIPENET_PROPERTIES); - if (properties != null && properties.generatesStructure(getStructure())) { - items.add(getItem(material)); - } - } - } - - @Override - public @NotNull ItemStack getPickBlock(@NotNull IBlockState state, @NotNull RayTraceResult target, - @NotNull World world, @NotNull BlockPos pos, @NotNull Player player) { - PipeMaterialTileEntity tile = getTileEntity(world, pos); - if (tile != null) return getItem(tile.getMaterial()); - else return super.getPickBlock(state, target, world, pos, player); + public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStructure structure, Material material) { + super(properties, structure); + this.material = material; } @Override @@ -67,74 +40,49 @@ public IPipeMaterialStructure getStructure() { return (IPipeMaterialStructure) super.getStructure(); } - @NotNull - public ItemStack getItem(@NotNull Material material) { - return new ItemStack(this, 1, registry.getIDForObject(material)); - } - - @Nullable - public Material getMaterialForStack(@NotNull ItemStack stack) { - return registry.getObjectById(stack.getMetadata()); - } - @Override - protected @NotNull IPipeNetNodeHandler getHandler(IBlockAccess world, BlockPos pos) { - PipeMaterialTileEntity tile = getTileEntity(world, pos); + protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + PipeMaterialBlockEntity tile = getBlockEntity(world, pos); if (tile != null) return tile.getMaterial().getProperty(PropertyKey.PIPENET_PROPERTIES); - else return Materials.Aluminium.getProperty(PropertyKey.PIPENET_PROPERTIES); + else return GTMaterials.Aluminium.getProperty(PropertyKey.PIPENET_PROPERTIES); } @Override protected @NotNull IPipeNetNodeHandler getHandler(@NotNull ItemStack stack) { - Material material = getMaterialForStack(stack); - if (material == null) material = Materials.Aluminium; + Material material = this.material; + if (material == null) material = GTMaterials.Aluminium; return material.getProperty(PropertyKey.PIPENET_PROPERTIES); } @Override - public void addInformation(@NotNull ItemStack stack, World worldIn, @NotNull List tooltip, - @NotNull ITooltipFlag flagIn) { - super.addInformation(stack, worldIn, tooltip, flagIn); - if (ConfigHolder.misc.debug) { - Material material = getMaterialForStack(stack); + public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag) { + super.appendHoverText(stack, level, tooltip, flag); + if (ConfigHolder.INSTANCE.dev.debug) { if (material != null) - tooltip.add("MetaItem Id: " + getStructure().getOrePrefix().name + material.toCamelCaseString()); + tooltip.add(Component.literal("MetaItem Id: " + getStructure().getTagPrefix().name + material.toCamelCaseString())); } } // tile entity // - @NotNull + @Override - protected BlockStateContainer.Builder constructState(BlockStateContainer.@NotNull Builder builder) { - return super.constructState(builder).add(AbstractPipeModel.MATERIAL_PROPERTY); + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + super.createBlockStateDefinition(builder); + builder.add(AbstractPipeModel.MATERIAL_PROPERTY); } @Override - public @Nullable PipeMaterialTileEntity getTileEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { - if (GTUtility.arePosEqual(lastTilePos.get(), pos)) { + public @Nullable PipeMaterialBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull BlockPos pos) { + if (lastTilePos.get().equals(pos)) { PipeBlockEntity tile = lastTile.get().get(); - if (tile != null && !tile.isInvalid()) return (PipeMaterialTileEntity) tile; + if (tile != null && !tile.isRemoved()) return (PipeMaterialBlockEntity) tile; } - TileEntity tile = world.getTileEntity(pos); - if (tile instanceof PipeMaterialTileEntity pipe) { - lastTilePos.set(pos.toImmutable()); + BlockEntity tile = world.getBlockEntity(pos); + if (tile instanceof PipeMaterialBlockEntity pipe) { + lastTilePos.set(pos.immutable()); lastTile.set(new WeakReference<>(pipe)); return pipe; } else return null; } - - @Override - public Class getTileClass(@NotNull World world, @NotNull IBlockState state) { - return PipeMaterialTileEntity.class; - } - - @Override - protected Pair getParticleTexture(World world, BlockPos blockPos) { - PipeMaterialTileEntity tile = getTileEntity(world, blockPos); - if (tile != null) { - return getStructure().getModel().getParticleTexture(tile.getPaintingColor(), tile.getMaterial()); - } - return null; - } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java deleted file mode 100644 index 8c3ca7c674..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/RayTraceAABB.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; - -import net.minecraft.util.Direction; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; - -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.Nullable; - -/** - * A ray trace that additionally contains the {@link AxisAlignedBB} it hit. - */ -public class RayTraceAABB extends RayTraceResult { - - private final AxisAlignedBB bb; - - public RayTraceAABB(Type typeIn, Vec3d hitVecIn, Direction sideHitIn, BlockPos blockPosIn, AxisAlignedBB bb) { - super(typeIn, hitVecIn, sideHitIn, blockPosIn); - this.bb = bb; - } - - @Contract("null, _ -> null; !null, _ -> new") - public static RayTraceAABB of(@Nullable RayTraceResult result, AxisAlignedBB bb) { - if (result == null) return null; - if (result.typeOfHit == Type.ENTITY) - throw new IllegalArgumentException("Cannot create a RayTraceAABB for an entity hit!"); - return new RayTraceAABB(result.typeOfHit, result.hitVec, result.sideHit, result.getBlockPos(), bb); - } - - public AxisAlignedBB getBB() { - return bb; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java index 7804a3555b..f1f85d0359 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java @@ -5,7 +5,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.BlockEntity; import net.minecraft.util.Direction; import net.minecraft.util.EnumParticleTypes; @@ -20,10 +20,10 @@ public interface IWorldPipeNetTile { // universal (mostly for active nodes) @NotNull - EnumMap getTargetsWithCapabilities(WorldPipeNetNode destination); + EnumMap getTargetsWithCapabilities(WorldPipeNetNode destination); @Nullable - TileEntity getTargetWithCapabilities(WorldPipeNetNode destination, Direction facing); + BlockEntity getTargetWithCapabilities(WorldPipeNetNode destination, Direction facing); PipeCapabilityWrapper getWrapperForNode(WorldPipeNetNode node); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 2667511086..ea94562da5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -1,8 +1,10 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; import com.gregtechceu.gtceu.api.blockentity.NeighborCacheBlockEntity; +import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.IToolable; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverBehavior; @@ -19,6 +21,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.api.machine.TickableSubscription; import com.gregtechceu.gtceu.api.pipenet.PipeCoverContainer; @@ -26,10 +29,13 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; +import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; +import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; +import com.mojang.datafixers.util.Pair; import lombok.Getter; import lombok.Setter; import net.minecraft.core.BlockPos; @@ -37,12 +43,17 @@ import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.TickTask; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.block.Blocks; 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.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; @@ -55,9 +66,11 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Set; +import java.util.function.Consumer; public class PipeBlockEntity extends NeighborCacheBlockEntity implements IWorldPipeNetTile, ITickSubscription, IEnhancedManaged, IAsyncAutoSyncBlockEntity, IAutoPersistBlockEntity, IToolGridHighLight, IToolable { @@ -87,13 +100,14 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity implements IWorldP @Setter @DescSynced private @Nullable Material frameMaterial; - - private final Set tickers = new ObjectOpenHashSet<>(); + + private final List serverTicks = new ArrayList<>(); + private final List waitingToAdd = new ArrayList<>(); @Persisted @DescSynced @Getter - protected final PipeCoverContainer covers = new PipeCoverContainer(this); + protected final PipeCoverHolder covers = new PipeCoverHolder(this); private final Object2ObjectOpenHashMap, IPipeCapabilityObject> capabilities = new Object2ObjectOpenHashMap<>(); private final Object2ObjectOpenCustomHashMap netCapabilities = WorldPipeNet .getSensitiveHashMap(); @@ -110,8 +124,7 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity implements IWorldP private long nextSoundTime = 0; public PipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - + super(type, pos, blockState, true); } @Nullable @@ -121,7 +134,7 @@ public PipeBlockEntity getPipeNeighbor(Direction facing, boolean allowChunkloadi else return null; } - public void getDrops(@NotNull NonNullList drops, @NotNull BlockState state) { + public void getDrops(@NotNull List drops, @NotNull BlockState state) { drops.add(getMainDrop(state)); if (getFrameMaterial() != null) drops.add(GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, getFrameMaterial()).asStack()); @@ -145,7 +158,7 @@ public ItemStack getMainDrop(@NotNull BlockState state) { } public ItemStack getDrop() { - return new ItemStack(getBlockType(), 1, getBlockType().damageDropped(getBlockState())); + return new ItemStack(getBlockType(), 1); } public long getOffsetTimer() { @@ -251,10 +264,6 @@ public void onLoad() { initialize(); } - public void removeTicker(TickableSubscription ticker) { - this.tickers.remove(ticker); - } - public boolean isTicking() { return !tickers.isEmpty(); } @@ -289,7 +298,7 @@ public void onNeighborChanged(@NotNull Direction facing) { } @Override - public @Nullable TileEntity getTargetWithCapabilities(WorldPipeNetNode node, Direction facing) { + public @Nullable BlockEntity getTargetWithCapabilities(WorldPipeNetNode node, Direction facing) { PipeCapabilityWrapper wrapper = netCapabilities.get(node); if (wrapper == null || !wrapper.isActive(facing)) return null; else return getNeighbor(facing); @@ -300,6 +309,16 @@ public PipeCapabilityWrapper getWrapperForNode(WorldPipeNetNode node) { return netCapabilities.get(node); } + @Override + public @NotNull PipeCoverHolder getCoverHolder() { + return covers; + } + + @Override + public void dealAreaDamage(int size, Consumer damageFunction) { + + } + /** * Updates the pipe's active status based on the tile entity connected to the side. * @@ -355,17 +374,12 @@ private void addCapabilities(IPipeCapabilityObject[] capabilities) { } } - public T getCapabilityCoverQuery(@NotNull Capability capability, @Nullable Direction facing) { + public LazyOptional getCapabilityCoverQuery(@NotNull Capability capability, @Nullable Direction facing) { // covers have access to the capability objects no matter the connection status IPipeCapabilityObject object = capabilities.get(capability); return object == null ? null : object.getCapabilityForSide(capability, facing); } - @Override - public boolean hasCapability(@NotNull Capability capability, Direction facing) { - return getCapability(capability, facing) != null; - } - @Override public LazyOptional getCapability(@NotNull Capability capability, @Nullable Direction facing) { if (capability == GTCapability.CAPABILITY_COVERABLE) { @@ -400,13 +414,12 @@ public NetLogicData getNetLogicData(int networkID) { return netLogicDatas.get(networkID); } - @Override public @NotNull PipeBlock getBlockType() { - return (PipeBlock) super.getBlockType(); + return (PipeBlock) this.getBlockState().getBlock(); } @Override - public void setWorld(@NotNull World worldIn) { + public void setWorld(@NotNull Level worldIn) { if (worldIn == this.getWorld()) return; super.setWorld(worldIn); } @@ -584,7 +597,7 @@ public void spawnParticles(Direction direction, EnumParticleTypes particleType, // misc overrides // @Override - public World world() { + public Level world() { return getWorld(); } @@ -616,10 +629,10 @@ public void markAsDirty() { } public static @Nullable PipeBlockEntity getTileNoLoading(BlockPos pos, int dimension) { - World world = DimensionManager.getWorld(dimension); + Level world = DimensionManager.getWorld(dimension); if (world == null || !world.isBlockLoaded(pos)) return null; - TileEntity tile = world.getTileEntity(pos); + BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof PipeBlockEntity pipe) return pipe; else return null; } @@ -636,8 +649,8 @@ public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { for (Direction facing : GTUtil.DIRECTIONS) { Cover cover = getCoverHolder().getCoverAtSide(facing); if (cover != null) { - frameMask |= 1 << facing.ordinal(); - if (cover.forcePipeRenderConnection()) connectionMask |= 1 << facing.ordinal(); + frameMask |= (byte) (1 << facing.ordinal()); + if (cover.forcePipeRenderConnection()) connectionMask |= (byte) (1 << facing.ordinal()); } } frameMask = (byte) ~frameMask; @@ -650,7 +663,7 @@ public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { .withProperty(CoverRendererPackage.PROPERTY, getCoverHolder().createPackage()); } - public void getCoverBoxes(Consumer consumer) { + public void getCoverBoxes(Consumer consumer) { for (Direction facing : GTUtil.DIRECTIONS) { if (getCoverHolder().hasCover(facing)) { consumer.accept(CoverRendererBuilder.PLATE_AABBS.get(facing)); @@ -686,11 +699,62 @@ public void setNeighborsToFire() { for (Direction side : GTUtil.DIRECTIONS) { if (!GTValues.RNG.nextBoolean()) continue; BlockPos blockPos = getPos().offset(side); - IBlockState blockState = getWorld().getBlockState(blockPos); + BlockState blockState = getWorld().getBlockState(blockPos); if (blockState.getBlock().isAir(blockState, getWorld(), blockPos) || blockState.getBlock().isFlammable(getWorld(), blockPos, side.getOpposite())) { getWorld().setBlockState(blockPos, Blocks.FIRE.getDefaultState()); } } } + + @Override + public @Nullable TickableSubscription subscribeServerTick(Runnable runnable) { + if (!isRemote()) { + var subscription = new TickableSubscription(runnable); + waitingToAdd.add(subscription); + var blockState = getBlockState(); + if (!blockState.getValue(BlockProperties.SERVER_TICK)) { + if (getLevel() instanceof ServerLevel serverLevel) { + blockState = blockState.setValue(BlockProperties.SERVER_TICK, true); + setBlockState(blockState); + serverLevel.getServer().tell(new TickTask(0, () -> serverLevel.setBlockAndUpdate(getBlockPos(), + getBlockState().setValue(BlockProperties.SERVER_TICK, true)))); + } + } + return subscription; + } + return null; + } + + @Override + public void unsubscribe(@Nullable TickableSubscription current) { + if (current != null) { + current.unsubscribe(); + } + } + + @Override + public Pair<@Nullable GTToolType, InteractionResult> onToolClick(@NotNull Set toolTypes, ItemStack itemStack, UseOnContext context) { + return null; + } + + @Override + public ManagedFieldHolder getFieldHolder() { + return null; + } + + @Override + public IManagedStorage getSyncStorage() { + return null; + } + + @Override + public void onChanged() { + + } + + @Override + public IManagedStorage getRootStorage() { + return null; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java index cea616e282..b82fc9b0d9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -3,10 +3,13 @@ import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; +import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.api.machine.TickableSubscription; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; @@ -18,6 +21,7 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.INBTSerializable; +import net.minecraftforge.common.util.LazyOptional; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -47,7 +51,7 @@ protected final void addCoverSilent(@NotNull Direction side, @NotNull CoverBehav @Override public final void addCover(@NotNull Direction side, @NotNull CoverBehavior cover) { addCoverSilent(side, cover); - if (!getLevel().isRemote) { + if (!getLevel().isClientSide) { // do not sync or handle logic on client side CoverSaveHandler.writeCoverPlacement(this, COVER_ATTACHED_PIPE, side, cover); if (holder.isConnected(side) && !cover.canPipePassThrough()) { @@ -119,6 +123,16 @@ public void scheduleRenderUpdate() { pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1); } + @Override + public void scheduleNeighborShapeUpdate() { + + } + + @Override + public boolean canPlaceCoverOnSide(CoverDefinition definition, Direction side) { + return false; + } + @Override public double getCoverPlateThickness() { float thickness = holder.getBlockType().getStructure().getRenderThickness(); @@ -131,6 +145,31 @@ public double getCoverPlateThickness() { return Math.min(1.0 / 16.0, (1.0 - thickness) / 2); } + @Override + public Direction getFrontFacing() { + return null; + } + + @Override + public boolean shouldRenderBackSide() { + return false; + } + + @Override + public IItemTransfer getItemTransferCap(@Nullable Direction side, boolean useCoverCapability) { + return null; + } + + @Override + public IFluidTransfer getFluidTransferCap(@Nullable Direction side, boolean useCoverCapability) { + return null; + } + + @Override + public void setCoverAtSide(@Nullable CoverBehavior coverBehavior, Direction side) { + + } + @Override public boolean shouldRenderCoverBackSides() { return false; @@ -158,7 +197,7 @@ public boolean canConnectRedstone(@Nullable Direction side) { return canConnectRedstone(Direction.UP) || canConnectRedstone(Direction.DOWN); } - Cover cover = getCoverAtSide(side); + CoverBehavior cover = getCoverAtSide(side); return cover != null && cover.canConnectRedstone(); } @@ -166,14 +205,14 @@ public int getOutputRedstoneSignal(@Nullable Direction side) { if (side == null) { return getHighestOutputRedstoneSignal(); } - Cover cover = getCoverAtSide(side); + CoverBehavior cover = getCoverAtSide(side); return cover == null ? 0 : cover.getRedstoneSignalOutput(); } public int getHighestOutputRedstoneSignal() { int highestSignal = 0; for (Direction side : GTUtil.DIRECTIONS) { - Cover cover = getCoverAtSide(side); + CoverBehavior cover = getCoverAtSide(side); if (cover == null) continue; highestSignal = Math.max(highestSignal, cover.getRedstoneSignalOutput()); } @@ -182,7 +221,7 @@ public int getHighestOutputRedstoneSignal() { @Override public void update() { - if (!getLevel().isRemote) { + if (!getLevel().isClientSide) { updateCovers(); } } @@ -279,12 +318,12 @@ public void markDirty() { } @Override - public boolean isValid() { - return !holder.isInvalid(); + public boolean isInValid() { + return holder.isRemoved(); } @Override - public T getCapability(@NotNull Capability capability, Direction side) { + public LazyOptional getCapability(@NotNull Capability capability, Direction side) { return holder.getCapabilityCoverQuery(capability, side); } @@ -297,4 +336,14 @@ public CoverRendererPackage createPackage() { } return rendererPackage; } + + @Override + public @Nullable TickableSubscription subscribeServerTick(Runnable runnable) { + return holder.subscribeServerTick(runnable); + } + + @Override + public void unsubscribe(@Nullable TickableSubscription current) { + holder.unsubscribe(current); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java index b3e68b921b..1e422ddfed 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java @@ -17,13 +17,13 @@ import net.minecraftforge.client.model.data.ModelData; import org.jetbrains.annotations.NotNull; -public class PipeMaterialTileEntity extends PipeBlockEntity { +public class PipeMaterialBlockEntity extends PipeBlockEntity { @Persisted @DescSynced private Material material; - public PipeMaterialTileEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { + public PipeMaterialBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java index 211397557d..bb4b24f1a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java @@ -5,7 +5,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCapabilityWrapper; import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinData; -import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.BlockEntity; import net.minecraft.util.Direction; import net.minecraftforge.common.capabilities.Capability; @@ -63,11 +63,11 @@ public boolean hasCapabilityAtPointer(@NotNull Capability capability, WorldPi public E getCapabilityAtPointer(@NotNull Capability capability, WorldPipeNetNode node, @Nullable SimulatorKey simulator) { if (pointerFinished(simulator)) return null; - PipeCapabilityWrapper wrapper = node.getTileEntity().getWrapperForNode(node); + PipeCapabilityWrapper wrapper = node.getBlockEntity().getWrapperForNode(node); Direction pointer = getPointerFacing(simulator); if (!wrapper.isActive(pointer) || !wrapper.supports(capability)) return null; - TileEntity target = node.getTileEntity().getTargetWithCapabilities(node, pointer); + BlockEntity target = node.getBlockEntity().getTargetWithCapabilities(node, pointer); return target == null ? null : target.getCapability(capability, pointer.getOpposite()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/pattern/BlockPattern.java b/src/main/java/com/gregtechceu/gtceu/api/pattern/BlockPattern.java index d1cad89ddc..110fad1401 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pattern/BlockPattern.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pattern/BlockPattern.java @@ -136,7 +136,7 @@ public boolean checkPatternAt(MultiblockState worldState, BlockPos centerPos, Di } } boolean canPartShared = true; - if (worldState.getTileEntity() instanceof IMachineBlockEntity machineBlockEntity && + if (worldState.getBlockEntity() instanceof IMachineBlockEntity machineBlockEntity && machineBlockEntity.getMetaMachine() instanceof IMultiPart part) { // add detected parts if (!predicate.isAny()) { if (part.isFormed() && !part.canShared() && diff --git a/src/main/java/com/gregtechceu/gtceu/api/pattern/MultiblockState.java b/src/main/java/com/gregtechceu/gtceu/api/pattern/MultiblockState.java index 4549c44422..5ad9fff81c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pattern/MultiblockState.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pattern/MultiblockState.java @@ -119,7 +119,7 @@ public BlockState getBlockState() { } @Nullable - public BlockEntity getTileEntity() { + public BlockEntity getBlockEntity() { if (!getBlockState().hasBlockEntity()) { return null; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java b/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java index 5dbe792ec3..cc3e8f3f52 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java @@ -258,7 +258,7 @@ public static TraceabilityPredicate frames(Material... frameMaterials) { .filter(Objects::nonNull).filter(RegistryEntry::isPresent).map(RegistryEntry::get) .toArray(Block[]::new)) .or(new TraceabilityPredicate(blockWorldState -> { - BlockEntity tileEntity = blockWorldState.getTileEntity(); + BlockEntity tileEntity = blockWorldState.getBlockEntity(); if (!(tileEntity instanceof IPipeNode pipeNode)) { return false; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/pattern/predicates/SimplePredicate.java b/src/main/java/com/gregtechceu/gtceu/api/pattern/predicates/SimplePredicate.java index 21160288f0..824ef9f3c1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pattern/predicates/SimplePredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pattern/predicates/SimplePredicate.java @@ -131,7 +131,7 @@ private boolean checkInnerConditions(MultiblockState blockWorldState) { } } if (nbtParser != null && !blockWorldState.world.isClientSide) { - BlockEntity te = blockWorldState.getTileEntity(); + BlockEntity te = blockWorldState.getBlockEntity(); if (te != null) { CompoundTag nbt = te.saveWithFullMetadata(); if (Pattern.compile(nbtParser).matcher(nbt.toString()).find()) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/KineticMachineBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/KineticMachineBlock.java index 29d1754022..ea16351f44 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/block/KineticMachineBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/block/KineticMachineBlock.java @@ -61,8 +61,8 @@ public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldS // we can prevent a major re-propagation here BlockEntity tileEntity = level.getBlockEntity(pos); - if (tileEntity instanceof KineticBlockEntity kineticTileEntity) { - kineticTileEntity.preventSpeedUpdate = 0; + if (tileEntity instanceof KineticBlockEntity kineticBlockEntity) { + kineticBlockEntity.preventSpeedUpdate = 0; if (oldState.getBlock() != state.getBlock()) return; @@ -71,7 +71,7 @@ public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldS if (!areStatesKineticallyEquivalent(oldState, state)) return; - kineticTileEntity.preventSpeedUpdate = 2; + kineticBlockEntity.preventSpeedUpdate = 2; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java index 31da1ba8dc..c9a6863903 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java @@ -154,7 +154,7 @@ public void resetTransferred() { * } * } *

- * if it was in a ticking TileEntity + * if it was in a ticking BlockEntity */ private void updateTransferredState() { long currentTime = getLevelTime(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java index f5e3f5dc2b..f44ae6b71b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java @@ -57,7 +57,7 @@ public static void recipeAddition(Consumer originalConsumer) { AirScrubberRecipes.init(consumer); ChemistryRecipes.init(consumer); - MetaTileEntityMachineRecipeLoader.init(consumer); + MetaBlockEntityMachineRecipeLoader.init(consumer); MiscRecipeLoader.init(consumer); VanillaStandardRecipes.init(consumer); WoodMachineRecipes.init(consumer); @@ -72,7 +72,7 @@ public static void recipeAddition(Consumer originalConsumer) { CircuitRecipes.init(consumer); ComponentRecipes.init(consumer); - MetaTileEntityLoader.init(consumer); + MetaBlockEntityLoader.init(consumer); // GCyM GCyMRecipes.init(consumer); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java index 560a41dd59..6708b5673d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java @@ -97,8 +97,8 @@ public class CleanroomMachine extends WorkableElectricMultiblockMachine @Nullable private Collection cleanroomReceivers; - public CleanroomMachine(IMachineBlockEntity metaTileEntityId) { - super(metaTileEntityId); + public CleanroomMachine(IMachineBlockEntity metaBlockEntityId) { + super(metaBlockEntityId); } ////////////////////////////////////// @@ -419,7 +419,7 @@ protected TraceabilityPredicate innerPredicate() { Set receivers = blockWorldState.getMatchContext().getOrCreate("cleanroomReceiver", Sets::newHashSet); // all non-GTMachines are allowed inside by default - BlockEntity blockEntity = blockWorldState.getTileEntity(); + BlockEntity blockEntity = blockWorldState.getBlockEntity(); if (blockEntity instanceof IMachineBlockEntity machineBlockEntity) { var machine = machineBlockEntity.getMetaMachine(); if (isMachineBanned(machine)) { @@ -448,19 +448,19 @@ public boolean addCache() { }; } - protected boolean isMachineBanned(MetaMachine metaTileEntity) { + protected boolean isMachineBanned(MetaMachine metaBlockEntity) { // blacklisted machines: mufflers and all generators, miners/drills, primitives - if (metaTileEntity instanceof ICleanroomProvider) return true; - if (metaTileEntity instanceof IMufflerMachine) return true; - if (metaTileEntity instanceof SimpleGeneratorMachine) return true; + if (metaBlockEntity instanceof ICleanroomProvider) return true; + if (metaBlockEntity instanceof IMufflerMachine) return true; + if (metaBlockEntity instanceof SimpleGeneratorMachine) return true; // todo: enable checks when these are added? - // if (metaTileEntity instanceof FuelMultiblockController) return true; - if (metaTileEntity instanceof LargeMinerMachine) return true; - if (metaTileEntity instanceof FluidDrillMachine) return true; - // if (metaTileEntity instanceof MetaTileEntityCentralMonitor) return true; - if (metaTileEntity instanceof CokeOvenMachine) return true; - if (metaTileEntity instanceof PrimitiveBlastFurnaceMachine) return true; - return metaTileEntity instanceof PrimitivePumpMachine; + // if (metaBlockEntity instanceof FuelMultiblockController) return true; + if (metaBlockEntity instanceof LargeMinerMachine) return true; + if (metaBlockEntity instanceof FluidDrillMachine) return true; + // if (metaBlockEntity instanceof MetaBlockEntityCentralMonitor) return true; + if (metaBlockEntity instanceof CokeOvenMachine) return true; + if (metaBlockEntity instanceof PrimitiveBlastFurnaceMachine) return true; + return metaBlockEntity instanceof PrimitivePumpMachine; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java index 6c35edd895..31614b70d8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java @@ -103,8 +103,8 @@ public boolean dampingWhenWaiting() { private static class ResearchStationRecipeLogic extends RecipeLogic { - public ResearchStationRecipeLogic(ResearchStationMachine metaTileEntity) { - super(metaTileEntity); + public ResearchStationRecipeLogic(ResearchStationMachine metaBlockEntity) { + super(metaBlockEntity); } @NotNull diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/CleaningMaintenanceHatchPartMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/CleaningMaintenanceHatchPartMachine.java index 0258c429e9..e5426dcee5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/CleaningMaintenanceHatchPartMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/CleaningMaintenanceHatchPartMachine.java @@ -31,8 +31,8 @@ public class CleaningMaintenanceHatchPartMachine extends AutoMaintenanceHatchPar // must come after the static block private static final ICleanroomProvider DUMMY_CLEANROOM = DummyCleanroom.createForTypes(CLEANED_TYPES); - public CleaningMaintenanceHatchPartMachine(IMachineBlockEntity metaTileEntityId) { - super(metaTileEntityId); + public CleaningMaintenanceHatchPartMachine(IMachineBlockEntity metaBlockEntityId) { + super(metaBlockEntityId); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/MaintenanceHatchPartMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/MaintenanceHatchPartMachine.java index 7e7e276809..95ec003978 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/MaintenanceHatchPartMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/MaintenanceHatchPartMachine.java @@ -85,8 +85,8 @@ public class MaintenanceHatchPartMachine extends TieredPartMachine @Nullable protected TickableSubscription maintenanceSubs; - public MaintenanceHatchPartMachine(IMachineBlockEntity metaTileEntityId, boolean isConfigurable) { - super(metaTileEntityId, isConfigurable ? 3 : 1); + public MaintenanceHatchPartMachine(IMachineBlockEntity metaBlockEntityId, boolean isConfigurable) { + super(metaBlockEntityId, isConfigurable ? 3 : 1); this.isConfigurable = isConfigurable; this.itemStackHandler = createInventory(); this.itemStackHandler.setFilter(itemStack -> GTItems.DUCT_TAPE.is(itemStack)); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/ObjectHolderMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/ObjectHolderMachine.java index 8b4da319b4..899937b4bb 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/ObjectHolderMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/ObjectHolderMachine.java @@ -122,8 +122,8 @@ public ManagedFieldHolder getFieldHolder() { private class ObjectHolderHandler extends NotifiableItemStackHandler { - public ObjectHolderHandler(MetaMachine metaTileEntity) { - super(metaTileEntity, 2, IO.IN, IO.BOTH, size -> new ItemStackTransfer(size) { + public ObjectHolderHandler(MetaMachine metaBlockEntity) { + super(metaBlockEntity, 2, IO.IN, IO.BOTH, size -> new ItemStackTransfer(size) { @Override public int getSlotLimit(int slot) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java b/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java index e06945ab6c..93608a0a91 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java @@ -8,13 +8,13 @@ public class SteamMinerLogic extends MinerLogic { /** * Creates the logic for steam miners * - * @param metaTileEntity the {@link IRecipeLogicMachine} this logic belongs to + * @param metaBlockEntity the {@link IRecipeLogicMachine} this logic belongs to * @param fortune the fortune amount to apply when mining ores * @param speed the speed in ticks per block mined * @param maximumRadius the maximum radius (square shaped) the miner can mine in */ - public SteamMinerLogic(IRecipeLogicMachine metaTileEntity, int fortune, int speed, int maximumRadius) { - super(metaTileEntity, fortune, speed, maximumRadius); + public SteamMinerLogic(IRecipeLogicMachine metaBlockEntity, int fortune, int speed, int maximumRadius) { + super(metaBlockEntity, fortune, speed, maximumRadius); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemEndpointMachine.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemEndpointMachine.java index 62ea6868ec..4239e180fd 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemEndpointMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemEndpointMachine.java @@ -11,8 +11,8 @@ public class LDItemEndpointMachine extends LongDistanceEndpointMachine { - public LDItemEndpointMachine(IMachineBlockEntity metaTileEntityId) { - super(metaTileEntityId, LDItemPipeType.INSTANCE); + public LDItemEndpointMachine(IMachineBlockEntity metaBlockEntityId) { + super(metaBlockEntityId, LDItemPipeType.INSTANCE); } @SuppressWarnings("UnstableApiUsage") diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/LevelMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/LevelMixin.java index 2d80a249d7..b7b86fb094 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/LevelMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/LevelMixin.java @@ -38,7 +38,7 @@ private ChunkAccess getChunkNow(int pX, int pZ) { } @Inject(method = "getBlockEntity", at = @At(value = "HEAD"), cancellable = true) - private void getTileEntity(BlockPos pos, CallbackInfoReturnable cir) { + private void getBlockEntity(BlockPos pos, CallbackInfoReturnable cir) { if (!this.isClientSide && Thread.currentThread() != this.thread && (MultiblockWorldSavedData.isThreadService() || AsyncThreadData.isThreadService()) && isLoaded(pos)) { ChunkAccess chunk = this.getChunkNow(pos.getX() >> 4, pos.getZ() >> 4); diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/ServerChunkProviderMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/ServerChunkProviderMixin.java index 45bb8c8542..c540d63914 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/ServerChunkProviderMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/ServerChunkProviderMixin.java @@ -59,7 +59,7 @@ private void injectClearCache(CallbackInfo ci) { } @Inject(method = "getChunkNow", at = @At(value = "HEAD"), cancellable = true) - private void getTileEntity(int pChunkX, int pChunkZ, CallbackInfoReturnable cir) { + private void getBlockEntity(int pChunkX, int pChunkZ, CallbackInfoReturnable cir) { if (Thread.currentThread() != this.mainThread && (MultiblockWorldSavedData.isThreadService() || AsyncThreadData.isThreadService())) { long i = ChunkPos.asLong(pChunkX, pChunkZ); diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java index 63d5169664..430b0055ca 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java @@ -760,7 +760,7 @@ public static void init(RegistrateLangProvider provider) { "Caused %s Lag Spike Warnings (anything taking longer than %sms) on the Server."); provider.add("behavior.portable_scanner.debug_machine", "Meta-ID: %s"); provider.add("behavior.portable_scanner.debug_machine_invalid", " invalid!"); - provider.add("behavior.portable_scanner.debug_machine_invalid_null=invalid! MetaTileEntity =", + provider.add("behavior.portable_scanner.debug_machine_invalid_null=invalid! MetaBlockEntity =", " null!"); provider.add("behavior.portable_scanner.debug_machine_valid", " valid"); provider.add("behavior.portable_scanner.divider", "========================="); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java index 4c5c987a97..d488d801ed 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java @@ -10,7 +10,7 @@ import java.util.function.Consumer; import static com.gregtechceu.gtceu.data.recipe.CraftingComponent.*; -import static com.gregtechceu.gtceu.data.recipe.misc.MetaTileEntityLoader.registerMachineRecipe; +import static com.gregtechceu.gtceu.data.recipe.misc.MetaBlockEntityLoader.registerMachineRecipe; /** * @author KilaBash diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java index 93bcbf9ccd..5d8ba9791c 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java @@ -31,7 +31,7 @@ import static com.gregtechceu.gtceu.data.recipe.CraftingComponent.HULL; import static com.gregtechceu.gtceu.data.recipe.CraftingComponent.PUMP; -public class MetaTileEntityLoader { +public class MetaBlockEntityLoader { public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "casing_ulv", GTBlocks.MACHINE_CASING_ULV.asStack(), "PPP", diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java index 01850659c4..5070ebb41a 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java @@ -30,7 +30,7 @@ import static com.gregtechceu.gtceu.common.data.GTRecipeTypes.ASSEMBLER_RECIPES; import static com.gregtechceu.gtceu.common.data.GTRecipeTypes.ASSEMBLY_LINE_RECIPES; -public class MetaTileEntityMachineRecipeLoader { +public class MetaBlockEntityMachineRecipeLoader { public static void init(Consumer provider) { // this needs to exist here now :) diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/RecipeLogicProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/RecipeLogicProvider.java index d93440c7e2..38d5dad0bc 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/RecipeLogicProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/RecipeLogicProvider.java @@ -75,7 +75,7 @@ protected void addTooltip(CompoundTag capData, ITooltip tooltip, Player player, long absEUt = Math.abs(EUt); // Default behavior, if this TE is not a steam machine (or somehow not instanceof - // IGregTechTileEntity...) + // IGregTechBlockEntity...) var tier = GTUtil.getTierByVoltage(absEUt); Component text = Component.literal(FormattingUtil.formatNumbers(absEUt)).withStyle(ChatFormatting.RED) .append(Component.literal(" EU/t").withStyle(ChatFormatting.RESET) diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/RecipeLogicInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/RecipeLogicInfoProvider.java index e8b46ba7cb..0d6bb01b0d 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/RecipeLogicInfoProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/RecipeLogicInfoProvider.java @@ -69,7 +69,7 @@ protected void addProbeInfo(RecipeLogic capability, IProbeInfo probeInfo, Player if (text == null) { // Default behavior, if this TE is not a steam machine (or somehow not instanceof - // IGregTechTileEntity...) + // IGregTechBlockEntity...) text = ChatFormatting.RED.toString() + absEUt + TextStyleClass.INFO + " EU/t" + ChatFormatting.GREEN + " (" + GTValues.VNF[GTUtil.getTierByVoltage(absEUt)] + ChatFormatting.GREEN + ")"; From 2ada98e6fba8c75f96e52e72b3d863762b08b565 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Wed, 21 Aug 2024 19:09:32 +0300 Subject: [PATCH 03/70] holy hell --- .../gtceu/api/blockentity/INeighborCache.java | 1 + .../api/blockentity/ISyncedBlockEntity.java | 94 ++++++ .../blockentity/NeighborCacheBlockEntity.java | 10 +- .../api/blockentity/SyncedBlockEntity.java | 119 ++++++++ .../gtceu/api/capability/ICoverable.java | 32 +- .../gtceu/api/cover/CoverBehavior.java | 36 ++- .../gtceu/api/cover/CoverDefinition.java | 6 +- .../api/data/chemical/material/Material.java | 6 +- .../properties/AlloyBlastProperty.java | 2 +- .../material/properties/BlastProperty.java | 2 +- .../material/properties/DustProperty.java | 2 +- .../properties/FluidPipeProperties.java | 2 +- .../material/properties/FluidProperty.java | 2 +- .../material/properties/GemProperty.java | 2 +- .../material/properties/HazardProperty.java | 2 +- .../properties/IMaterialProperty.java | 2 +- .../material/properties/IngotProperty.java | 2 +- .../properties/ItemPipeProperties.java | 2 +- .../properties/MaterialProperties.java | 16 +- .../material/properties/OreProperty.java | 2 +- .../properties/PipeNetProperties.java | 155 ++++++++++ .../material/properties/PolymerProperty.java | 2 +- .../material/properties/PropertyKey.java | 8 +- .../material/properties/RotorProperty.java | 2 +- .../material/properties/ToolProperty.java | 2 +- .../material/properties/WireProperties.java | 2 +- .../material/properties/WoodProperty.java | 2 +- .../gtceu/api/data/tag/TagPrefix.java | 8 +- .../gtceu/api/graphnet/GraphNetBacker.java | 43 +-- .../gtceu/api/graphnet/MultiNodeHelper.java | 3 +- .../gtceu/api/graphnet/NetNode.java | 22 +- .../gtceu/api/graphnet/alg/NetPathMapper.java | 2 +- .../api/graphnet/alg/SinglePathAlgorithm.java | 2 - .../api/graphnet/edge/NetFlowSharedEdge.java | 5 +- .../logic/AbstractDoubleLogicData.java | 18 +- .../graphnet/logic/AbstractIntLogicData.java | 18 +- .../graphnet/logic/AbstractLongLogicData.java | 18 +- .../api/graphnet/logic/NetLogicData.java | 31 +- .../api/graphnet/logic/NetLogicEntry.java | 1 + .../api/graphnet/logic/NetLogicRegistry.java | 2 +- .../graphnet/pipenet/IPipeNetNodeHandler.java | 2 +- .../api/graphnet/pipenet/NodeLossCache.java | 11 +- .../api/graphnet/pipenet/WorldPipeNet.java | 26 +- .../graphnet/pipenet/WorldPipeNetNode.java | 1 + .../logic/EdgeCoverReferenceLogic.java | 73 ++--- .../pipenet/logic/TemperatureLogic.java | 4 + .../logic/TemperatureLossFunction.java | 1 + .../physical/IPipeCapabilityObject.java | 3 +- .../pipenet/physical/IPipeStructure.java | 4 +- .../physical/PipeStructureRegistry.java | 5 +- .../physical/block/MaterialPipeBlockItem.java | 15 +- .../physical/block/PipeActivableBlock.java | 35 +-- .../pipenet/physical/block/PipeBlock.java | 283 ++++++++--------- .../pipenet/physical/block/PipeBlockItem.java | 2 + .../physical/block/PipeMaterialBlock.java | 23 +- .../physical/tile/IWorldPipeNetTile.java | 13 +- .../tile/PipeActivableBlockEntity.java | 40 ++- .../physical/tile/PipeBlockEntity.java | 286 +++++++++--------- .../physical/tile/PipeCoverHolder.java | 196 ++++-------- ...tity.java => PipeMaterialBlockEntity.java} | 23 +- .../pipenet/predicate/BlockedPredicate.java | 11 +- .../pipenet/predicate/FilterPredicate.java | 16 +- .../pipenet/transfer/TransferControl.java | 7 +- .../traverse/AbstractTileRoundRobinData.java | 17 +- .../predicate/EdgePredicateHandler.java | 6 +- .../predicate/test/FluidTestObject.java | 6 +- .../predicate/test/ItemTestObject.java | 21 +- .../api/graphnet/servernet/ServerNet.java | 22 +- .../api/graphnet/servernet/ServerNetNode.java | 19 +- .../traverse/TraverseDataProvider.java | 5 +- .../graphnet/traverse/TraverseHelpers.java | 4 +- .../gtceu/api/graphnet/worldnet/WorldNet.java | 11 +- .../gtceu/api/network/PacketDataList.java | 111 +++++++ .../client/particle/GTOverheatParticle.java | 254 ++++++++++++++++ .../gtceu/client/particle/GTParticle.java | 119 ++++++++ .../client/particle/GTParticleManager.java | 217 +++++++++++++ .../gtceu/client/renderer/GTRenderTypes.java | 10 + .../client/renderer/GTRendererProvider.java | 5 +- .../gtceu/client/renderer/IRenderSetup.java | 35 +++ .../renderer/pipe/AbstractPipeModel.java | 212 +++++++++++++ .../renderer/pipe/ActivablePipeModel.java | 124 ++++++++ .../client/renderer/pipe/PipeItemModel.java | 146 +++++++++ .../renderer/pipe/cache/ActivableSQC.java | 84 +++++ .../renderer/pipe/cache/ColorQuadCache.java | 42 +++ .../pipe/cache/StructureQuadCache.java | 121 ++++++++ .../renderer/pipe/cache/SubListAddress.java | 12 + .../renderer/pipe/cover/CoverRenderer.java | 21 ++ .../pipe/cover/CoverRendererBuilder.java | 157 ++++++++++ .../pipe/cover/CoverRendererPackage.java | 56 ++++ .../pipe/quad/OverlayLayerDefinition.java | 17 ++ .../renderer/pipe/quad/PipeQuadHelper.java | 151 +++++++++ .../client/renderer/pipe/quad/QuadHelper.java | 211 +++++++++++++ .../pipe/quad/RecolorableBakedQuad.java | 244 +++++++++++++++ .../client/renderer/pipe/quad/UVMapper.java | 28 ++ .../renderer/pipe/util/ActivableCacheKey.java | 28 ++ .../client/renderer/pipe/util/CacheKey.java | 54 ++++ .../client/renderer/pipe/util/ColorData.java | 7 + .../renderer/pipe/util/SpriteInformation.java | 13 + .../gtceu/client/util/DrawUtil.java | 18 ++ .../client/util/EffectRenderContext.java | 85 ++++++ .../gtceu/client/util/RenderBufferHelper.java | 108 +++++++ .../gtceu/common/cover/FacadeCover.java | 5 + .../common/cover/MachineControllerCover.java | 11 +- .../gtceu/common/cover/ShutterCover.java | 5 + .../cover/filter/BaseFilterContainer.java | 252 +++++++++++++++ .../gtceu/common/data/GTBlockEntities.java | 20 +- .../gtceu/common/data/GTCovers.java | 4 +- .../gtceu/common/data/GTRecipes.java | 4 +- .../machine/trait/miner/SteamMinerLogic.java | 6 +- .../recipe/generated/PipeRecipeHandler.java | 10 +- .../data/recipe/misc/CreateRecipeLoader.java | 2 +- .../recipe/misc/MetaTileEntityLoader.java | 2 +- .../MetaTileEntityMachineRecipeLoader.java | 2 +- .../gtceu/utils/DimensionFacingPos.java | 41 +++ .../com/gregtechceu/gtceu/utils/GTUtil.java | 106 ++++++- .../gtceu/utils/TaskScheduler.java | 88 ++++++ .../gtceu/utils/function/Task.java | 12 + 117 files changed, 4334 insertions(+), 805 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/blockentity/SyncedBlockEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java rename src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/{PipeMaterialTileEntity.java => PipeMaterialBlockEntity.java} (78%) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/network/PacketDataList.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/IRenderSetup.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/SubListAddress.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/OverlayLayerDefinition.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/CacheKey.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformation.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java create mode 100644 src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java create mode 100644 src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java create mode 100644 src/main/java/com/gregtechceu/gtceu/utils/function/Task.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java index e070d27a7a..bf77251371 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java @@ -3,6 +3,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java new file mode 100644 index 0000000000..b12522c93e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java @@ -0,0 +1,94 @@ +package com.gregtechceu.gtceu.api.blockentity; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.Connection; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.world.level.block.entity.BlockEntity; + +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +/** + * Functions which sync data between the Server and Client sides in a TileEntity. + */ +public interface ISyncedBlockEntity { + + /** + * Used to sync data from Server -> Client. + * Called during initial loading of the chunk or when many blocks change at once. + *

+ * Data is received in {@link #receiveInitialSyncData(FriendlyByteBuf)}. + *

+ * Typically used to send server side data to the client on initial chunk loading. + *

+ * Should be called automatically. + *

+ * This method is called Server-Side. + *

+ * Equivalent to {@link BlockEntity#getUpdateTag()}. + * + * @param buf the buffer to write data to + */ + void writeInitialSyncData(@NotNull FriendlyByteBuf buf); + + /** + * Used to receive Server -> Client sync data. + * Called during initial loading of the chunk or when many blocks change at once. + *

+ * Data sent is from {@link #writeInitialSyncData(FriendlyByteBuf)}. + *

+ * Typically used to receive server side data on initial chunk loading. + *

+ * Should be called automatically. + *

+ * This method is called Client-Side. + *

+ * Equivalent to {@link net.minecraft.world.level.block.entity.BlockEntity#handleUpdateTag(CompoundTag)}. + * + * @param buf the buffer to read data from + */ + void receiveInitialSyncData(@NotNull FriendlyByteBuf buf); + + /** + * Used to send an anonymous Server -> Client packet. + * Call to build up the packet to send to the client when it is re-synced. + *

+ * Data is received in {@link #receiveCustomData(int, FriendlyByteBuf)}; + *

+ * Typically used to signal to the client that a rendering update is needed + * when sending a server-side state update. + *

+ * Should be called manually. + *

+ * This method is called Server-Side. + *

+ * Equivalent to {@link BlockEntity#getUpdatePacket()} + * + * @param discriminator the discriminator determining the packet sent. + * @param dataWriter a consumer which writes packet data to a buffer. + * @see gregtech.api.capability.GregtechDataCodes + */ + void writeCustomData(int discriminator, @NotNull Consumer<@NotNull FriendlyByteBuf> dataWriter); + + /** + * Used to receive an anonymous Server -> Client packet. + * Called when receiving a packet for the location this TileEntity is currently in. + *

+ * Data is sent with {@link #writeCustomData(int, Consumer)}. + *

+ * Typically used to perform a rendering update when receiving server-side state changes. + *

+ * Should be called automatically. + *

+ * This method is called Client-Side. + *

+ * Equivalent to {@link BlockEntity#onDataPacket(Connection, ClientboundBlockEntityDataPacket)} + * + * @param discriminator the discriminator determining the packet sent. + * @param buf the buffer containing the packet data. + * @see gregtech.api.capability.GregtechDataCodes + */ + void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java index e2f3fa2d98..0e780dc71f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java @@ -3,28 +3,32 @@ import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IRPCBlockEntity; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; + import org.jetbrains.annotations.MustBeInvokedByOverriders; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; -public abstract class NeighborCacheBlockEntity extends BlockEntity implements INeighborCache, - IAsyncAutoSyncBlockEntity, IRPCBlockEntity, IAutoPersistBlockEntity { +public abstract class NeighborCacheBlockEntity extends SyncedBlockEntity implements INeighborCache, + IAsyncAutoSyncBlockEntity, IRPCBlockEntity, IAutoPersistBlockEntity { private final BlockEntity[] neighbors = new BlockEntity[6]; private boolean neighborsInvalidated = false; + /** * @param doInvalidationHere set to false if you override {@link NeighborCacheBlockEntity#invalidateNeighbors()} * with a method that references something you do not yet have set. */ - public NeighborCacheBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState, boolean doInvalidationHere) { + public NeighborCacheBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState, + boolean doInvalidationHere) { super(type, pos, blockState); if (doInvalidationHere) invalidateNeighbors(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/SyncedBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/SyncedBlockEntity.java new file mode 100644 index 0000000000..7217941ea5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/SyncedBlockEntity.java @@ -0,0 +1,119 @@ +package com.gregtechceu.gtceu.api.blockentity; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.network.PacketDataList; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.Connection; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +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 io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.function.Consumer; + +public abstract class SyncedBlockEntity extends BlockEntity implements ISyncedBlockEntity, INeighborCache { + + private final PacketDataList updates = new PacketDataList(); + + public SyncedBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { + super(type, pos, blockState); + } + + public @Nullable BlockEntity getNeighbor(@NotNull Direction side) { + if (level == null || worldPosition == null) return null; + return level.getBlockEntity(worldPosition.relative(side)); + } + + @Override + public final void writeCustomData(int discriminator, @NotNull Consumer<@NotNull FriendlyByteBuf> dataWriter) { + ByteBuf backedBuffer = Unpooled.buffer(); + dataWriter.accept(new FriendlyByteBuf(backedBuffer)); + byte[] updateData = Arrays.copyOfRange(backedBuffer.array(), 0, backedBuffer.writerIndex()); + this.updates.add(discriminator, updateData); + notifyWorld(); + } + + /** + * Adds all data packets from another synced tile entity. Useful when the old tile is replaced with a new one. + * + * @param syncedBlockEntity other synced tile entity + */ + public void addPacketsFrom(SyncedBlockEntity syncedBlockEntity) { + if (this == syncedBlockEntity || syncedBlockEntity.updates.isEmpty()) return; + boolean wasEmpty = this.updates.isEmpty(); + this.updates.addAll(syncedBlockEntity.updates); + syncedBlockEntity.updates.clear(); + if (wasEmpty) notifyWorld(); // if the data is not empty we already notified the world + } + + private void notifyWorld() { + BlockState blockState = getBlockState(); + level.sendBlockUpdated(getBlockPos(), blockState, blockState, 0); + } + + @Override + public final Packet getUpdatePacket() { + if (this.updates.isEmpty()) { + return null; + } + CompoundTag updateTag = new CompoundTag(); + updateTag.put("d", this.updates.dumpToNbt()); + return ClientboundBlockEntityDataPacket.create(this, be -> updateTag); + } + + @Override + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { + CompoundTag updateTag = pkt.getTag(); + ListTag listTag = updateTag.getList("d", Tag.TAG_COMPOUND); + for (Tag entryBase : listTag) { + CompoundTag entryTag = (CompoundTag) entryBase; + for (String discriminatorKey : entryTag.getAllKeys()) { + ByteBuf backedBuffer = Unpooled.copiedBuffer(entryTag.getByteArray(discriminatorKey)); + receiveCustomData(Integer.parseInt(discriminatorKey), new FriendlyByteBuf(backedBuffer)); + if (backedBuffer.readableBytes() != 0) { + GTCEu.LOGGER.error( + "Class {} failed to finish reading receiveCustomData with discriminator {} and {} bytes remaining", + BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(this.getType()), discriminatorKey, + backedBuffer.readableBytes()); + } + } + } + } + + @Override + public final @NotNull CompoundTag getUpdateTag() { + CompoundTag updateTag = super.getUpdateTag(); + ByteBuf backedBuffer = Unpooled.buffer(); + writeInitialSyncData(new FriendlyByteBuf(backedBuffer)); + byte[] updateData = Arrays.copyOfRange(backedBuffer.array(), 0, backedBuffer.writerIndex()); + updateTag.putByteArray("d", updateData); + return updateTag; + } + + @Override + public final void handleUpdateTag(@NotNull CompoundTag tag) { + super.handleUpdateTag(tag); // deserializes Forge data and capabilities + byte[] updateData = tag.getByteArray("d"); + ByteBuf backedBuffer = Unpooled.copiedBuffer(updateData); + receiveInitialSyncData(new FriendlyByteBuf(backedBuffer)); + if (backedBuffer.readableBytes() != 0) { + GTCEu.LOGGER.error("Class {} failed to finish reading initialSyncData with {} bytes remaining", + BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(this.getType()), backedBuffer.readableBytes()); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java b/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java index f621ef1d77..3813b7ac2d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java @@ -18,13 +18,17 @@ import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; +import net.minecraftforge.common.capabilities.ICapabilityProvider; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -33,7 +37,7 @@ import java.util.Objects; import java.util.stream.Collectors; -public interface ICoverable extends ITickSubscription, IAppearance { +public interface ICoverable extends ITickSubscription, IAppearance, ICapabilityProvider { Level getLevel(); @@ -51,8 +55,17 @@ public interface ICoverable extends ITickSubscription, IAppearance { void scheduleNeighborShapeUpdate(); + /** + * @param side the side to check + * @return if the cover can be added at the side + */ boolean canPlaceCoverOnSide(CoverDefinition definition, Direction side); + /** + * @return if it is possible to attach any cover at all + */ + boolean acceptsCovers(); + double getCoverPlateThickness(); Direction getFrontFacing(); @@ -64,14 +77,13 @@ public interface ICoverable extends ITickSubscription, IAppearance { IFluidTransfer getFluidTransferCap(@Nullable Direction side, boolean useCoverCapability); /** - * Its an internal method, you should never call it yourself. - *
* Use {@link ICoverable#removeCover(boolean, Direction, Player)} and * {@link ICoverable#placeCoverOnSide(Direction, ItemStack, CoverDefinition, ServerPlayer)} instead * * @param coverBehavior * @param side */ + @ApiStatus.Internal void setCoverAtSide(@Nullable CoverBehavior coverBehavior, Direction side); @Nullable @@ -151,6 +163,13 @@ default void onUnload() { } } + /** + * @param side the side to get the neighbor at + * @return the neighbor tile entity at the side + */ + @Nullable + BlockEntity getNeighbor(@NotNull Direction side); + default void onNeighborChanged(Block block, BlockPos fromPos, boolean isMoving) { for (CoverBehavior cover : getCovers()) { cover.onNeighborChanged(block, fromPos, isMoving); @@ -164,6 +183,13 @@ default boolean hasAnyCover() { return false; } + /** + * @param side the side to get the redstone from + * @param ignoreCover if the cover is being ignored + * @return the redstone signal being input at the side + */ + int getInputRedstoneSignal(@NotNull Direction side, boolean ignoreCover); + default boolean hasCover(Direction facing) { return getCoverAtSide(facing) != null; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java index 29587d813e..6978977aaa 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java @@ -5,7 +5,7 @@ import com.gregtechceu.gtceu.api.gui.factory.CoverUIFactory; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; -import com.gregtechceu.gtceu.client.renderer.cover.ICoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; @@ -27,8 +27,11 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; import lombok.Getter; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -140,10 +143,20 @@ public void setRedstoneSignalOutput(int redstoneSignalOutput) { coverHolder.markDirty(); } + /** + * @return if the Cover can connect to redstone + */ public boolean canConnectRedstone() { return false; } + /** + * Called when the redstone input signal changes. + * + * @param redstone the new signal value + */ + public void onRedstoneInputSignalChange(int redstone) {} + ////////////////////////////////////// // ******* Interaction *******// ////////////////////////////////////// @@ -176,7 +189,14 @@ public boolean shouldRenderPlate() { return true; } - public ICoverRenderer getCoverRenderer() { + /** + * @return if the pipe this cover is placed on should always render a connection to the cover + */ + public boolean forcePipeRenderConnection() { + return true; + } + + public CoverRenderer getCoverRenderer() { return coverDefinition.getCoverRenderer(); } @@ -220,4 +240,16 @@ public IItemTransfer getItemTransferCap(IItemTransfer defaultValue) { public IFluidTransfer getFluidTransferCap(IFluidTransfer defaultValue) { return defaultValue; } + + /** + * Will be called for each capability request to the CoverableView + * Cover can override CoverableView capabilities, modify their values, or deny accessing them + * + * @param capability the requested Capability + * @param defaultValue value of the capability from CoverableView itself + * @return the resulting capability the caller will receive + */ + public LazyOptional getCapability(@NotNull Capability capability, LazyOptional defaultValue) { + return defaultValue; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java index 7e05c81908..90b76e6f13 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.api.cover; import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.client.renderer.cover.ICoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; @@ -24,9 +24,9 @@ public interface TieredCoverBehaviourProvider { private final ResourceLocation id; private final CoverBehaviourProvider behaviorCreator; @Getter - private final ICoverRenderer coverRenderer; + private final CoverRenderer coverRenderer; - public CoverDefinition(ResourceLocation id, CoverBehaviourProvider behaviorCreator, ICoverRenderer coverRenderer) { + public CoverDefinition(ResourceLocation id, CoverBehaviourProvider behaviorCreator, CoverRenderer coverRenderer) { this.behaviorCreator = behaviorCreator; this.id = id; this.coverRenderer = coverRenderer; diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java index 297763b219..b14c0797ff 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java @@ -490,15 +490,15 @@ public MaterialStack multiply(long amount) { return new MaterialStack(this, amount); } - public > boolean hasProperty(PropertyKey key) { + public boolean hasProperty(PropertyKey key) { return getProperty(key) != null; } - public > T getProperty(PropertyKey key) { + public T getProperty(PropertyKey key) { return properties.getProperty(key); } - public > void setProperty(PropertyKey key, IMaterialProperty property) { + public void setProperty(PropertyKey key, IMaterialProperty property) { if (!GTCEuAPI.materialManager.canModifyMaterials()) { throw new IllegalStateException("Cannot add properties to a Material when registry is frozen!"); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/AlloyBlastProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/AlloyBlastProperty.java index d52d9b7259..0e9771607c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/AlloyBlastProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/AlloyBlastProperty.java @@ -11,7 +11,7 @@ import java.util.function.Supplier; -public class AlloyBlastProperty implements IMaterialProperty { +public class AlloyBlastProperty implements IMaterialProperty { /** * Internal material fluid field diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/BlastProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/BlastProperty.java index 0bfefaa5f0..3310f14e6c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/BlastProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/BlastProperty.java @@ -2,7 +2,7 @@ import org.jetbrains.annotations.NotNull; -public class BlastProperty implements IMaterialProperty { +public class BlastProperty implements IMaterialProperty { /** * Blast Furnace Temperature of this Material. diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/DustProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/DustProperty.java index e216d13d3a..8a98ca3bad 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/DustProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/DustProperty.java @@ -2,7 +2,7 @@ import lombok.Getter; -public class DustProperty implements IMaterialProperty { +public class DustProperty implements IMaterialProperty { /** * Tool level needed to harvest block of this Material. diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java index f7c5c6c5b1..d21cf1944d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java @@ -17,7 +17,7 @@ import java.util.Collection; import java.util.Objects; -public class FluidPipeProperties implements IMaterialProperty, IPropertyFluidFilter { +public class FluidPipeProperties implements IMaterialProperty, IPropertyFluidFilter { /** * The maximum number of channels any fluid pipe can have diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidProperty.java index cd06185ceb..29ac6184f8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidProperty.java @@ -19,7 +19,7 @@ import java.util.function.Supplier; @NoArgsConstructor -public class FluidProperty implements IMaterialProperty, FluidStorage { +public class FluidProperty implements IMaterialProperty, FluidStorage { private final FluidStorageImpl storage = new FluidStorageImpl(); @Getter diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/GemProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/GemProperty.java index 296fa2d6ae..dbd05e8038 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/GemProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/GemProperty.java @@ -1,6 +1,6 @@ package com.gregtechceu.gtceu.api.data.chemical.material.properties; -public class GemProperty implements IMaterialProperty { +public class GemProperty implements IMaterialProperty { @Override public void verifyProperty(MaterialProperties properties) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/HazardProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/HazardProperty.java index be0e630caf..f63a34822f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/HazardProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/HazardProperty.java @@ -33,7 +33,7 @@ * @date 2024/2/12 * @implNote HazardProperty */ -public class HazardProperty implements IMaterialProperty { +public class HazardProperty implements IMaterialProperty { public final MedicalCondition condition; public final HazardTrigger hazardTrigger; diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IMaterialProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IMaterialProperty.java index 00eb7da44f..e6952c83e4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IMaterialProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IMaterialProperty.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.api.data.chemical.material.properties; @FunctionalInterface -public interface IMaterialProperty { +public interface IMaterialProperty { void verifyProperty(MaterialProperties properties); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IngotProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IngotProperty.java index d7d1be9b70..2554f9f291 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IngotProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/IngotProperty.java @@ -6,7 +6,7 @@ import lombok.Setter; import org.jetbrains.annotations.Nullable; -public class IngotProperty implements IMaterialProperty { +public class IngotProperty implements IMaterialProperty { /** * Specifies a material into which this material parts turn when heated diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java index 283e7660da..acfb7a57d1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java @@ -2,7 +2,7 @@ import java.util.Objects; -public class ItemPipeProperties implements IMaterialProperty { +public class ItemPipeProperties implements IMaterialProperty { /** * Items will try to take the path with the lowest priority diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/MaterialProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/MaterialProperties.java index 759fe54781..3838011fa3 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/MaterialProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/MaterialProperties.java @@ -18,7 +18,7 @@ public static void addBaseType(PropertyKey baseTypeKey) { baseTypes.add(baseTypeKey); } - private final Map>, IMaterialProperty> propertyMap; + private final Map, IMaterialProperty> propertyMap; private Material material; public MaterialProperties() { @@ -29,15 +29,15 @@ public boolean isEmpty() { return propertyMap.isEmpty(); } - public > T getProperty(PropertyKey key) { + public T getProperty(PropertyKey key) { return key.cast(propertyMap.get(key)); } - public > boolean hasProperty(PropertyKey key) { + public boolean hasProperty(PropertyKey key) { return propertyMap.get(key) != null; } - public > void setProperty(PropertyKey key, IMaterialProperty value) { + public void setProperty(PropertyKey key, IMaterialProperty value) { if (value == null) throw new IllegalArgumentException("Material Property must not be null!"); if (hasProperty(key)) throw new IllegalArgumentException("Material Property " + key.toString() + " already registered!"); @@ -45,7 +45,7 @@ public > void setProperty(PropertyKey key, IMa propertyMap.remove(PropertyKey.EMPTY); } - public > void removeProperty(PropertyKey property) { + public void removeProperty(PropertyKey property) { if (!hasProperty(property)) throw new IllegalArgumentException("Material Property " + property.toString() + " not present!"); propertyMap.remove(property); @@ -53,7 +53,7 @@ public > void removeProperty(PropertyKey prope propertyMap.put(PropertyKey.EMPTY, PropertyKey.EMPTY.constructDefault()); } - public > void ensureSet(PropertyKey key, boolean verify) { + public void ensureSet(PropertyKey key, boolean verify) { if (!hasProperty(key)) { propertyMap.put(key, key.constructDefault()); propertyMap.remove(PropertyKey.EMPTY); @@ -61,12 +61,12 @@ public > void ensureSet(PropertyKey key, boole } } - public > void ensureSet(PropertyKey key) { + public void ensureSet(PropertyKey key) { ensureSet(key, false); } public void verify() { - List> oldList; + List oldList; do { oldList = new ArrayList<>(propertyMap.values()); oldList.forEach(p -> p.verifyProperty(this)); diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/OreProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/OreProperty.java index 1f6c014511..a25b4f506a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/OreProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/OreProperty.java @@ -14,7 +14,7 @@ import java.util.Arrays; import java.util.List; -public class OreProperty implements IMaterialProperty { +public class OreProperty implements IMaterialProperty { /** * List of Ore byproducts. diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java new file mode 100644 index 0000000000..1c33883a8b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java @@ -0,0 +1,155 @@ +package com.gregtechceu.gtceu.api.data.chemical.material.properties; + +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; + +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.util.StringRepresentable; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.LevelAccessor; + +import it.unimi.dsi.fastutil.objects.Object2ObjectRBTreeMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +public class PipeNetProperties implements IMaterialProperty, IPipeNetNodeHandler { + + protected final Map, IPipeNetMaterialProperty> properties = new Object2ObjectRBTreeMap<>( + Comparator.comparing(IPipeNetMaterialProperty.MaterialPropertyKey::getSerializedName)); + + public void setProperty(IPipeNetMaterialProperty property) { + this.properties.put(property.getKey(), property); + } + + public boolean hasProperty(IPipeNetMaterialProperty.MaterialPropertyKey key) { + return this.properties.containsKey(key); + } + + public Collection getRegisteredProperties() { + return properties.values(); + } + + public T getProperty(IPipeNetMaterialProperty.MaterialPropertyKey key) { + return key.cast(this.properties.get(key)); + } + + public void removeProperty(IPipeNetMaterialProperty.MaterialPropertyKey key) { + this.properties.remove(key); + } + + public boolean generatesStructure(IPipeStructure structure) { + for (IPipeNetMaterialProperty p : properties.values()) { + if (p.generatesStructure(structure)) return true; + } + return false; + } + + @Override + public @NotNull Collection getOrCreateFromNets(LevelAccessor level, BlockPos pos, + IPipeStructure structure) { + List list = new ObjectArrayList<>(); + for (IPipeNetMaterialProperty p : properties.values()) { + if (p.supportsStructure(structure)) { + WorldPipeNetNode node = p.getOrCreateFromNet(level, pos, structure); + if (node != null) list.add(node); + } + } + return list; + } + + @Override + public @NotNull Collection getFromNets(LevelAccessor level, BlockPos pos, + IPipeStructure structure) { + List list = new ObjectArrayList<>(); + for (IPipeNetMaterialProperty p : properties.values()) { + if (p.supportsStructure(structure)) { + WorldPipeNetNode node = p.getFromNet(level, pos, structure); + if (node != null) list.add(node); + } + } + return list; + } + + @Override + public void removeFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure) { + for (IPipeNetMaterialProperty p : properties.values()) { + if (p.supportsStructure(structure)) p.removeFromNet(level, pos, structure); + } + } + + @Override + public void addInformation(@NotNull ItemStack stack, BlockGetter level, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeStructure structure) { + for (IPipeNetMaterialProperty p : properties.values()) { + if (p.supportsStructure(structure)) + p.addInformation(stack, level, tooltip, flagIn, (IPipeMaterialStructure) structure); + } + } + + @Override + public void verifyProperty(MaterialProperties properties) { + for (IPipeNetMaterialProperty p : this.properties.values()) { + p.verifyProperty(properties); + } + } + + protected static final class MaterialPropertyComparator implements Comparator { + + @Override + public int compare(IPipeNetMaterialProperty o1, IPipeNetMaterialProperty o2) { + return 0; + } + } + + public interface IPipeNetMaterialProperty extends IMaterialProperty { + + @Nullable + WorldPipeNetNode getOrCreateFromNet(LevelAccessor world, BlockPos pos, IPipeStructure structure); + + @Nullable + WorldPipeNetNode getFromNet(LevelAccessor world, BlockPos pos, IPipeStructure structure); + + void mutateData(NetLogicData data, IPipeStructure structure); + + void removeFromNet(LevelAccessor world, BlockPos pos, IPipeStructure structure); + + boolean generatesStructure(IPipeStructure structure); + + boolean supportsStructure(IPipeStructure structure); + + void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeMaterialStructure structure); + + MaterialPropertyKey getKey(); + + class MaterialPropertyKey implements StringRepresentable { + + private final @NotNull String name; + + public MaterialPropertyKey(@NotNull String name) { + this.name = name; + } + + @Override + public @NotNull String getSerializedName() { + return name; + } + + T cast(IPipeNetMaterialProperty property) { + return (T) property; + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PolymerProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PolymerProperty.java index bc9d98e8a8..910be765b7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PolymerProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PolymerProperty.java @@ -2,7 +2,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialFlags; -public class PolymerProperty implements IMaterialProperty { +public class PolymerProperty implements IMaterialProperty { @Override public void verifyProperty(MaterialProperties properties) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java index 90fb77da86..4771282201 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java @@ -1,11 +1,13 @@ package com.gregtechceu.gtceu.api.data.chemical.material.properties; -public class PropertyKey> { +public class PropertyKey { public static final PropertyKey BLAST = new PropertyKey<>("blast", BlastProperty.class); public static final PropertyKey ALLOY_BLAST = new PropertyKey<>("blast_alloy", AlloyBlastProperty.class); public static final PropertyKey DUST = new PropertyKey<>("dust", DustProperty.class); + public static final PropertyKey PIPENET_PROPERTIES = new PropertyKey<>("net_pipe", + PipeNetProperties.class); public static final PropertyKey FLUID_PIPE = new PropertyKey<>("fluid_pipe", FluidPipeProperties.class); public static final PropertyKey FLUID = new PropertyKey<>("fluid", FluidProperty.class); @@ -45,7 +47,7 @@ protected T constructDefault() { } } - public T cast(IMaterialProperty property) { + public T cast(IMaterialProperty property) { return this.type.cast(property); } @@ -67,7 +69,7 @@ public String toString() { return key; } - private static class EmptyProperty implements IMaterialProperty { + private static class EmptyProperty implements IMaterialProperty { @Override public void verifyProperty(MaterialProperties properties) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/RotorProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/RotorProperty.java index ae3b17ff72..451b2bc2f6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/RotorProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/RotorProperty.java @@ -3,7 +3,7 @@ import lombok.Getter; import org.jetbrains.annotations.NotNull; -public class RotorProperty implements IMaterialProperty { +public class RotorProperty implements IMaterialProperty { /** * Power of rotors made from this Material. diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java index 8a1ef2ec06..4a631a823a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java @@ -17,7 +17,7 @@ import static com.gregtechceu.gtceu.api.item.tool.GTToolType.*; -public class ToolProperty implements IMaterialProperty { +public class ToolProperty implements IMaterialProperty { /** * Harvest speed of tools made from this Material. diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java index 81acb549bf..bc7c5fab79 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java @@ -7,7 +7,7 @@ import static com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialFlags.GENERATE_FOIL; -public class WireProperties implements IMaterialProperty { +public class WireProperties implements IMaterialProperty { private int voltage; private int amperage; diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WoodProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WoodProperty.java index 7f9d506ea4..12fb39471f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WoodProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WoodProperty.java @@ -1,6 +1,6 @@ package com.gregtechceu.gtceu.api.data.chemical.material.properties; -public class WoodProperty implements IMaterialProperty { +public class WoodProperty implements IMaterialProperty { @Override public void verifyProperty(MaterialProperties properties) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java index e644041030..14704d4512 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java @@ -1082,14 +1082,14 @@ public boolean doGenerateBlock(Material material) { } @FunctionalInterface - public interface MaterialRecipeHandler> { + public interface MaterialRecipeHandler { void accept(TagPrefix prefix, Material material, T property, Consumer provider); } - public > void executeHandler(Consumer provider, - PropertyKey propertyKey, - MaterialRecipeHandler handler) { + public void executeHandler(Consumer provider, + PropertyKey propertyKey, + MaterialRecipeHandler handler) { for (Material material : GTCEuAPI.materialManager.getRegisteredMaterials()) { if (material.hasProperty(propertyKey) && !material.hasFlag(MaterialFlags.NO_UNIFICATION) && !ChemicalHelper.get(this, material).isEmpty()) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java index 2c96f7697a..3c59fe7f63 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java @@ -13,11 +13,12 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.ListTag; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.nbt.Tag; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -204,15 +205,15 @@ public void readFromNBT(@NotNull CompoundTag nbt) { // construct map of node ids -> nodes, while building nodes to groups // construct edges using map Int2ObjectOpenHashMap groupMap = new Int2ObjectOpenHashMap<>(); - NBTTagList vertices = nbt.getTagList("Vertices", 10); - int vertexCount = vertices.tagCount(); + ListTag vertices = nbt.getList("Vertices", Tag.TAG_COMPOUND); + int vertexCount = vertices.size(); Int2ObjectOpenHashMap vertexMap = new Int2ObjectOpenHashMap<>(vertexCount); for (int i = 0; i < vertexCount; i++) { - CompoundTag tag = vertices.getCompoundTagAt(i); + CompoundTag tag = vertices.getCompound(i); NetNode node = this.backedNet.getNewNode(); node.deserializeNBT(tag); - if (tag.hasKey("GroupID")) { - int id = tag.getInteger("GroupID"); + if (tag.contains("GroupID")) { + int id = tag.getInt("GroupID"); NetGroup group = groupMap.get(id); if (group == null) { group = new NetGroup(this.backedNet); @@ -226,12 +227,12 @@ public void readFromNBT(@NotNull CompoundTag nbt) { this.vertexMap.put(node.getEquivalencyData(), vertex); } - NBTTagList edges = nbt.getTagList("Edges", 10); - int edgeCount = edges.tagCount(); + ListTag edges = nbt.getList("Edges", Tag.TAG_COMPOUND); + int edgeCount = edges.size(); for (int i = 0; i < edgeCount; i++) { - CompoundTag tag = edges.getCompoundTagAt(i); - GraphEdge graphEdge = this.getGraph().addEdge(vertexMap.get(tag.getInteger("SourceID")), - vertexMap.get(tag.getInteger("TargetID"))); + CompoundTag tag = edges.getCompound(i); + GraphEdge graphEdge = this.getGraph().addEdge(vertexMap.get(tag.getInt("SourceID")), + vertexMap.get(tag.getInt("TargetID"))); this.getGraph().setEdgeWeight(graphEdge, tag.getDouble("Weight")); graphEdge.wrapped.deserializeNBT(tag); } @@ -246,7 +247,7 @@ public void readFromNBT(@NotNull CompoundTag nbt) { Object2IntOpenHashMap vertexMap = new Object2IntOpenHashMap<>(); int i = 0; int g = 0; - NBTTagList vertices = new NBTTagList(); + ListTag vertices = new ListTag(); for (GraphVertex graphVertex : this.getGraph().vertexSet()) { vertexMap.put(graphVertex, i); NetGroup group = graphVertex.wrapped.getGroupUnsafe(); @@ -258,22 +259,22 @@ public void readFromNBT(@NotNull CompoundTag nbt) { groupID = g; g++; } else groupID = groupMap.getInt(group); - tag.setInteger("GroupID", groupID); + tag.putInt("GroupID", groupID); } - vertices.appendTag(tag); + vertices.add(tag); i++; } - compound.setTag("Vertices", vertices); + compound.put("Vertices", vertices); - NBTTagList edges = new NBTTagList(); + ListTag edges = new ListTag(); for (GraphEdge graphEdge : this.getGraph().edgeSet()) { CompoundTag tag = graphEdge.wrapped.serializeNBT(); - tag.setInteger("SourceID", vertexMap.getInt(graphEdge.getSource())); - tag.setInteger("TargetID", vertexMap.getInt(graphEdge.getTarget())); - tag.setDouble("Weight", graphEdge.getWeight()); - edges.appendTag(tag); + tag.putInt("SourceID", vertexMap.getInt(graphEdge.getSource())); + tag.putInt("TargetID", vertexMap.getInt(graphEdge.getTarget())); + tag.putDouble("Weight", graphEdge.getWeight()); + edges.add(tag); } - compound.setTag("Edges", edges); + compound.put("Edges", edges); return compound; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java index 0bf6b9e4f9..863cb9ee4d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java @@ -20,7 +20,8 @@ * B) making sure that logic entries requiring it are the same object across all synced nodes.
*
* MultiNodeHelpers have no standard implementation and must be handled by a net and its nodes; see - * {@link com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet} and {@link com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode} + * {@link com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet} and + * {@link com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode} * for an example of this in action. */ public class MultiNodeHelper implements INetLogicEntryListener { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java index bb1374eaee..646c4cf22a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java @@ -7,9 +7,12 @@ import com.gregtechceu.gtceu.api.graphnet.path.INetPath; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.lowdragmc.lowdraglib.syncdata.IContentChangeAware; +import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; +import lombok.Getter; +import lombok.Setter; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NBTTagList; -import net.minecraftforge.common.util.INBTSerializable; +import net.minecraft.nbt.ListTag; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -18,7 +21,11 @@ import java.util.Iterator; import java.util.Objects; -public abstract class NetNode implements INBTSerializable { +public abstract class NetNode implements ITagSerializable, IContentChangeAware { + + @Getter + @Setter + public Runnable onContentsChanged = () -> {}; /** * For interacting with the internal graph representation ONLY, do not use or set this field otherwise. @@ -60,6 +67,9 @@ public void setActive(boolean active) { NetGroup group = getGroupUnsafe(); if (group != null) group.clearPathCaches(); else this.clearPathCache(); + if (onContentsChanged != null) { + onContentsChanged.run(); + } } } @@ -121,8 +131,8 @@ public void onRemove() {} @Override public CompoundTag serializeNBT() { CompoundTag tag = new CompoundTag(); - tag.setTag("Data", this.data.serializeNBT()); - tag.setBoolean("IsActive", this.isActive()); + tag.put("Data", this.data.serializeNBT()); + tag.putBoolean("IsActive", this.isActive()); return tag; } @@ -130,7 +140,7 @@ public CompoundTag serializeNBT() { public void deserializeNBT(CompoundTag nbt) { this.isActive = nbt.getBoolean("IsActive"); this.data.clearData(); - this.data.deserializeNBT((NBTTagList) nbt.getTag("Data")); + this.data.deserializeNBT((ListTag) nbt.get("Data")); } /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java index 2381c4bb7f..d022176ef4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/NetPathMapper.java @@ -3,8 +3,8 @@ import com.gregtechceu.gtceu.api.graphnet.graph.GraphEdge; import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; import com.gregtechceu.gtceu.api.graphnet.path.INetPath; -import gregtech.api.util.function.TriFunction; +import org.apache.commons.lang3.function.TriFunction; import org.jetbrains.annotations.NotNull; import org.jgrapht.GraphPath; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java index 5f45c96939..e503ff3974 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/SinglePathAlgorithm.java @@ -7,7 +7,6 @@ import com.gregtechceu.gtceu.api.graphnet.graph.GraphVertex; import com.gregtechceu.gtceu.api.graphnet.path.INetPath; -import com.github.bsideup.jabel.Desugar; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.Iterator; @@ -84,6 +83,5 @@ private double getWeight(GraphEdge graphEdge) { return this.net.getGraph().getEdgeWeight(graphEdge); } - @Desugar private record Results(double weight, boolean valid) {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java index 1e6790c5f5..691aee9866 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java @@ -3,10 +3,9 @@ import com.gregtechceu.gtceu.api.graphnet.IGraphNet; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; -import net.minecraft.util.math.MathHelper; - import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.util.Mth; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -142,7 +141,7 @@ public void recalculateFlowLimits(long queryTick) { this.map.clear(); } else { List toRemove = new ObjectArrayList<>(); - long regenerationPer = MathHelper.ceil((double) regenerationUnits * getThroughput() / map.size()); + long regenerationPer = Mth.ceil((double) regenerationUnits * getThroughput() / map.size()); map.replaceAll((k, v) -> { v -= regenerationPer; if (v <= 0) toRemove.add(k); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java index d4b93c36de..485ad56103 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java @@ -1,12 +1,12 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import net.minecraft.nbt.NBTTagDouble; -import net.minecraft.network.PacketBuffer; +import net.minecraft.nbt.DoubleTag; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.NotNull; public abstract class AbstractDoubleLogicData> - extends NetLogicEntry { + extends NetLogicEntry { private double value; @@ -28,22 +28,22 @@ public double getValue() { } @Override - public NBTTagDouble serializeNBT() { - return new NBTTagDouble(this.value); + public DoubleTag serializeNBT() { + return DoubleTag.valueOf(this.value); } @Override - public void deserializeNBT(NBTTagDouble nbt) { - this.value = nbt.getDouble(); + public void deserializeNBT(DoubleTag nbt) { + this.value = nbt.getAsDouble(); } @Override - public void encode(PacketBuffer buf, boolean fullChange) { + public void encode(FriendlyByteBuf buf, boolean fullChange) { buf.writeDouble(value); } @Override - public void decode(PacketBuffer buf, boolean fullChange) { + public void decode(FriendlyByteBuf buf, boolean fullChange) { this.value = buf.readDouble(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java index dfa8e2cc24..43519a7148 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java @@ -1,11 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import net.minecraft.nbt.NBTTagInt; -import net.minecraft.network.PacketBuffer; +import net.minecraft.nbt.IntTag; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.NotNull; -public abstract class AbstractIntLogicData> extends NetLogicEntry { +public abstract class AbstractIntLogicData> extends NetLogicEntry { private int value; @@ -27,22 +27,22 @@ public int getValue() { } @Override - public NBTTagInt serializeNBT() { - return new NBTTagInt(this.value); + public IntTag serializeNBT() { + return IntTag.valueOf(this.value); } @Override - public void deserializeNBT(NBTTagInt nbt) { - this.value = nbt.getInt(); + public void deserializeNBT(IntTag nbt) { + this.value = nbt.getAsInt(); } @Override - public void encode(PacketBuffer buf, boolean fullChange) { + public void encode(FriendlyByteBuf buf, boolean fullChange) { buf.writeVarInt(this.value); } @Override - public void decode(PacketBuffer buf, boolean fullChange) { + public void decode(FriendlyByteBuf buf, boolean fullChange) { this.value = buf.readVarInt(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java index a5dae29cb2..b51d9c4135 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java @@ -1,12 +1,12 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import net.minecraft.nbt.NBTTagLong; -import net.minecraft.network.PacketBuffer; +import net.minecraft.nbt.LongTag; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; -public abstract class AbstractLongLogicData> extends NetLogicEntry { +public abstract class AbstractLongLogicData> extends NetLogicEntry { private long value; @@ -29,22 +29,22 @@ public long getValue() { } @Override - public NBTTagLong serializeNBT() { - return new NBTTagLong(this.value); + public LongTag serializeNBT() { + return LongTag.valueOf(this.value); } @Override - public void deserializeNBT(NBTTagLong nbt) { - this.value = nbt.getLong(); + public void deserializeNBT(LongTag nbt) { + this.value = nbt.getAsLong(); } @Override - public void encode(PacketBuffer buf, boolean fullChange) { + public void encode(FriendlyByteBuf buf, boolean fullChange) { buf.writeVarLong(this.value); } @Override - public void decode(PacketBuffer buf, boolean fullChange) { + public void decode(FriendlyByteBuf buf, boolean fullChange) { this.value = buf.readVarLong(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index ce3554e751..571c25ec6e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -1,15 +1,19 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import net.minecraft.nbt.ListTag; +import com.lowdragmc.lowdraglib.syncdata.IContentChangeAware; +import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; + import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.StringRepresentable; -import net.minecraftforge.common.util.INBTSerializable; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectCollection; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import lombok.Getter; +import lombok.Setter; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -17,10 +21,16 @@ import java.util.Set; /** - * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on logics, + * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on + * logics, * making a logics class return two different names is a valid way to register multiple instances. */ -public final class NetLogicData implements INBTSerializable, INetLogicEntryListener { +public final class NetLogicData implements ITagSerializable, IContentChangeAware, INetLogicEntryListener { + + @Nullable + @Getter + @Setter + private Runnable onContentsChanged = () -> {}; // TODO caching logic on simple logics to reduce amount of reduntant creation? private final Object2ObjectOpenHashMap> logicEntrySet; @@ -67,6 +77,9 @@ public NetLogicData setLogicEntry(NetLogicEntry entry) { public void clearData() { logicEntrySet.clear(); logicEntrySet.trim(4); + if (onContentsChanged != null) { + onContentsChanged.run(); + } } public NetLogicData removeLogicEntry(@NotNull NetLogicEntry key) { @@ -80,12 +93,18 @@ public NetLogicData removeLogicEntry(@NotNull String key) { this.listeners.forEach(l -> l.markChanged(entry, true, true)); logicEntrySet.trim(); } + if (onContentsChanged != null) { + onContentsChanged.run(); + } return this; } @Override public void markLogicEntryAsUpdated(NetLogicEntry entry, boolean fullChange) { this.listeners.forEach(l -> l.markChanged(entry, false, fullChange)); + if (onContentsChanged != null) { + onContentsChanged.run(); + } } public boolean hasLogicEntry(@NotNull String key) { @@ -182,7 +201,7 @@ public void deserializeNBT(ListTag nbt) { } } - //@Override + // @Override public void encode(FriendlyByteBuf buf) { buf.writeVarInt(getEntries().size()); for (NetLogicEntry entry : getEntries()) { @@ -195,7 +214,7 @@ public void encode(FriendlyByteBuf buf) { } } - //@Override + // @Override public void decode(FriendlyByteBuf buf) { this.logicEntrySet.clear(); int entryCount = buf.readVarInt(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java index 4f4f3e669e..ee178efcde 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java @@ -5,6 +5,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; import com.lowdragmc.lowdraglib.networking.IPacket; + import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.StringRepresentable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index e783619091..6444f8582f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -12,7 +12,7 @@ public final class NetLogicRegistry { private static final Map>> REGISTRY = new Object2ObjectOpenHashMap<>(); static void register(NetLogicEntry entry) { - REGISTRY.putIfAbsent(entry.getName(), entry::getNew); + REGISTRY.putIfAbsent(entry.getSerializedName(), entry::getNew); } public static @Nullable Supplier<@NotNull NetLogicEntry> getSupplierNullable(String name) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java index 2a14200ee9..6e5852f6a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java @@ -7,8 +7,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; + import org.jetbrains.annotations.NotNull; import java.util.Collection; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java index 1b97663fa7..0976efc8f7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java @@ -3,13 +3,11 @@ import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseData; -import gregtech.api.util.TaskScheduler; -import gregtech.api.util.function.Task; -import net.minecraft.world.World; - -import com.github.bsideup.jabel.Desugar; +import com.gregtechceu.gtceu.utils.TaskScheduler; +import com.gregtechceu.gtceu.utils.function.Task; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.world.level.Level; import org.jetbrains.annotations.Nullable; import java.util.Map; @@ -39,7 +37,7 @@ public static void registerLossResult(Key key, NodeLossResult result) { private final Map cache = new Object2ObjectOpenHashMap<>(); - private NodeLossCache(World world) { + private NodeLossCache(Level world) { TaskScheduler.scheduleTask(world, TaskScheduler.weakTask(this)); } @@ -69,6 +67,5 @@ public static Key key(WorldPipeNetNode node, ITraverseData data) { return new Key(node, data.getTestObject(), data.getSimulatorKey()); } - @Desugar public record Key(WorldPipeNetNode node, IPredicateTestObject testObject, SimulatorKey simulator) {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index ade342a614..51606dc35e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet; import com.gregtechceu.gtceu.api.blockentity.IDirtyNotifiable; +import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.graphnet.IGraphNet; import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; import com.gregtechceu.gtceu.api.graphnet.NetNode; @@ -11,10 +12,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNet; - import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.Level; import net.minecraftforge.common.capabilities.Capability; @@ -36,7 +38,7 @@ public abstract class WorldPipeNet extends WorldNet { public static final int MULTI_NET_TIMEOUT = 10; - private static final Object2ObjectOpenHashMap> dimensionNets = new Object2ObjectOpenHashMap<>(); + private static final Object2ObjectOpenHashMap, Set> dimensionNets = new Object2ObjectOpenHashMap<>(); public WorldPipeNet(String name, Function graphBuilder, AlgorithmBuilder... algorithmBuilders) { @@ -48,11 +50,11 @@ public WorldPipeNet(String name, boolean directed, AlgorithmBuilder... algorithm } @Override - public void setWorld(Level world) { - if (getLevel() == world) return; - super.setLevel(world); + public void setLevel(Level level) { + if (getLevel() == level) return; + super.setLevel(level); dimensionNets.compute(getDimension(), (k, v) -> { - if (v == null) v = GTUtility.createWeakHashSet(); + if (v == null) v = GTUtil.createWeakHashSet(); v.add(this); return v; }); @@ -95,8 +97,8 @@ protected void updatePredicationInternal(@NotNull WorldPipeNetNode node, @NotNul * @return whether the predication state has changed and this net needs to be marked dirty. */ protected boolean predicateEdge(@NotNull NetEdge edge, @NotNull WorldPipeNetNode source, - @Nullable Cover coverSource, - @NotNull WorldPipeNetNode target, @Nullable Cover coverTarget) { + @Nullable CoverBehavior coverSource, + @NotNull WorldPipeNetNode target, @Nullable CoverBehavior coverTarget) { Map> prevValue = new Object2ObjectOpenHashMap<>( edge.getPredicateHandler().getPredicateSet()); edge.getPredicateHandler().clearPredicates(); @@ -127,7 +129,7 @@ protected boolean predicateEdge(@NotNull NetEdge edge, @NotNull WorldPipeNetNode * @param a the cover on the source of the edge * @param b the cover on the sink of the edge */ - protected void coverPredication(@NotNull NetEdge edge, @Nullable Cover a, @Nullable Cover b) {} + protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) {} public abstract Capability[] getTargetCapabilities(); @@ -173,10 +175,10 @@ public void synchronizeNode(WorldPipeNetNode node) { } public static String getDataID(final String baseID, final Level world) { - if (world == null || world.isRemote) + if (world == null || world.isClientSide) throw new RuntimeException("WorldPipeNets should only be created on the server!"); - int dimension = world.provider.getDimension(); - return baseID + '.' + dimension; + ResourceKey dimension = world.dimension(); + return baseID + '/' + dimension.location(); } /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java index ef292d7bfe..3af9762fd3 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -8,6 +8,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java index ab7e2ba899..dccdeeb300 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java @@ -1,18 +1,21 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import gregtech.api.cover.Cover; +import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import gregtech.api.util.DimensionFacingPos; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.utils.DimensionFacingPos; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.PacketBuffer; -import net.minecraft.tileentity.BlockEntity; -import net.minecraft.util.Direction; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -24,10 +27,10 @@ public final class EdgeCoverReferenceLogic extends NetLogicEntry coverSource; + private WeakReference coverSource; private DimensionFacingPos coverSourcePos; @Nullable - private WeakReference coverTarget; + private WeakReference coverTarget; private DimensionFacingPos coverTargetPos; public EdgeCoverReferenceLogic() { @@ -35,29 +38,29 @@ public EdgeCoverReferenceLogic() { } @Contract("_,_ -> this") - public EdgeCoverReferenceLogic coverSource(@NotNull DimensionFacingPos pos, @NotNull Cover cover) { + public EdgeCoverReferenceLogic coverSource(@NotNull DimensionFacingPos pos, @NotNull CoverBehavior cover) { this.coverSource = new WeakReference<>(cover); this.coverSourcePos = pos; return this; } @Contract("_,_ -> this") - public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @NotNull Cover cover) { + public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @NotNull CoverBehavior cover) { this.coverTarget = new WeakReference<>(cover); this.coverTargetPos = pos; return this; } - private @Nullable Cover getSource() { + private @Nullable CoverBehavior getSource() { if (coverSource == null) return null; - Cover ref = coverSource.get(); + CoverBehavior ref = coverSource.get(); if (ref == null) { - Level world = DimensionManager.getWorld(coverSourcePos.getDimension()); - if (world == null || !world.isBlockLoaded(coverSourcePos.getPos())) return null; + Level world = Platform.getMinecraftServer().getLevel(coverSourcePos.getDimension()); + if (world == null || !world.isLoaded(coverSourcePos.getPos())) return null; BlockEntity tile = world.getBlockEntity(coverSourcePos.getPos()); if (tile instanceof PipeBlockEntity pipe) { - Cover cover = pipe.getCoverHolder().getCoverAtSide(coverSourcePos.getFacing()); + CoverBehavior cover = pipe.getCoverHolder().getCoverAtSide(coverSourcePos.getFacing()); if (cover != null) { this.coverSource = new WeakReference<>(cover); return cover; @@ -77,16 +80,16 @@ public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @Not } } - private @Nullable Cover getTarget() { + private @Nullable CoverBehavior getTarget() { if (coverTarget == null) return null; - Cover ref = coverTarget.get(); + CoverBehavior ref = coverTarget.get(); if (ref == null) { - Level world = DimensionManager.getWorld(coverTargetPos.getDimension()); - if (world == null || !world.isBlockLoaded(coverTargetPos.getPos())) return null; + Level world = Platform.getMinecraftServer().getLevel(coverTargetPos.getDimension()); + if (world == null || !world.isLoaded(coverTargetPos.getPos())) return null; BlockEntity tile = world.getBlockEntity(coverTargetPos.getPos()); if (tile instanceof PipeBlockEntity pipe) { - Cover cover = pipe.getCoverHolder().getCoverAtSide(coverTargetPos.getFacing()); + CoverBehavior cover = pipe.getCoverHolder().getCoverAtSide(coverTargetPos.getFacing()); if (cover != null) { this.coverTarget = new WeakReference<>(cover); return cover; @@ -109,22 +112,22 @@ public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @Not @Override public CompoundTag serializeNBT() { CompoundTag tag = new CompoundTag(); - tag.setLong("SourcePos", coverSourcePos.getPos().toLong()); - tag.setByte("SourceFacing", (byte) coverSourcePos.getFacing().ordinal()); - tag.setInteger("SourceDim", coverSourcePos.getDimension()); - tag.setLong("TargetPos", coverTargetPos.getPos().toLong()); - tag.setByte("TargetFacing", (byte) coverTargetPos.getFacing().ordinal()); - tag.setInteger("TargetDim", coverTargetPos.getDimension()); + tag.putLong("SourcePos", coverSourcePos.getPos().asLong()); + tag.putByte("SourceFacing", (byte) coverSourcePos.getFacing().ordinal()); + tag.putString("SourceDim", coverSourcePos.getDimension().location().toString()); + tag.putLong("TargetPos", coverTargetPos.getPos().asLong()); + tag.putByte("TargetFacing", (byte) coverTargetPos.getFacing().ordinal()); + tag.putString("TargetDim", coverTargetPos.getDimension().location().toString()); return tag; } @Override public void deserializeNBT(CompoundTag nbt) { - this.coverSourcePos = new DimensionFacingPos(BlockPos.fromLong(nbt.getLong("SourcePos")), - GTUtil.DIRECTIONS[nbt.getByte("SourceFacing")], nbt.getInteger("SourceDim")); + this.coverSourcePos = new DimensionFacingPos(BlockPos.of(nbt.getLong("SourcePos")), + GTUtil.DIRECTIONS[nbt.getByte("SourceFacing")], ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("SourceDim")))); this.coverSource = new WeakReference<>(null); - this.coverTargetPos = new DimensionFacingPos(BlockPos.fromLong(nbt.getLong("TargetPos")), - GTUtil.DIRECTIONS[nbt.getByte("TargetFacing")], nbt.getInteger("TargetDim")); + this.coverTargetPos = new DimensionFacingPos(BlockPos.of(nbt.getLong("TargetPos")), + GTUtil.DIRECTIONS[nbt.getByte("TargetFacing")], ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("TargetDim")))); this.coverTarget = coverSource; } @@ -139,8 +142,8 @@ public boolean shouldEncode() { } @Override - public void encode(PacketBuffer buf, boolean fullChange) {} + public void encode(FriendlyByteBuf buf, boolean fullChange) {} @Override - public void decode(PacketBuffer buf, boolean fullChange) {} + public void decode(FriendlyByteBuf buf, boolean fullChange) {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index 962b0c4a88..3e04e322a4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -10,12 +10,16 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; import com.gregtechceu.gtceu.api.graphnet.traverse.util.CompleteLossOperator; import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; +import com.gregtechceu.gtceu.client.particle.GTOverheatParticle; + import com.lowdragmc.lowdraglib.Platform; + import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java index 6a98a05cb0..8f421395ba 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; import com.lowdragmc.lowdraglib.networking.IPacket; + import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.common.util.INBTSerializable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java index a9f52e7492..2ad5bb7168 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeCapabilityObject.java @@ -3,10 +3,9 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import net.minecraft.core.Direction; -import net.minecraft.util.Direction; import net.minecraftforge.common.capabilities.Capability; - import net.minecraftforge.common.util.LazyOptional; + import org.jetbrains.annotations.Nullable; public interface IPipeCapabilityObject { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java index 199009d0f3..3ea5e7bb19 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -1,12 +1,14 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; - +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.core.Direction; import net.minecraft.util.StringRepresentable; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; + import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java index 7dfe3e8f6c..f37751a880 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; -import gregtech.api.util.GTUtility; - +import com.gregtechceu.gtceu.utils.GTUtil; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import org.jetbrains.annotations.NotNull; @@ -27,7 +26,7 @@ public static void register(@NotNull T structure) { * Do not modify the returned set. */ public static @NotNull Set getStructures(Class structureClass) { - GTUtility.forceInitialization(structureClass); + GTUtil.forceInitialization(structureClass); Set structures = (Set) REGISTRY.get(structureClass); if (structures == null) return Collections.emptySet(); return structures; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index b0411066a5..5003cbd81f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -1,13 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import gregtech.api.unification.material.Material; - -import net.minecraft.item.ItemStack; import net.minecraft.network.chat.Component; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; + import org.jetbrains.annotations.NotNull; public class MaterialPipeBlockItem extends PipeBlockItem { @@ -23,14 +21,7 @@ public MaterialPipeBlockItem(Item.Properties properties, PipeMaterialBlock block @Override public Component getName(ItemStack stack) { - Material material = getBlock().getMaterialForStack(stack); - return material == null ? "unnamed" : getBlock().getStructure().getTagPrefix().getLocalNameForItem(material); - } - - @NotNull - @Override - public String getItemStackDisplayName(@NotNull ItemStack stack) { - Material material = getBlock().getMaterialForStack(stack); - return material == null ? "unnamed" : getBlock().getStructure().getTagPrefix().getLocalNameForItem(material); + Material material = getBlock().material; + return material == null ? Component.literal("unnamed") : getBlock().getStructure().getTagPrefix().getLocalizedName(material); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java index c87e69eb46..5b15e1e005 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java @@ -3,16 +3,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeActivableBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import gregtech.api.util.GTUtility; -import gregtech.client.renderer.pipe.ActivablePipeModel; - -import net.minecraft.block.state.BlockStateContainer; -import net.minecraft.block.state.BlockState; -import net.minecraft.tileentity.BlockEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -20,29 +15,19 @@ public abstract class PipeActivableBlock extends PipeBlock { - public PipeActivableBlock(IPipeStructure structure) { - super(structure); - } - - @Override - protected @NotNull BlockStateContainer.Builder constructState(BlockStateContainer.@NotNull Builder builder) { - return super.constructState(builder).add(ActivablePipeModel.ACTIVE_PROPERTY); - } - - @Override - public Class getTileClass(@NotNull Level world, @NotNull BlockState state) { - return PipeActivableBlockEntity.class; + public PipeActivableBlock(BlockBehaviour.Properties properties, IPipeStructure structure) { + super(properties, structure); } @Override - public @Nullable PipeActivableBlockEntity getBlockEntity(@NotNull IBlockAccess world, @NotNull BlockPos pos) { - if (GTUtility.arePosEqual(lastTilePos.get(), pos)) { + public @Nullable PipeActivableBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull BlockPos pos) { + if (lastTilePos.get().equals(pos)) { PipeBlockEntity tile = lastTile.get().get(); - if (tile != null && !tile.isInvalid()) return (PipeActivableBlockEntity) tile; + if (tile != null && !tile.isRemoved()) return (PipeActivableBlockEntity) tile; } BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof PipeActivableBlockEntity pipe) { - lastTilePos.set(pos.toImmutable()); + lastTilePos.set(pos.immutable()); lastTile.set(new WeakReference<>(pipe)); return pipe; } else return null; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index dff20c31cb..0deffae4ba 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -1,9 +1,8 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; +import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.block.MaterialBlock; -import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; @@ -15,14 +14,17 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCoverHolder; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; -import com.gregtechceu.gtceu.common.data.GTBlocks; +import com.gregtechceu.gtceu.api.pipenet.IPipeNode; +import com.gregtechceu.gtceu.common.data.GTBlockEntities; +import com.gregtechceu.gtceu.common.item.CoverPlaceBehavior; import com.gregtechceu.gtceu.config.ConfigHolder; +import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; import com.gregtechceu.gtceu.utils.EntityDamageUtil; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.client.renderer.IBlockRendererProvider; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import lombok.Getter; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; @@ -35,14 +37,16 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.*; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; @@ -54,6 +58,9 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import lombok.Getter; import org.apache.commons.lang3.mutable.MutableObject; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -97,13 +104,13 @@ public PipeBlock(BlockBehaviour.Properties properties, IPipeStructure structure) super(properties); this.structure = structure; /* - setTranslationKey(structure.getName()); - setSoundType(SoundType.METAL); - setHardness(2.0f); - setHarvestLevel(getToolClass(), 1); - setResistance(3.0f); - setLightOpacity(1); - disableStats(); + * setTranslationKey(structure.getName()); + * setSoundType(SoundType.METAL); + * setHardness(2.0f); + * setHarvestLevel(getToolClass(), 1); + * setResistance(3.0f); + * setLightOpacity(1); + * disableStats(); */ } @@ -134,123 +141,84 @@ public void doPlacementLogic(PipeBlockEntity tile, Direction placedBlockSearchSi } @Override - public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - ItemStack item = player.getItemInHand(hand); - PipeBlockEntity tile = getBlockEntity(level, pos); - if (tile != null) { - if (tile.getFrameMaterial() == null) { - MaterialBlock frame = (MaterialBlock) ((BlockItem) item.getItem()).getBlock(); - if (frame != null) { - tile.setFrameMaterial(frame.material); - SoundType type = frame.getSoundType(frame.defaultBlockState()); - level.playSound(player, pos, type.getPlaceSound(), SoundSource.BLOCKS, - (type.getVolume() + 1.0F) / 2.0F, type.getPitch() * 0.8F); - if (!player.isCreative()) { - item.shrink(1); - } - return InteractionResult.SUCCESS; - } - } + public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, + BlockHitResult hit) { + ItemStack itemStack = player.getItemInHand(hand); + BlockEntity entity = level.getBlockEntity(pos); + + PipeBlockEntity pipeBlockEntity = null; + if (entity instanceof PipeBlockEntity pbe) { + pipeBlockEntity = pbe; + } + if (pipeBlockEntity == null) { + return InteractionResult.FAIL; + } - Direction facing = hit.getDirection(); - Direction actualSide = ICoverable.determineGridSideHit(hit); - if (actualSide != null) facing = actualSide; - - // cover comes first - ICoverable coverable = tile.getCoverHolder(); - CoverBehavior cover = coverable.getCoverAtSide(facing); - if (cover != null) { - if (ToolHelper.isTool(item, GTToolType.SCREWDRIVER)) { - InteractionResult result = cover.onScrewdriverClick(player, hand, hit); - if (result != InteractionResult.PASS) { - if (result == InteractionResult.SUCCESS) { - ToolHelper.damageItem(item, player); - ToolHelper.playToolSound(GTToolType.SCREWDRIVER, (ServerPlayer) player); - return InteractionResult.SUCCESS; - } - return InteractionResult.PASS; - } - } - if (ToolHelper.isTool(item, GTToolType.SOFT_MALLET)) { - InteractionResult result = cover.onSoftMalletClick(player, hand, hit); - if (result != InteractionResult.PASS) { - if (result == InteractionResult.SUCCESS) { - ToolHelper.damageItem(item, player); - ToolHelper.playToolSound(GTToolType.SOFT_MALLET, (ServerPlayer) player); - return InteractionResult.SUCCESS; - } - return InteractionResult.PASS; - } - } - //InteractionResult result = cover.onRightClick(player, hand, trace); - //if (result == EnumActionResult.SUCCESS) return true; - - // allow crowbar to run even if the right click returns a failure - if (ToolHelper.isTool(item, GTToolType.CROWBAR)) { - coverable.removeCover(facing, player); - ToolHelper.damageItem(item, player); - ToolHelper.playToolSound(GTToolType.CROWBAR, (ServerPlayer) player); - return InteractionResult.SUCCESS; - } - } - // frame removal - Material frame = tile.getFrameMaterial(); - if (frame != null && ToolHelper.isTool(item, GTToolType.CROWBAR)) { - tile.setFrameMaterial(null); - popResource(level, pos, GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, frame).asStack()); - ToolHelper.damageItem(item, player); - ToolHelper.playToolSound(GTToolType.CROWBAR, (ServerPlayer) player); + if (pipeBlockEntity.getFrameMaterial() == null) { + var frameBlock = MaterialBlock.getFrameboxFromItem(itemStack); + if (frameBlock != null) { + pipeBlockEntity.setFrameMaterial(frameBlock.material); + if (!player.isCreative()) itemStack.shrink(1); + SoundType type = VanillaRecipeHelper.isMaterialWood(frameBlock.material) ? SoundType.WOOD : + SoundType.METAL; + level.playSound(player, pos, + type.getPlaceSound(), SoundSource.BLOCKS, + (type.getVolume() + 1.0F) / 2.0F, type.getPitch() * 0.8F); + player.swing(hand); return InteractionResult.SUCCESS; } - // pipe modification - if (isPipeTool(item)) { - PipeBlockEntity other = tile.getPipeNeighbor(facing, true); - - if (player.isShiftKeyDown() && allowsBlocking()) { - ToolHelper.damageItem(item, player); - ToolHelper.playToolSound(GTToolType.WRENCH, (ServerPlayer) player); - if (tile.isBlocked(facing)) unblockTile(tile, other, facing); - else blockTile(tile, other, facing); - } else { - if (tile.isConnected(facing)) { - ToolHelper.damageItem(item, player); - ToolHelper.playToolSound(item, player); - disconnectTile(tile, other, facing); - } else if (coverCheck(tile, other, facing)) { - ToolHelper.damageItem(item, player); - ToolHelper.playToolSound(item, player); - connectTile(tile, other, facing); - } else { - // if the covers disallow the connection, simply try to render a connection. - connectTile(tile, null, facing); - } + } + + if (itemStack.getItem() instanceof PipeBlockItem itemPipe) { + BlockPos offsetPos = pos.offset(hit.getDirection().getNormal()); + BlockState stateAtSide = level.getBlockState(offsetPos); + if (stateAtSide.getBlock() instanceof MaterialBlock matBlock && matBlock.tagPrefix == TagPrefix.frameGt) { + boolean wasPlaced = matBlock.replaceWithFramedPipe(level, offsetPos, stateAtSide, player, itemStack, + hit); + if (wasPlaced) { + connectTile(pipeBlockEntity, pipeBlockEntity.getPipeNeighbor(hit.getDirection(), false), + hit.getDirection()); } - return InteractionResult.SUCCESS; + return wasPlaced ? InteractionResult.CONSUME : InteractionResult.FAIL; } } - return super.use(state, level, pos, player, hand, hit); - } -/* - @Override - public void onBlockClicked(@NotNull Level worldIn, @NotNull BlockPos pos, @NotNull Player playerIn) { - PipeBlockEntity tile = getBlockEntity(worldIn, pos); - if (tile != null) { - RayTraceAABB trace = collisionRayTrace(playerIn, worldIn, pos); - if (trace == null) { - super.onBlockClicked(worldIn, pos, playerIn); - return; - } - Direction facing = trace.sideHit; - Direction actualSide = CoverRayTracer.determineGridSideHit(trace); - if (actualSide != null) facing = actualSide; - Cover cover = tile.getCoverHolder().getCoverAtSide(facing); - if (cover != null) { - if (cover.onLeftClick(playerIn, trace)) return; + + Set types = ToolHelper.getToolTypes(itemStack); + if (!types.isEmpty() && ToolHelper.canUse(itemStack)) { + var result = pipeBlockEntity.onToolClick(types, itemStack, new UseOnContext(player, hand, hit)); + if (result.getSecond() == InteractionResult.CONSUME && player instanceof ServerPlayer serverPlayer) { + ToolHelper.playToolSound(result.getFirst(), serverPlayer); + + if (!serverPlayer.isCreative()) { + ToolHelper.damageItem(itemStack, serverPlayer, 1); + } } + return result.getSecond(); } - super.onBlockClicked(worldIn, pos, playerIn); - } -*/ + return InteractionResult.PASS; + } + + /* + * @Override + * public void onBlockClicked(@NotNull Level worldIn, @NotNull BlockPos pos, @NotNull Player playerIn) { + * PipeBlockEntity tile = getBlockEntity(worldIn, pos); + * if (tile != null) { + * RayTraceAABB trace = collisionRayTrace(playerIn, worldIn, pos); + * if (trace == null) { + * super.onBlockClicked(worldIn, pos, playerIn); + * return; + * } + * Direction facing = trace.sideHit; + * Direction actualSide = CoverRayTracer.determineGridSideHit(trace); + * if (actualSide != null) facing = actualSide; + * Cover cover = tile.getCoverHolder().getCoverAtSide(facing); + * if (cover != null) { + * if (cover.onLeftClick(playerIn, trace)) return; + * } + * } + * super.onBlockClicked(worldIn, pos, playerIn); + * } + */ /** * Should be called to verify if a connection can be formed before * {@link #connectTile(PipeBlockEntity, PipeBlockEntity, Direction)} is called. @@ -260,7 +228,8 @@ public void onBlockClicked(@NotNull Level worldIn, @NotNull BlockPos pos, @NotNu public static boolean coverCheck(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, Direction facing) { CoverBehavior tileCover = tile.getCoverHolder().getCoverAtSide(facing); - CoverBehavior acrossCover = tileAcross != null ? tileAcross.getCoverHolder().getCoverAtSide(facing.getOpposite()) : + CoverBehavior acrossCover = tileAcross != null ? + tileAcross.getCoverHolder().getCoverAtSide(facing.getOpposite()) : null; return (tileCover == null || tileCover.canPipePassThrough()) && (acrossCover == null || acrossCover.canPipePassThrough()); @@ -320,7 +289,8 @@ public static void disconnectTile(@NotNull PipeBlockEntity tile, @Nullable PipeB } } - public static void blockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, Direction facing) { + public static void blockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBlockEntity tileAcross, + Direction facing) { tile.setBlocked(facing); if (tileAcross == null || tile.getLevel().isClientSide) return; @@ -381,9 +351,9 @@ public void destroy(LevelAccessor level, BlockPos pos, BlockState state) { // misc stuff // - @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag) { + public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, + TooltipFlag flag) { if (getStructure() instanceof IPipeChanneledStructure channeledStructure) { if (channeledStructure.getChannelCount() > 1) tooltip.add(Component.translatable("gtceu.pipe.channels", channeledStructure.getChannelCount())); @@ -414,7 +384,8 @@ public List getDrops(BlockState state, LootParams.Builder builder) { } @Override - public boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacements.Type type, EntityType entityType) { + public boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacements.Type type, + EntityType entityType) { return false; } @@ -431,24 +402,26 @@ public void entityInside(BlockState state, Level level, BlockPos pos, Entity ent } } - /* TODO fix - @Override - public boolean recolorBlock(@NotNull Level world, @NotNull BlockPos pos, @NotNull Direction side, - @NotNull EnumDyeColor color) { - if (getStructure().isPaintable()) { - PipeBlockEntity tile = getBlockEntity(world, pos); - if (tile != null && tile.getPaintingColor() != color.colorValue) { - tile.setPaintingColor(color.colorValue, false); - return true; - } - } - return false; - } + /* + * TODO fix + * + * @Override + * public boolean recolorBlock(@NotNull Level world, @NotNull BlockPos pos, @NotNull Direction side, + * + * @NotNull EnumDyeColor color) { + * if (getStructure().isPaintable()) { + * PipeBlockEntity tile = getBlockEntity(world, pos); + * if (tile != null && tile.getPaintingColor() != color.colorValue) { + * tile.setPaintingColor(color.colorValue, false); + * return true; + * } + * } + * return false; + * } */ // collision boxes // - @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { MutableObject shape = new MutableObject<>(Shapes.empty()); @@ -500,7 +473,7 @@ public boolean hasPipeCollisionChangingItem(BlockGetter world, BlockPos pos, Ite if (hasAnyCover && ToolHelper.isTool(stack, GTToolType.SCREWDRIVER)) return true; final boolean acceptsCovers = coverable.acceptsCovers(); - return GTUtil.isCoverBehaviorItem(stack, () -> hasAnyCover, coverDef -> acceptsCovers); + return CoverPlaceBehavior.isCoverBehaviorItem(stack, () -> hasAnyCover, coverDef -> acceptsCovers); } public boolean isPipeTool(@NotNull ItemStack stack) { @@ -513,17 +486,9 @@ public GTToolType getToolClass() { // blockstate // - @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - constructState(builder).add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED); - } - - protected @NotNull StateDefinition.Builder constructState(StateDefinition.Builder builder) { - return builder.add(AbstractPipeModel.THICKNESS_PROPERTY).add(AbstractPipeModel.CLOSED_MASK_PROPERTY) - .add(AbstractPipeModel.BLOCKED_MASK_PROPERTY).add(AbstractPipeModel.COLOR_PROPERTY) - .add(AbstractPipeModel.FRAME_MATERIAL_PROPERTY).add(AbstractPipeModel.FRAME_MASK_PROPERTY) - .add(CoverRendererPackage.PROPERTY); + builder.add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED); } public static BlockState writeConnectionMask(@NotNull BlockState state, byte connectionMask) { @@ -545,9 +510,18 @@ public static byte readConnectionMask(@NotNull BlockState state) { // tile entity // + @Nullable @Override - public final boolean hasBlockEntity(@NotNull BlockState state) { - return true; + public BlockEntityTicker getTicker(Level level, BlockState state, + BlockEntityType blockEntityType) { + if (!level.isClientSide && state.getValue(BlockProperties.SERVER_TICK)) { + return (pLevel, pPos, pState, pTile) -> { + if (pTile instanceof IPipeNode pipeNode) { + pipeNode.serverTick(); + } + }; + } + return null; } @Nullable @@ -567,7 +541,7 @@ public PipeBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull Block @Nullable @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new PipeBlockEntity(/*TODO block entity type*/, pos, state); + return new PipeBlockEntity(GTBlockEntities.NEW_PIPE.get(), pos, state); } @Override @@ -600,7 +574,6 @@ public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) { // cover compatibility // - @Override public void neighborChanged(BlockState state, Level level, BlockPos pos, Block neighborBlock, BlockPos neighborPos, boolean movedByPiston) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java index aab49900ca..ac13580e4e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.component.IInteractionItem; import com.gregtechceu.gtceu.common.data.GTItems; + import net.minecraft.world.InteractionHand; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.DyeColor; @@ -10,6 +11,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.block.state.BlockState; + import org.jetbrains.annotations.NotNull; public class PipeBlockItem extends BlockItem { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index 3793023a87..fee31966aa 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -8,18 +8,15 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeMaterialBlockEntity; import com.gregtechceu.gtceu.common.data.GTMaterials; import com.gregtechceu.gtceu.config.ConfigHolder; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; + import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import org.apache.commons.lang3.tuple.Pair; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -30,7 +27,8 @@ public abstract class PipeMaterialBlock extends PipeBlock { public final Material material; - public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStructure structure, Material material) { + public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStructure structure, + Material material) { super(properties, structure); this.material = material; } @@ -55,23 +53,18 @@ public IPipeMaterialStructure getStructure() { } @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag) { + public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, + TooltipFlag flag) { super.appendHoverText(stack, level, tooltip, flag); if (ConfigHolder.INSTANCE.dev.debug) { if (material != null) - tooltip.add(Component.literal("MetaItem Id: " + getStructure().getTagPrefix().name + material.toCamelCaseString())); + tooltip.add(Component + .literal("MetaItem Id: " + getStructure().getTagPrefix().name + material.toCamelCaseString())); } } // tile entity // - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - super.createBlockStateDefinition(builder); - builder.add(AbstractPipeModel.MATERIAL_PROPERTY); - } - @Override public @Nullable PipeMaterialBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull BlockPos pos) { if (lastTilePos.get().equals(pos)) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java index f1f85d0359..f79f156bc0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/IWorldPipeNetTile.java @@ -1,13 +1,12 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; import com.gregtechceu.gtceu.api.capability.ICoverable; -import gregtech.api.cover.CoverableView; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.tileentity.BlockEntity; -import net.minecraft.util.Direction; -import net.minecraft.util.EnumParticleTypes; +import net.minecraft.core.Direction; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.block.entity.BlockEntity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -32,9 +31,9 @@ public interface IWorldPipeNetTile { // fluid piping - void spawnParticles(Direction direction, EnumParticleTypes particleType, int particleCount); + void spawnParticles(Direction direction, ParticleOptions particleType, int particleCount); - void dealAreaDamage(int size, Consumer damageFunction); + void dealAreaDamage(int size, Consumer damageFunction); void playLossSound(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java index a5b9049afc..d7eaf9bda8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java @@ -1,43 +1,37 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; -import gregtech.api.capability.GregtechDataCodes; -import gregtech.client.renderer.pipe.ActivablePipeModel; - -import net.minecraft.network.PacketBuffer; -import net.minecraftforge.common.property.IExtendedBlockState; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import lombok.Getter; +import net.minecraft.core.BlockPos; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; public class PipeActivableBlockEntity extends PipeBlockEntity implements IActivable { + private static final int PIPE_ACTIVE = 2; + + @Getter private boolean active; + public PipeActivableBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { + super(type, pos, blockState); + } + @Override public void setActive(boolean active) { if (this.active != active) { this.active = active; - writeCustomData(GregtechDataCodes.PIPE_ACTIVE, buf -> buf.writeBoolean(active)); + writeCustomData(PIPE_ACTIVE, buf -> buf.writeBoolean(active)); markDirty(); } } @Override - public boolean isActive() { - return active; - } - - @Override - @OnlyIn(Dist.CLIENT) - public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { - return super.getRenderInformation(state).withProperty(ActivablePipeModel.ACTIVE_PROPERTY, isActive()); - } - - @Override - public void receiveCustomData(int discriminator, @NotNull PacketBuffer buf) { + public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { super.receiveCustomData(discriminator, buf); - if (discriminator == GregtechDataCodes.PIPE_ACTIVE) { + if (discriminator == PIPE_ACTIVE) { boolean active = buf.readBoolean(); if (this.active != active) { this.active = active; @@ -47,13 +41,13 @@ public void receiveCustomData(int discriminator, @NotNull PacketBuffer buf) { } @Override - public void writeInitialSyncData(@NotNull PacketBuffer buf) { + public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { buf.writeBoolean(active); super.writeInitialSyncData(buf); } @Override - public void receiveInitialSyncData(@NotNull PacketBuffer buf) { + public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { active = buf.readBoolean(); super.receiveInitialSyncData(buf); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index ea94562da5..2716ae7396 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -4,7 +4,6 @@ import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; import com.gregtechceu.gtceu.api.blockentity.NeighborCacheBlockEntity; -import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.IToolable; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverBehavior; @@ -20,13 +19,17 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; - import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.api.machine.TickableSubscription; -import com.gregtechceu.gtceu.api.pipenet.PipeCoverContainer; +import com.gregtechceu.gtceu.client.particle.GTOverheatParticle; +import com.gregtechceu.gtceu.client.particle.GTParticleManager; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; @@ -35,34 +38,42 @@ import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; -import com.mojang.datafixers.util.Pair; -import lombok.Getter; -import lombok.Setter; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.core.NonNullList; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.particles.ParticleOptions; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.TickTask; import net.minecraft.server.level.ServerLevel; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; 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.Blocks; 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.minecraft.world.phys.AABB; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; + +import com.mojang.datafixers.util.Pair; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import net.minecraftforge.common.util.LazyOptional; -import org.jetbrains.annotations.MustBeInvokedByOverriders; +import lombok.Getter; +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -72,11 +83,14 @@ import java.util.Set; import java.util.function.Consumer; -public class PipeBlockEntity extends NeighborCacheBlockEntity implements IWorldPipeNetTile, ITickSubscription, IEnhancedManaged, - IAsyncAutoSyncBlockEntity, IAutoPersistBlockEntity, IToolGridHighLight, IToolable { +public class PipeBlockEntity extends NeighborCacheBlockEntity + implements IWorldPipeNetTile, ITickSubscription, IEnhancedManaged, + IAsyncAutoSyncBlockEntity, IAutoPersistBlockEntity, IToolGridHighLight, IToolable { public static final int DEFAULT_COLOR = 0xFFFFFFFF; + public static final int UPDATE_PIPE_LOGIC = 0; + private final Int2ObjectOpenHashMap netLogicDatas = new Int2ObjectOpenHashMap<>(); private final ObjectOpenHashSet listeners = new ObjectOpenHashSet<>(); @@ -100,7 +114,7 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity implements IWorldP @Setter @DescSynced private @Nullable Material frameMaterial; - + private final List serverTicks = new ArrayList<>(); private final List waitingToAdd = new ArrayList<>(); @@ -141,14 +155,19 @@ public void getDrops(@NotNull List drops, @NotNull BlockState state) } @Override - public void validate() { - super.validate(); + public void clearRemoved() { + super.clearRemoved(); scheduleRenderUpdate(); } @Override - public void invalidate() { - super.invalidate(); + public void scheduleRenderUpdate() { + super.scheduleRenderUpdate(); + } + + @Override + public void setRemoved() { + super.setRemoved(); // TODO I hate this so much can someone please make it so that covers go through getDrops()? getCoverHolder().dropAllCovers(); } @@ -250,12 +269,50 @@ public int getDefaultPaintingColor() { // ticking // - public void addTicker(TickableSubscription ticker) { - this.tickers.add(ticker); + @Override + public @Nullable TickableSubscription subscribeServerTick(Runnable runnable) { + if (!isClientSide()) { + var subscription = new TickableSubscription(runnable); + waitingToAdd.add(subscription); + var blockState = getBlockState(); + if (!blockState.getValue(BlockProperties.SERVER_TICK)) { + if (getLevel() instanceof ServerLevel serverLevel) { + blockState = blockState.setValue(BlockProperties.SERVER_TICK, true); + setBlockState(blockState); + serverLevel.getServer().tell(new TickTask(0, () -> serverLevel.setBlockAndUpdate(getBlockPos(), + getBlockState().setValue(BlockProperties.SERVER_TICK, true)))); + } + } + return subscription; + } + return null; } - public void update() { - this.tickers.forEach(TickableSubscription::run); + @Override + public void unsubscribe(@Nullable TickableSubscription current) { + if (current != null) { + current.unsubscribe(); + } + } + + public final void serverTick() { + if (!waitingToAdd.isEmpty()) { + serverTicks.addAll(waitingToAdd); + waitingToAdd.clear(); + } + var iter = serverTicks.iterator(); + while (iter.hasNext()) { + var tickable = iter.next(); + if (tickable.isStillSubscribed()) { + tickable.run(); + } + if (!tickable.isStillSubscribed()) { + iter.remove(); + } + } + if (serverTicks.isEmpty() && waitingToAdd.isEmpty() && !this.isRemoved()) { + getLevel().setBlockAndUpdate(getBlockPos(), getBlockState().setValue(BlockProperties.SERVER_TICK, false)); + } } @Override @@ -264,10 +321,6 @@ public void onLoad() { initialize(); } - public boolean isTicking() { - return !tickers.isEmpty(); - } - // activeness // @Override @@ -297,7 +350,6 @@ public void onNeighborChanged(@NotNull Direction facing) { return caps; } - @Override public @Nullable BlockEntity getTargetWithCapabilities(WorldPipeNetNode node, Direction facing) { PipeCapabilityWrapper wrapper = netCapabilities.get(node); if (wrapper == null || !wrapper.isActive(facing)) return null; @@ -314,11 +366,6 @@ public PipeCapabilityWrapper getWrapperForNode(WorldPipeNetNode node) { return covers; } - @Override - public void dealAreaDamage(int size, Consumer damageFunction) { - - } - /** * Updates the pipe's active status based on the tile entity connected to the side. * @@ -385,7 +432,7 @@ public LazyOptional getCapability(@NotNull Capability capability, @Nul if (capability == GTCapability.CAPABILITY_COVERABLE) { return GTCapability.CAPABILITY_COVERABLE.orEmpty(capability, LazyOptional.of(this::getCovers)); } - T pipeCapability; + LazyOptional pipeCapability; IPipeCapabilityObject object = capabilities.get(capability); if (object == null || (pipeCapability = object.getCapabilityForSide(capability, facing)) == null) pipeCapability = super.getCapability(capability, facing); @@ -395,15 +442,15 @@ public LazyOptional getCapability(@NotNull Capability capability, @Nul if (facing == null || isConnected(facing)) { return pipeCapability; } - return null; + return super.getCapability(capability, facing); } - T coverCapability = cover.getCapability(capability, pipeCapability); + LazyOptional coverCapability = cover.getCapability(capability, pipeCapability); if (coverCapability == pipeCapability) { if (isConnectedCoverAdjusted(facing)) { return pipeCapability; } - return null; + return super.getCapability(capability, facing); } return coverCapability; } @@ -419,13 +466,13 @@ public NetLogicData getNetLogicData(int networkID) { } @Override - public void setWorld(@NotNull Level worldIn) { - if (worldIn == this.getWorld()) return; - super.setWorld(worldIn); + public void setLevel(@NotNull Level level) { + if (level == this.getLevel()) return; + super.setLevel(level); } protected void initialize() { - if (!getWorld().isRemote) { + if (!getLevel().isClientSide) { this.netLogicDatas.clear(); this.capabilities.clear(); this.netCapabilities.clear(); @@ -490,13 +537,14 @@ public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { scheduleRenderUpdate(); } + // TODO figure out replacement @Override - public void receiveCustomData(int discriminator, @NotNull PacketBuffer buf) { + public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { if (discriminator == UPDATE_PIPE_LOGIC) { // extra check just to make sure we don't affect actual net data with our writes - if (world.isRemote) { + if (level.isClientSide) { int networkID = buf.readVarInt(); - String identifier = buf.readString(255); + String identifier = buf.readUtf(255); boolean removed = buf.readBoolean(); boolean fullChange = buf.readBoolean(); if (removed) { @@ -518,30 +566,13 @@ public void receiveCustomData(int discriminator, @NotNull PacketBuffer buf) { data.markLogicEntryAsUpdated(entry, false); } else return; } - if (identifier.equals(TemperatureLogic.INSTANCE.getName())) { + if (identifier.equals(TemperatureLogic.INSTANCE.getSerializedName())) { TemperatureLogic tempLogic = this.netLogicDatas.get(networkID) .getLogicEntryNullable(TemperatureLogic.INSTANCE); if (tempLogic != null) updateTemperatureLogic(tempLogic); } } } - } else if (discriminator == UPDATE_CONNECTIONS) { - this.connectionMask = buf.readByte(); - this.renderMask = buf.readByte(); - scheduleRenderUpdate(); - } else if (discriminator == UPDATE_BLOCKED_CONNECTIONS) { - this.blockedMask = buf.readByte(); - scheduleRenderUpdate(); - } else if (discriminator == UPDATE_FRAME_MATERIAL) { - String name = buf.readString(255); - if (name.equals("")) this.frameMaterial = null; - else this.frameMaterial = GregTechAPI.materialManager.getMaterial(name); - scheduleRenderUpdate(); - } else if (discriminator == UPDATE_PAINT) { - this.paintingColor = buf.readInt(); - scheduleRenderUpdate(); - } else { - this.getCoverHolder().readCustomData(discriminator, buf); } } @@ -549,7 +580,7 @@ public void receiveCustomData(int discriminator, @NotNull PacketBuffer buf) { public void updateTemperatureLogic(@NotNull TemperatureLogic logic) { if (overheatParticle == null || !overheatParticle.isAlive()) { - long tick = FMLCommonHandler.instance().getMinecraftServerInstance().getTickCounter(); + long tick = Platform.getMinecraftServer().getTickCount(); int temp = logic.getTemperature(tick); if (temp > GTOverheatParticle.TEMPERATURE_CUTOFF) { IPipeStructure structure = this.getStructure(); @@ -579,17 +610,16 @@ public boolean isOverheatParticleAlive() { return overheatParticle != null && overheatParticle.isAlive(); } - @Override - public void spawnParticles(Direction direction, EnumParticleTypes particleType, int particleCount) { - if (getWorld() instanceof WorldServer server) { - server.spawnParticle(particleType, - getPos().getX() + 0.5, - getPos().getY() + 0.5, - getPos().getZ() + 0.5, + public void spawnParticles(Direction direction, ParticleOptions particleType, int particleCount) { + if (getLevel() instanceof ServerLevel server) { + server.sendParticles(particleType, + getBlockPos().getX() + 0.5, + getBlockPos().getY() + 0.5, + getBlockPos().getZ() + 0.5, particleCount, - direction.getXOffset() * 0.2 + GTValues.RNG.nextDouble() * 0.1, - direction.getYOffset() * 0.2 + GTValues.RNG.nextDouble() * 0.1, - direction.getZOffset() * 0.2 + GTValues.RNG.nextDouble() * 0.1, + direction.getStepX() * 0.2 + GTValues.RNG.nextDouble() * 0.1, + direction.getStepY() * 0.2 + GTValues.RNG.nextDouble() * 0.1, + direction.getStepZ() * 0.2 + GTValues.RNG.nextDouble() * 0.1, 0.1); } } @@ -597,25 +627,26 @@ public void spawnParticles(Direction direction, EnumParticleTypes particleType, // misc overrides // @Override - public Level world() { - return getWorld(); + public void notifyBlockUpdate() { + if (getLevel() != null) { + getLevel().updateNeighborsAt(getBlockPos(), getLevel().getBlockState(getBlockPos()).getBlock()); + } } - @Override - public BlockPos pos() { - return getPos(); - } + public void scheduleNeighborShapeUpdate() { + Level level = getLevel(); + BlockPos pos = getBlockPos(); - @Override - public void notifyBlockUpdate() { - getWorld().notifyNeighborsOfStateChange(getPos(), getBlockType(), true); + if (level == null || pos == null) + return; + + level.getBlockState(pos).updateNeighbourShapes(level, pos, Block.UPDATE_ALL); } @SuppressWarnings("ConstantConditions") // yes this CAN actually be null - @Override public void markDirty() { - if (getWorld() != null && getPos() != null) { - getWorld().markChunkDirty(getPos(), this); + if (getLevel() != null && getBlockPos() != null) { + getLevel().setBlocksDirty(getBlockPos(), this.getBlockState(), this.getBlockState()); } } @@ -628,39 +659,35 @@ public void markAsDirty() { } } - public static @Nullable PipeBlockEntity getTileNoLoading(BlockPos pos, int dimension) { - Level world = DimensionManager.getWorld(dimension); - if (world == null || !world.isBlockLoaded(pos)) return null; + public static @Nullable PipeBlockEntity getTileNoLoading(BlockPos pos, ResourceKey dimension) { + Level world = Platform.getMinecraftServer().getLevel(dimension); + if (world == null || !world.isLoaded(pos)) return null; BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof PipeBlockEntity pipe) return pipe; else return null; } - /** - * Note - the block corresponding to this tile entity must register any new unlisted properties to the default - * state. - */ - @OnlyIn(Dist.CLIENT) - @MustBeInvokedByOverriders - public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { + @Override + public @NotNull ModelData getModelData() { byte frameMask = 0; byte connectionMask = this.connectionMask; for (Direction facing : GTUtil.DIRECTIONS) { - Cover cover = getCoverHolder().getCoverAtSide(facing); + CoverBehavior cover = getCoverHolder().getCoverAtSide(facing); if (cover != null) { frameMask |= (byte) (1 << facing.ordinal()); if (cover.forcePipeRenderConnection()) connectionMask |= (byte) (1 << facing.ordinal()); } } - frameMask = (byte) ~frameMask; - return state.withProperty(AbstractPipeModel.THICKNESS_PROPERTY, this.getStructure().getRenderThickness()) - .withProperty(AbstractPipeModel.CLOSED_MASK_PROPERTY, renderMask) - .withProperty(AbstractPipeModel.BLOCKED_MASK_PROPERTY, blockedMask) - .withProperty(AbstractPipeModel.COLOR_PROPERTY, getPaintingColor()) - .withProperty(AbstractPipeModel.FRAME_MATERIAL_PROPERTY, frameMaterial) - .withProperty(AbstractPipeModel.FRAME_MASK_PROPERTY, frameMask) - .withProperty(CoverRendererPackage.PROPERTY, getCoverHolder().createPackage()); + return ModelData.builder() + .with(AbstractPipeModel.THICKNESS_PROPERTY, this.getStructure().getRenderThickness()) + .with(AbstractPipeModel.CLOSED_MASK_PROPERTY, renderMask) + .with(AbstractPipeModel.BLOCKED_MASK_PROPERTY, blockedMask) + .with(AbstractPipeModel.COLOR_PROPERTY, getPaintingColor()) + .with(AbstractPipeModel.FRAME_MATERIAL_PROPERTY, frameMaterial) + .with(AbstractPipeModel.FRAME_MASK_PROPERTY, frameMask) + .with(CoverRendererPackage.PROPERTY, getCoverHolder().createPackage()) + .build(); } public void getCoverBoxes(Consumer consumer) { @@ -672,11 +699,11 @@ public void getCoverBoxes(Consumer consumer) { } @Override - public void dealAreaDamage(int size, Consumer damageFunction) { + public void dealAreaDamage(int size, Consumer damageFunction) { long timer = getOffsetTimer(); if (timer >= this.nextDamageTime) { - List entities = getWorld().getEntitiesWithinAABB(EntityLivingBase.class, - new AxisAlignedBB(getPos()).grow(size)); + List entities = getLevel().getEntitiesOfClass(LivingEntity.class, + new AABB(getBlockPos()).inflate(size)); entities.forEach(damageFunction); this.nextDamageTime = timer + 20; } @@ -685,56 +712,31 @@ public void dealAreaDamage(int size, Consumer damageFunction) public void playLossSound() { long timer = getOffsetTimer(); if (timer >= this.nextSoundTime) { - getWorld().playSound(null, pos, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 1.0F, 1.0F); + getLevel().playSound(null, getBlockPos(), SoundEvents.LAVA_EXTINGUISH, SoundSource.BLOCKS, 1.0F, 1.0F); this.nextSoundTime = timer + 20; } } public void visuallyExplode() { - getWorld().createExplosion(null, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, - 1.0f + GTValues.RNG.nextFloat(), false); + getLevel().explode(null, getBlockPos().getX() + 0.5, getBlockPos().getY() + 0.5, getBlockPos().getZ() + 0.5, + 1.0f + GTValues.RNG.nextFloat(), Level.ExplosionInteraction.BLOCK); } public void setNeighborsToFire() { for (Direction side : GTUtil.DIRECTIONS) { if (!GTValues.RNG.nextBoolean()) continue; - BlockPos blockPos = getPos().offset(side); - BlockState blockState = getWorld().getBlockState(blockPos); - if (blockState.getBlock().isAir(blockState, getWorld(), blockPos) || - blockState.getBlock().isFlammable(getWorld(), blockPos, side.getOpposite())) { - getWorld().setBlockState(blockPos, Blocks.FIRE.getDefaultState()); + BlockPos blockPos = getBlockPos().relative(side); + BlockState blockState = getLevel().getBlockState(blockPos); + if (level.isEmptyBlock(blockPos) || + blockState.isFlammable(getLevel(), blockPos, side.getOpposite())) { + getLevel().setBlockAndUpdate(blockPos, Blocks.FIRE.defaultBlockState()); } } } @Override - public @Nullable TickableSubscription subscribeServerTick(Runnable runnable) { - if (!isRemote()) { - var subscription = new TickableSubscription(runnable); - waitingToAdd.add(subscription); - var blockState = getBlockState(); - if (!blockState.getValue(BlockProperties.SERVER_TICK)) { - if (getLevel() instanceof ServerLevel serverLevel) { - blockState = blockState.setValue(BlockProperties.SERVER_TICK, true); - setBlockState(blockState); - serverLevel.getServer().tell(new TickTask(0, () -> serverLevel.setBlockAndUpdate(getBlockPos(), - getBlockState().setValue(BlockProperties.SERVER_TICK, true)))); - } - } - return subscription; - } - return null; - } - - @Override - public void unsubscribe(@Nullable TickableSubscription current) { - if (current != null) { - current.unsubscribe(); - } - } - - @Override - public Pair<@Nullable GTToolType, InteractionResult> onToolClick(@NotNull Set toolTypes, ItemStack itemStack, UseOnContext context) { + public Pair<@Nullable GTToolType, InteractionResult> onToolClick(@NotNull Set toolTypes, + ItemStack itemStack, UseOnContext context) { return null; } @@ -749,9 +751,7 @@ public IManagedStorage getSyncStorage() { } @Override - public void onChanged() { - - } + public void onChanged() {} @Override public IManagedStorage getRootStorage() { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java index b82fc9b0d9..5fe4eb1319 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -1,38 +1,45 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; -import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; - import com.gregtechceu.gtceu.api.machine.TickableSubscription; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; +import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; +import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; +import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; +import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; +import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; +import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; +import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.item.ItemStack; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.INBTSerializable; - import net.minecraftforge.common.util.LazyOptional; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.EnumMap; -import java.util.EnumSet; -public class PipeCoverHolder implements ICoverable, INBTSerializable { +public class PipeCoverHolder implements ICoverable, IEnhancedManaged { private final PipeBlockEntity holder; + @Persisted + @DescSynced + @RequireRerender private final EnumMap covers = new EnumMap<>(Direction.class); - private final EnumSet tickingCovers = EnumSet.noneOf(Direction.class); private final int[] sidedRedstoneInput = new int[6]; public PipeCoverHolder(PipeBlockEntity holder) { @@ -42,49 +49,43 @@ public PipeCoverHolder(PipeBlockEntity holder) { protected final void addCoverSilent(@NotNull Direction side, @NotNull CoverBehavior cover) { // we checked before if the side already has a cover this.covers.put(side, cover); - if (cover instanceof ITickSubscription) { - tickingCovers.add(side); - holder.addTicker(new TickableSubscription(this::update)); - } } @Override - public final void addCover(@NotNull Direction side, @NotNull CoverBehavior cover) { - addCoverSilent(side, cover); - if (!getLevel().isClientSide) { - // do not sync or handle logic on client side - CoverSaveHandler.writeCoverPlacement(this, COVER_ATTACHED_PIPE, side, cover); - if (holder.isConnected(side) && !cover.canPipePassThrough()) { - PipeBlock.disconnectTile(holder, holder.getPipeNeighbor(side, true), side); + public final boolean acceptsCovers() { + return covers.size() < GTUtil.DIRECTIONS.length; + } + + @Override + public void setCoverAtSide(@Nullable CoverBehavior coverBehavior, Direction side) { + if (coverBehavior != null) { + addCoverSilent(side, coverBehavior); + if (!getLevel().isClientSide) { + // do not sync or handle logic on client side + coverBehavior.getSyncStorage().markAllDirty(); + if (holder.isConnected(side) && !coverBehavior.canPipePassThrough()) { + PipeBlock.disconnectTile(holder, holder.getPipeNeighbor(side, true), side); + } } - } - holder.notifyBlockUpdate(); - holder.markAsDirty(); + holder.notifyBlockUpdate(); + holder.markAsDirty(); + } } @Override - public final void removeCover(@NotNull Direction side) { - Cover cover = getCoverAtSide(side); - if (cover == null) return; - - dropCover(side); - covers.remove(side); - tickingCovers.remove(side); - if (tickingCovers.isEmpty()) holder.removeTicker(this); - writeCustomData(COVER_REMOVED_PIPE, buffer -> buffer.writeByte(side.getIndex())); + public boolean removeCover(boolean dropItself, Direction side, @Nullable Player player) { + CoverBehavior cover = getCoverAtSide(side); + if (cover == null) return ICoverable.super.removeCover(dropItself, side, player); + holder.notifyBlockUpdate(); holder.markAsDirty(); - } - - @Override - public @NotNull ItemStack getStackForm() { - return holder.getDrop(); + return ICoverable.super.removeCover(side, player); } public void onLoad() { for (Direction side : GTUtil.DIRECTIONS) { - this.sidedRedstoneInput[side.getIndex()] = GTUtility.getRedstonePower(getLevel(), getPos(), side); + this.sidedRedstoneInput[side.get3DDataValue()] = GTUtil.getRedstonePower(getLevel(), getPos(), side); } } @@ -93,16 +94,16 @@ public final int getInputRedstoneSignal(@NotNull Direction side, boolean ignoreC if (!ignoreCover && getCoverAtSide(side) != null) { return 0; // covers block input redstone signal for machine } - return sidedRedstoneInput[side.getIndex()]; + return sidedRedstoneInput[side.get3DDataValue()]; } public void updateInputRedstoneSignals() { for (Direction side : GTUtil.DIRECTIONS) { - int redstoneValue = GTUtility.getRedstonePower(getLevel(), getPos(), side); - int currentValue = sidedRedstoneInput[side.getIndex()]; + int redstoneValue = GTUtil.getRedstonePower(getLevel(), getPos(), side); + int currentValue = sidedRedstoneInput[side.get3DDataValue()]; if (redstoneValue != currentValue) { - this.sidedRedstoneInput[side.getIndex()] = redstoneValue; - Cover cover = getCoverAtSide(side); + this.sidedRedstoneInput[side.get3DDataValue()] = redstoneValue; + CoverBehavior cover = getCoverAtSide(side); if (cover != null) { cover.onRedstoneInputSignalChange(redstoneValue); } @@ -117,20 +118,17 @@ public void notifyBlockUpdate() { @Override public void scheduleRenderUpdate() { - BlockPos pos = getPos(); - getLevel().markBlockRangeForRenderUpdate( - pos.getX() - 1, pos.getY() - 1, pos.getZ() - 1, - pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1); + holder.scheduleRenderUpdate(); } @Override public void scheduleNeighborShapeUpdate() { - + holder.scheduleNeighborShapeUpdate(); } @Override public boolean canPlaceCoverOnSide(CoverDefinition definition, Direction side) { - return false; + return holder.canConnectTo(side); } @Override @@ -165,29 +163,12 @@ public IFluidTransfer getFluidTransferCap(@Nullable Direction side, boolean useC return null; } - @Override - public void setCoverAtSide(@Nullable CoverBehavior coverBehavior, Direction side) { - - } - - @Override public boolean shouldRenderCoverBackSides() { return false; } - @Override public int getPaintingColorForRendering() { - return ConfigHolder.client.defaultPaintingColor; - } - - @Override - public boolean canPlaceCoverOnSide(@NotNull Direction side) { - return holder.canConnectTo(side); - } - - @Override - public final boolean acceptsCovers() { - return covers.size() < GTUtil.DIRECTIONS.length; + return Long.decode(ConfigHolder.INSTANCE.client.defaultPaintingColor).intValue(); } public boolean canConnectRedstone(@Nullable Direction side) { @@ -219,68 +200,6 @@ public int getHighestOutputRedstoneSignal() { return highestSignal; } - @Override - public void update() { - if (!getLevel().isClientSide) { - updateCovers(); - } - } - - @Override - public void writeCoverData(@NotNull Cover cover, int discriminator, @NotNull Consumer<@NotNull PacketBuffer> buf) { - writeCustomData(UPDATE_COVER_DATA_PIPE, buffer -> { - buffer.writeByte(cover.getAttachedSide().getIndex()); - buffer.writeVarInt(discriminator); - buf.accept(buffer); - }); - } - - public void writeInitialSyncData(PacketBuffer buf) { - CoverSaveHandler.writeInitialSyncData(buf, this); - } - - public void readInitialSyncData(PacketBuffer buf) { - CoverSaveHandler.receiveInitialSyncData(buf, this); - } - - @Override - public void writeCustomData(int dataId, @NotNull Consumer writer) { - holder.writeCustomData(dataId, writer); - } - - public void readCustomData(int dataId, PacketBuffer buf) { - if (dataId == COVER_ATTACHED_PIPE) { - CoverSaveHandler.readCoverPlacement(buf, this); - } else if (dataId == COVER_REMOVED_PIPE) { - // cover removed event - Direction placementSide = GTUtil.DIRECTIONS[buf.readByte()]; - this.covers.remove(placementSide); - this.tickingCovers.remove(placementSide); - if (this.tickingCovers.isEmpty()) holder.removeTicker(this); - holder.scheduleRenderUpdate(); - } else if (dataId == UPDATE_COVER_DATA_PIPE) { - // cover custom data received - Direction coverSide = GTUtil.DIRECTIONS[buf.readByte()]; - Cover cover = getCoverAtSide(coverSide); - int internalId = buf.readVarInt(); - if (cover != null) { - cover.readCustomData(internalId, buf); - } - } - } - - @Override - public CompoundTag serializeNBT() { - CompoundTag tag = new CompoundTag(); - CoverSaveHandler.writeCoverNBT(tag, this); - return tag; - } - - @Override - public void deserializeNBT(CompoundTag nbt) { - CoverSaveHandler.readCoverNBT(nbt, this, this::addCoverSilent); - } - @Override public Level getLevel() { return holder.getLevel(); @@ -292,8 +211,8 @@ public BlockPos getPos() { } @Override - public @Nullable BlockEntity getNeighbor(@NotNull Direction facing) { - return holder.getNeighbor(facing); + public @Nullable BlockEntity getNeighbor(@NotNull Direction side) { + return holder.getNeighbor(side); } @Override @@ -332,7 +251,7 @@ public CoverRendererPackage createPackage() { if (covers.isEmpty()) return CoverRendererPackage.EMPTY; CoverRendererPackage rendererPackage = new CoverRendererPackage(shouldRenderCoverBackSides()); for (var cover : covers.entrySet()) { - rendererPackage.addRenderer(cover.getValue().getRenderer(), cover.getKey()); + rendererPackage.addRenderer(cover.getValue().getCoverRenderer(), cover.getKey()); } return rendererPackage; } @@ -346,4 +265,17 @@ public CoverRendererPackage createPackage() { public void unsubscribe(@Nullable TickableSubscription current) { holder.unsubscribe(current); } + + @Override + public ManagedFieldHolder getFieldHolder() { + return null; + } + + @Override + public IManagedStorage getSyncStorage() { + return null; + } + + @Override + public void onChanged() {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialBlockEntity.java similarity index 78% rename from src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java rename to src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialBlockEntity.java index 1e422ddfed..d26bff06ed 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialTileEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialBlockEntity.java @@ -2,19 +2,20 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; - +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.common.data.GTMaterials; +import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; + import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; 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; - import net.minecraftforge.client.model.data.ModelData; + import org.jetbrains.annotations.NotNull; public class PipeMaterialBlockEntity extends PipeBlockEntity { @@ -38,7 +39,7 @@ protected void initialize() { @Override public void placedBy(ItemStack stack, Player player) { super.placedBy(stack, player); - setMaterial(getBlockType().getMaterialForStack(stack)); + setMaterial(getBlockType().material); initialize(); } @@ -58,22 +59,16 @@ public Material getMaterial() { @Override public ItemStack getMainDrop(@NotNull BlockState state) { - return getBlockType().getItem(getMaterial()); + return new ItemStack(getBlockType().asItem(), 1); } @Override public int getDefaultPaintingColor() { - return GTUtility.convertRGBtoARGB(getMaterial().getMaterialRGB()); - } - - @Override - @OnlyIn(Dist.CLIENT) - public IExtendedBlockState getRenderInformation(IExtendedBlockState state) { - return super.getRenderInformation(state).withProperty(AbstractPipeModel.MATERIAL_PROPERTY, getMaterial()); + return GTUtil.convertRGBtoARGB(getMaterial().getMaterialRGB()); } @Override public @NotNull ModelData getModelData() { - return super.getModelData(); + return super.getModelData().derive().with(AbstractPipeModel.MATERIAL_PROPERTY, getMaterial()).build(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java index 8c8977b51e..6252567ca5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java @@ -3,11 +3,10 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; -import net.minecraft.nbt.NBTTagByte; - +import net.minecraft.nbt.ByteTag; import org.jetbrains.annotations.NotNull; -public final class BlockedPredicate extends EdgePredicate { +public final class BlockedPredicate extends EdgePredicate { public static final BlockedPredicate INSTANCE = new BlockedPredicate(); @@ -22,12 +21,12 @@ private BlockedPredicate() { } @Override - public NBTTagByte serializeNBT() { - return new NBTTagByte((byte) 0); + public ByteTag serializeNBT() { + return ByteTag.valueOf((byte) 0); } @Override - public void deserializeNBT(NBTTagByte nbt) {} + public void deserializeNBT(ByteTag nbt) {} @Override public boolean andy() { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java index 9e9e24809a..5ba7df0c6b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java @@ -2,11 +2,11 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; -import gregtech.common.covers.filter.BaseFilterContainer; -import net.minecraft.item.ItemStack; +import com.gregtechceu.gtceu.common.cover.filter.BaseFilterContainer; import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -34,20 +34,20 @@ public void setTargetFilter(@Nullable BaseFilterContainer targetFilter) { @Override public CompoundTag serializeNBT() { CompoundTag tag = new CompoundTag(); - if (sourceFilter != null) tag.setTag("Source", sourceFilter.serializeNBT()); - if (targetFilter != null) tag.setTag("Target", targetFilter.serializeNBT()); + if (sourceFilter != null) tag.put("Source", sourceFilter.serializeNBT()); + if (targetFilter != null) tag.put("Target", targetFilter.serializeNBT()); return tag; } @Override public void deserializeNBT(CompoundTag nbt) { - if (nbt.hasKey("Source")) { + if (nbt.contains("Source")) { sourceFilter = new GenericFilterContainer(); - sourceFilter.deserializeNBT(nbt.getCompoundTag("Source")); + sourceFilter.deserializeNBT(nbt.getCompound("Source")); } else sourceFilter = null; - if (nbt.hasKey("Target")) { + if (nbt.contains("Target")) { targetFilter = new GenericFilterContainer(); - targetFilter.deserializeNBT(nbt.getCompoundTag("Target")); + targetFilter.deserializeNBT(nbt.getCompound("Target")); } else targetFilter = null; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java index a7c59b7048..6531b7f172 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java @@ -1,11 +1,10 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.transfer; -import net.minecraft.util.IStringSerializable; - +import net.minecraft.util.StringRepresentable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public abstract class TransferControl implements IStringSerializable { +public abstract class TransferControl implements StringRepresentable { private final String name; @@ -14,7 +13,7 @@ public TransferControl(@NotNull String name) { } @Override - public @NotNull String getName() { + public @NotNull String getSerializedName() { return name; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java index bb4b24f1a7..5bb85a2b79 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java @@ -5,10 +5,12 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCapabilityWrapper; import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinData; -import net.minecraft.tileentity.BlockEntity; -import net.minecraft.util.Direction; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.Direction; +import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; import org.apache.commons.lang3.mutable.MutableByte; import org.jetbrains.annotations.MustBeInvokedByOverriders; import org.jetbrains.annotations.NotNull; @@ -32,12 +34,7 @@ public void resetIfFinished(WorldPipeNetNode node, @Nullable SimulatorKey simula public @NotNull MutableByte getPointer(@Nullable SimulatorKey simulator) { if (simulator == null) return pointer; - MutableByte value = simulatorMap.get(simulator); - if (value == null) { - value = new MutableByte(); - simulatorMap.put(simulator, value); - } - return value; + return simulatorMap.computeIfAbsent(simulator, k -> new MutableByte()); } public final boolean pointerFinished(@Nullable SimulatorKey simulator) { @@ -60,8 +57,8 @@ public boolean hasCapabilityAtPointer(@NotNull Capability capability, WorldPi } @Nullable - public E getCapabilityAtPointer(@NotNull Capability capability, WorldPipeNetNode node, - @Nullable SimulatorKey simulator) { + public LazyOptional getCapabilityAtPointer(@NotNull Capability capability, WorldPipeNetNode node, + @Nullable SimulatorKey simulator) { if (pointerFinished(simulator)) return null; PipeCapabilityWrapper wrapper = node.getBlockEntity().getWrapperForNode(node); Direction pointer = getPointerFacing(simulator); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java index 633732b9ef..a97ace306d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.util.StringRepresentable; @@ -14,10 +15,11 @@ import java.util.function.Predicate; /** - * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on predicates, + * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on + * predicates, * making a predicate class return two different names is a valid way to register multiple instances. */ -public final class EdgePredicateHandler implements INBTSerializable, Predicate { +public final class EdgePredicateHandler implements ITagSerializable, Predicate { private final Map> predicateSet; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java index 993bf3730b..9aa50c65e6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.predicate.test; import net.minecraft.nbt.CompoundTag; -import net.minecraftforge.fluids.Fluid; +import net.minecraft.world.level.material.Fluid; import net.minecraftforge.fluids.FluidStack; import org.jetbrains.annotations.Contract; @@ -20,7 +20,7 @@ public final class FluidTestObject implements IPredicateTestObject, Predicate { public final Item item; - public final int meta; public final CompoundTag tag; public final int stackLimit; @@ -22,29 +21,27 @@ public class ItemTestObject implements IPredicateTestObject, Predicate new") public ItemStack recombine() { - return new ItemStack(item, 1, meta, tag); + return new ItemStack(item, 1, tag); } @Contract("_ -> new") public ItemStack recombine(int amount) { assert amount <= getStackLimit() && amount > 0; - return new ItemStack(item, amount, meta, tag); + return new ItemStack(item, amount, tag); } @Override public boolean test(@NotNull ItemStack stack) { - if (this.stackLimit == stack.getMaxStackSize() && this.item == stack.getItem() && - this.meta == stack.getMetadata()) { - CompoundTag other = stack.getTagCompound(); + if (this.stackLimit == stack.getMaxStackSize() && this.item == stack.getItem()) { + CompoundTag other = stack.getTag(); return Objects.equals(this.tag, other); } return false; @@ -59,7 +56,7 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ItemTestObject that = (ItemTestObject) o; - return meta == that.meta && Objects.equals(item, that.item) && Objects.equals(tag, that.tag); + return Objects.equals(item, that.item) && Objects.equals(tag, that.tag); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java index 70f43ce973..4f167a4adb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java @@ -26,16 +26,18 @@ public abstract class ServerNet extends SavedData implements IGraphNet { protected final GraphNetBacker backer; /* - public static ServerNet get(String name, ServerLevel level, Function graphBuilder, - AlgorithmBuilder... algorithmBuilder) { - return level.getDataStorage().computeIfAbsent(tag -> new ServerNet(tag, graphBuilder, algorithmBuilder), () -> new ServerNet(graphBuilder, algorithmBuilder), name); - } - - public static ServerNet get(String name, ServerLevel level, boolean directed, AlgorithmBuilder... algorithmBuilders) { - return get(name, level, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), - algorithmBuilders); - } - */ + * public static ServerNet get(String name, ServerLevel level, Function graphBuilder, + * AlgorithmBuilder... algorithmBuilder) { + * return level.getDataStorage().computeIfAbsent(tag -> new ServerNet(tag, graphBuilder, algorithmBuilder), () -> + * new ServerNet(graphBuilder, algorithmBuilder), name); + * } + * + * public static ServerNet get(String name, ServerLevel level, boolean directed, AlgorithmBuilder... + * algorithmBuilders) { + * return get(name, level, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), + * algorithmBuilders); + * } + */ public ServerNet(Function graphBuilder, AlgorithmBuilder... algorithmBuilders) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java index 0ec9957140..356b4b094e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java @@ -2,14 +2,17 @@ import com.gregtechceu.gtceu.api.graphnet.IGraphNet; import com.gregtechceu.gtceu.api.graphnet.NetNode; -import gregtech.api.util.DimensionPos; +import net.minecraft.core.BlockPos; +import net.minecraft.core.GlobalPos; +import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.util.math.BlockPos; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; public class ServerNetNode extends NetNode { - private DimensionPos pos; + private GlobalPos pos; public ServerNetNode(IGraphNet net) { super(net); @@ -18,20 +21,20 @@ public ServerNetNode(IGraphNet net) { @Override public CompoundTag serializeNBT() { CompoundTag tag = super.serializeNBT(); - tag.setLong("Pos", pos.getPos().toLong()); - tag.setInteger("Dim", pos.getDimension()); + tag.putLong("Pos", pos.pos().asLong()); + tag.putString("Dim", pos.dimension().location().toString()); return tag; } @Override public void deserializeNBT(CompoundTag nbt) { super.deserializeNBT(nbt); - BlockPos pos = BlockPos.fromLong(nbt.getLong("Pos")); - this.pos = new DimensionPos(pos, nbt.getInteger("Dim")); + BlockPos pos = BlockPos.of(nbt.getLong("Pos")); + this.pos = GlobalPos.of(ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("Dim"))), pos); } @Override - public DimensionPos getEquivalencyData() { + public GlobalPos getEquivalencyData() { return pos; } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java index 63f2ef9222..ef6a4f7865 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java @@ -3,9 +3,8 @@ import com.gregtechceu.gtceu.api.graphnet.IGraphNet; import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; - -import net.minecraft.util.Direction; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; @FunctionalInterface public interface TraverseDataProvider, T extends IPredicateTestObject> { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java index 7d8fc8b343..8b6e9fa2f8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java @@ -5,8 +5,8 @@ import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; import com.gregtechceu.gtceu.api.graphnet.path.INetPath; import com.gregtechceu.gtceu.api.graphnet.traverse.util.FlowConsumptionStack; -import gregtech.api.util.GTUtility; +import com.gregtechceu.gtceu.utils.GTUtil; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -241,7 +241,7 @@ D extends IEqualizableTraverseData> long traverseEqualDistribution( if (totalDesired == 0) return 0; maxMult = Math.min(maxMult, flowIn / totalDesired); // scaling - long mult = GTUtility.binarySearch(0, maxMult, l -> { + long mult = GTUtil.binarySearch(0, maxMult, l -> { for (DistributorHelper helper : distributorHelperMap.values()) { if (!helper.supportsMult(l)) return false; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java index a2d4fcb6b4..5c02567f92 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -13,25 +13,23 @@ import com.gregtechceu.gtceu.api.graphnet.path.GenericGraphNetPath; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; -import lombok.Getter; -import lombok.Setter; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; import net.minecraft.world.level.Level; -import net.minecraft.world.storage.WorldSavedData; +import lombok.Getter; +import lombok.Setter; +import net.minecraft.world.level.saveddata.SavedData; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Iterator; import java.util.function.Function; -public abstract class WorldNet extends WorldSavedData implements IGraphNet, GenericGraphNetPath.Provider { +public abstract class WorldNet extends SavedData implements IGraphNet, GenericGraphNetPath.Provider { protected final GraphNetBacker backer; @Getter @@ -41,7 +39,6 @@ public abstract class WorldNet extends WorldSavedData implements IGraphNet, Gene public WorldNet(String name, @NotNull Function graphBuilder, AlgorithmBuilder... algorithmBuilders) { - super(name); this.backer = new GraphNetBacker(this, graphBuilder.apply(this), algorithmBuilders); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/network/PacketDataList.java b/src/main/java/com/gregtechceu/gtceu/api/network/PacketDataList.java new file mode 100644 index 0000000000..17dca65cf3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/network/PacketDataList.java @@ -0,0 +1,111 @@ +package com.gregtechceu.gtceu.api.network; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; + +import org.jetbrains.annotations.NotNull; + +/** + * An optimised data structure backed by two arrays. + * This is essentially equivalent to List>, but more efficient. + * {@link it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap} can not be used since it doesn't allow duplicate + * discriminators. + */ +public class PacketDataList { + + private int[] discriminators; + private byte[][] data; + private int size = 0; + + public PacketDataList() { + this.discriminators = new int[4]; + this.data = new byte[4][]; + } + + /** + * Resizes the arrays to fit the required elements. + * + * @param s minimum size + */ + private void ensureSize(int s) { + if (this.discriminators.length < s) { + int n = this.discriminators.length; + int newCapacity = Math.max(n + 2, s); // there are rarely more than 2 elements in the list + int[] temp = new int[newCapacity]; + byte[][] temp2 = new byte[newCapacity][]; + System.arraycopy(this.discriminators, 0, temp, 0, n); + System.arraycopy(this.data, 0, temp2, 0, n); + this.discriminators = temp; + this.data = temp2; + } + } + + /** + * Adds a discriminator - data pair to the list + * + * @param discriminator data id + * @param data data + */ + public void add(int discriminator, byte[] data) { + ensureSize(this.size + 1); + this.discriminators[this.size] = discriminator; + this.data[this.size] = data; + this.size++; + } + + /** + * Adds all discriminator - data pairs from another list. + * This does not check if the other list is empty or the same list. + * + * @param dataList other data list + */ + public void addAll(PacketDataList dataList) { + ensureSize(this.size + dataList.size); + System.arraycopy(dataList.discriminators, 0, this.discriminators, this.size, dataList.size); + System.arraycopy(dataList.data, 0, this.data, this.size, dataList.size); + this.size += dataList.size; + } + + /** + * @return amount of data packets + */ + public int size() { + return size; + } + + /** + * @return true if there are no data packets + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * remove all data packets + */ + public void clear() { + for (int i = 0; i < this.size; i++) { + this.data[i] = null; + } + this.size = 0; + } + + /** + * Writes all discriminator - data pairs to a nbt list. + * Also removes all data packets from this list. + * + * @return nbt list with discriminators and data + */ + @NotNull + public ListTag dumpToNbt() { + ListTag listTag = new ListTag(); + for (int i = 0; i < this.size; i++) { + CompoundTag entryTag = new CompoundTag(); + entryTag.putByteArray(Integer.toString(this.discriminators[i]), this.data[i]); + listTag.add(entryTag); + this.data[i] = null; + } + this.size = 0; + return listTag; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java new file mode 100644 index 0000000000..0ec81af238 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java @@ -0,0 +1,254 @@ +package com.gregtechceu.gtceu.client.particle; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.client.renderer.GTRenderTypes; +import com.gregtechceu.gtceu.client.util.BloomUtils; +import com.gregtechceu.gtceu.client.util.DrawUtil; +import com.gregtechceu.gtceu.client.util.EffectRenderContext; +import com.gregtechceu.gtceu.client.util.RenderBufferHelper; + +import com.lowdragmc.lowdraglib.Platform; + +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.core.BlockPos; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.VertexConsumer; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * @author brachy84 + */ +public class GTOverheatParticle extends GTParticle { + + public static final int TEMPERATURE_CUTOFF = 400; + + /** + * Source + */ + private static final int[] blackBodyColors = { + 0xFF3300, // 1000 K + 0xFF5300, // 1200 K + 0xFF6500, // 1400 K + 0xFF7300, // 1600 K + 0xFF7E00, // 1800 K + 0xFF8912, // 2000 K + 0xFF932C, // 2200 K + 0xFF9D3F, // 2400 K + 0xffa54f, // 2600 K + 0xffad5e, // 2800 K + 0xffb46b, // 3000 K + 0xffbb78, // 3200 K + 0xffc184, // 3400 K + 0xffc78f, // 3600 K + 0xffcc99, // 3800 K + 0xffd1a3, // 4000 K + 0xffd5ad, // 4200 K + 0xffd9b6, // 4400 K + 0xffddbe, // 4600 K + 0xffe1c6, // 4800 K + 0xffe4ce, // 5000 K + 0xffe8d5, // 5200 K + 0xffebdc, // 5400 K + 0xffeee3, // 5600 K + 0xfff0e9, // 5800 K + 0xfff3ef, // 6000 K + 0xfff5f5, // 6200 K + 0xfff8fb, // 6400 K + 0xfef9ff, // 6600 K + 0xf9f6ff, // 6800 K + 0xf5f3ff, // 7000 K + 0xf0f1ff, // 7200 K + 0xedefff, // 7400 K + 0xe9edff, // 7600 K + 0xe6ebff, // 7800 K + 0xe3e9ff, // 8000 K + 0xe0e7ff, // 8200 K + 0xdde6ff, // 8400 K + 0xdae4ff, // 8600 K + 0xd8e3ff, // 8800 K + 0xd6e1ff, // 9000 K + 0xd3e0ff, // 9200 K + 0xd1dfff, // 9400 K + 0xcfddff, // 9600 K + 0xcedcff, // 9800 K + 0xccdbff, // 10000 K + 0xcadaff, // 10200 K + 0xc9d9ff, // 10400 K + 0xc7d8ff, // 10600 K + 0xc6d8ff, // 10800 K + 0xc4d7ff, // 11000 K + 0xc3d6ff, // 11200 K + 0xc2d5ff, // 11400 K + 0xc1d4ff, // 11600 K + 0xc0d4ff, // 11800 K + 0xbfd3ff, // 12000 K + 0xbed2ff, // 12200 K + 0xbdd2ff, // 12400 K + 0xbcd1ff, // 12600 K + 0xbbd1ff, // 12800 K + 0xbad0ff, // 13000 K + 0xb9d0ff, // 13200 K + 0xb8cfff, // 13400 K + 0xb7cfff, // 13600 K + 0xb7ceff, // 13800 K + 0xb6ceff, // 14000 K + 0xb5cdff, // 14200 K + 0xb5cdff, // 14400 K + 0xb4ccff, // 14600 K + 0xb3ccff, // 14800 K + 0xb3ccff, // 15000 K + 0xb2cbff, // 15200 K + 0xb2cbff, // 15400 K + 0xb1caff, // 15600 K + 0xb1caff, // 15800 K + 0xb0caff, // 16000 K + 0xafc9ff, // 16200 K + 0xafc9ff, // 16400 K + 0xafc9ff, // 16600 K + 0xaec9ff, // 16800 K + 0xaec8ff, // 17000 K + 0xadc8ff, // 17200 K + 0xadc8ff, // 17400 K + 0xacc7ff, // 17600 K + 0xacc7ff, // 17800 K + 0xacc7ff, // 18000 K + 0xabc7ff, // 18200 K + 0xabc6ff, // 18400 K + 0xaac6ff, // 18600 K + 0xaac6ff, // 18800 K + 0xaac6ff, // 19000 K + 0xa9c6ff, // 19200 K + 0xa9c5ff, // 19400 K + 0xa9c5ff, // 19600 K + 0xa9c5ff, // 19800 K + 0xa8c5ff, // 20000 K + // color doesn't really change onwards + }; + + public static int getBlackBodyColor(int temperature) { + if (temperature < 1000) + return blackBodyColors[0]; + int index = (temperature - 1000) / 200; + if (index >= blackBodyColors.length - 1) + return blackBodyColors[blackBodyColors.length - 1]; + int color = blackBodyColors[index]; + return DrawUtil.interpolateColor(color, blackBodyColors[index + 1], temperature % 200 / 200f); + } + + private final PipeBlockEntity tileEntity; + private @NotNull TemperatureLogic temperatureLogic; + + protected VoxelShape pipeBoxes; + protected boolean insulated; + + protected float alpha = 0; + protected int color = blackBodyColors[0]; + + public GTOverheatParticle(@NotNull PipeBlockEntity tileEntity, @NotNull TemperatureLogic temperatureLogic, + @NotNull VoxelShape pipeBoxes, boolean insulated) { + super(tileEntity.getBlockPos().getX(), tileEntity.getBlockPos().getY(), tileEntity.getBlockPos().getZ()); + this.tileEntity = tileEntity; + this.temperatureLogic = temperatureLogic; + this.pipeBoxes = pipeBoxes; + updatePipeBoxes(pipeBoxes); + this.insulated = insulated; + } + + private int getTemperature() { + long tick = Platform.getMinecraftServer().getTickCount(); + return temperatureLogic.getTemperature(tick); + } + + public void updatePipeBoxes(@NotNull VoxelShape pipeBoxes) { + List boxes = pipeBoxes.toAabbs(); + this.pipeBoxes = boxes.stream() + .map(aabb -> aabb.inflate(0.001)) + .map(Shapes::create) + .reduce(Shapes.empty(), Shapes::or) + .optimize(); + } + + public void setTemperatureLogic(@NotNull TemperatureLogic logic) { + this.temperatureLogic = logic; + } + + @Override + public void onUpdate() { + if (tileEntity.isRemoved() || !tileEntity.isOverheatParticleAlive()) { + setExpired(); + tileEntity.killOverheatParticle(); + return; + } + int temperature = getTemperature(); + + if (temperature <= TEMPERATURE_CUTOFF || temperature > temperatureLogic.getTemperatureMaximum()) { + setExpired(); + return; + } + if (temperature < 500) { + alpha = 0f; + } else if (temperature < 1000) { + alpha = (temperature - 500f) / 500f; + alpha *= 0.8f; + } else { + alpha = 0.8f; + } + color = getBlackBodyColor(temperature); + + if (GTValues.RNG.nextFloat() < 0.04) { + spawnSmoke(); + } + } + + private void spawnSmoke() { + BlockPos pos = tileEntity.getBlockPos(); + float xPos = pos.getX() + 0.5F; + float yPos = pos.getY() + 0.9F; + float zPos = pos.getZ() + 0.5F; + + float ySpd = 0.3F + 0.1F * GTValues.RNG.nextFloat(); + tileEntity.getLevel().addParticle(ParticleTypes.LARGE_SMOKE, xPos, yPos, zPos, 0, ySpd, 0); + } + + @Override + public String toString() { + return "GTOverheatParticle{" + + "tileEntity=" + tileEntity + + ", temperatureLogic=" + temperatureLogic + + ", pipeBoxes=" + pipeBoxes + + ", insulated=" + insulated + + ", alpha=" + alpha + + ", color=" + color + + '}'; + } + + @Override + public void renderParticle(@NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) { + if (GTCEu.isShimmerLoaded()) { + BloomUtils.entityBloom(source -> renderBloomEffect(source, context)); + } + } + + public void renderBloomEffect(@NotNull MultiBufferSource source, @NotNull EffectRenderContext context) { + float red = ((color >> 16) & 0xFF) / 255f; + float green = ((color >> 8) & 0xFF) / 255f; + float blue = (color & 0xFF) / 255f; + + VertexConsumer buffer = source.getBuffer(GTRenderTypes.getBloomQuad()); + + // buffer.setTranslation(posX - context.cameraX(), posY - context.cameraY(), posZ - context.cameraZ()); + for (AABB cuboid : pipeBoxes.toAabbs()) { + RenderBufferHelper.renderCubeFace(buffer, cuboid, red, green, blue, alpha, true); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java new file mode 100644 index 0000000000..493c153174 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java @@ -0,0 +1,119 @@ +package com.gregtechceu.gtceu.client.particle; + +import com.gregtechceu.gtceu.client.renderer.IRenderSetup; +import com.gregtechceu.gtceu.client.util.EffectRenderContext; + +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import lombok.Getter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * A custom particle implementation with framework for more advanced rendering capabilities. + *

+ * GTParticle instances are managed by {@link GTParticleManager}. GTParticle instances with same {@link IRenderSetup}s + * will be drawn together as a batch. + */ +@OnlyIn(Dist.CLIENT) +public abstract class GTParticle { + + public double posX; + public double posY; + public double posZ; + + /** + * render range. If the distance between particle and render view entity exceeds this value, the particle + * will not be rendered. If render range is negative value or {@code NaN}, then the check is disabled and + * the + * particle will be rendered regardless of the distance. + */ + @Getter + private double renderRange = -1; + /** + * squared render range, or negative value if render distance check is disabled. + */ + @Getter + private double squaredRenderRange = -1; + + private boolean expired; + + protected GTParticle(double posX, double posY, double posZ) { + this.posX = posX; + this.posY = posY; + this.posZ = posZ; + } + + public boolean shouldRender(@NotNull EffectRenderContext context) { + if (squaredRenderRange < 0) return true; + return context.renderViewEntity().getEyePosition(context.partialTicks()) + .distanceToSqr(posX, posY, posZ) <= squaredRenderRange; + } + + public final boolean isAlive() { + return !expired; + } + + public final boolean isExpired() { + return expired; + } + + public final void setExpired() { + if (this.expired) return; + this.expired = true; + onExpired(); + } + + /** + * @return {@code true} to render the particle with + * {@link com.mojang.blaze3d.systems.RenderSystem#depthMask(boolean) depth mask} feature disabled; in + * other + * words, render the particle without modifying depth buffer. + */ + public boolean shouldDisableDepth() { + return false; + } + + /** + * Sets the render range. If the distance between particle and render view entity exceeds this value, the particle + * will not be rendered. If render range is negative value or {@code NaN}, then the check is disabled and the + * particle will be rendered regardless of the distance. + * + * @param renderRange Render range + */ + public final void setRenderRange(double renderRange) { + this.renderRange = renderRange; + if (renderRange >= 0) this.squaredRenderRange = renderRange * renderRange; + else this.squaredRenderRange = -1; + } + + /** + * Update the particle. This method is called each tick. + */ + public void onUpdate() {} + + /** + * Called once on expiration. + */ + protected void onExpired() {} + + /** + * Render the particle. If this particle has non-null {@link #getRenderSetup()} associated, this method will be + * called between a {@link IRenderSetup#preDraw(BufferBuilder)} call and a + * {@link IRenderSetup#postDraw(BufferBuilder)} call. + * + * @param buffer buffer builder + * @param context render context + */ + public void renderParticle(@NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) {} + + /** + * @return Render setup for this particle, if exists + */ + @Nullable + public IRenderSetup getRenderSetup() { + return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java new file mode 100644 index 0000000000..e0b3ab0adc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java @@ -0,0 +1,217 @@ +package com.gregtechceu.gtceu.client.particle; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.client.renderer.IRenderSetup; +import com.gregtechceu.gtceu.client.util.EffectRenderContext; + +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.event.CustomizeGuiOverlayEvent; +import net.minecraftforge.client.event.RenderLevelStageEvent; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; + +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.Tesselator; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +/** + * Singleton class responsible for managing, updating and rendering {@link GTParticle} instances. + */ +@OnlyIn(Dist.CLIENT) +@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = GTCEu.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE) +public class GTParticleManager { + + public static final GTParticleManager INSTANCE = new GTParticleManager(); + + @Nullable + private static Level currentWorld = null; + + private final Map<@Nullable IRenderSetup, ArrayDeque> depthEnabledParticles = new Object2ObjectLinkedOpenHashMap<>(); + private final Map<@Nullable IRenderSetup, ArrayDeque> depthDisabledParticles = new Object2ObjectLinkedOpenHashMap<>(); + + private final List newParticleQueue = new ArrayList<>(); + + public void addEffect(@NotNull GTParticle particles) { + newParticleQueue.add(particles); + } + + public void updateEffects() { + if (!depthEnabledParticles.isEmpty()) { + updateQueue(depthEnabledParticles); + } + if (!depthDisabledParticles.isEmpty()) { + updateQueue(depthDisabledParticles); + } + if (!newParticleQueue.isEmpty()) { + for (GTParticle particle : newParticleQueue) { + var queue = particle.shouldDisableDepth() ? depthDisabledParticles : depthEnabledParticles; + + ArrayDeque particles = queue.computeIfAbsent(particle.getRenderSetup(), + setup -> new ArrayDeque<>()); + + if (particles.size() > 6000) { + particles.removeFirst().setExpired(); + } + particles.add(particle); + } + newParticleQueue.clear(); + } + } + + private void updateQueue(Map> renderQueue) { + Iterator> it = renderQueue.values().iterator(); + while (it.hasNext()) { + ArrayDeque particles = it.next(); + + Iterator it2 = particles.iterator(); + while (it2.hasNext()) { + GTParticle particle = it2.next(); + if (particle.isAlive()) { + try { + particle.onUpdate(); + } catch (RuntimeException exception) { + GTCEu.LOGGER.error("particle update error: {}", particle.toString(), exception); + particle.setExpired(); + } + if (particle.isAlive()) continue; + } + it2.remove(); + } + + if (particles.isEmpty()) { + it.remove(); + } + } + } + + public void clearAllEffects(boolean cleanNewQueue) { + if (cleanNewQueue) { + for (GTParticle particle : newParticleQueue) { + particle.setExpired(); + } + newParticleQueue.clear(); + } + for (ArrayDeque particles : depthEnabledParticles.values()) { + for (GTParticle particle : particles) { + particle.setExpired(); + } + } + for (ArrayDeque particles : depthDisabledParticles.values()) { + for (GTParticle particle : particles) { + particle.setExpired(); + } + } + depthEnabledParticles.clear(); + depthDisabledParticles.clear(); + } + + public void renderParticles(@NotNull Entity renderViewEntity, float partialTicks) { + if (depthEnabledParticles.isEmpty() && depthDisabledParticles.isEmpty()) return; + + EffectRenderContext instance = EffectRenderContext.getInstance().update(renderViewEntity, partialTicks); + + RenderSystem.enableBlend(); + RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); + + if (!depthDisabledParticles.isEmpty()) { + RenderSystem.depthMask(false); + + renderGlParticlesInLayer(depthDisabledParticles, instance); + + RenderSystem.depthMask(true); + } + + renderGlParticlesInLayer(depthEnabledParticles, instance); + + RenderSystem.disableBlend(); + } + + private static void renderGlParticlesInLayer(@NotNull Map<@Nullable IRenderSetup, ArrayDeque> renderQueue, + @NotNull EffectRenderContext context) { + for (var e : renderQueue.entrySet()) { + @Nullable + IRenderSetup handler = e.getKey(); + ArrayDeque particles = e.getValue(); + if (particles.isEmpty()) continue; + + boolean initialized = false; + BufferBuilder buffer = Tesselator.getInstance().getBuilder(); + for (GTParticle particle : particles) { + if (particle.shouldRender(context)) { + try { + if (!initialized) { + initialized = true; + if (handler != null) { + handler.preDraw(buffer); + } + } + particle.renderParticle(buffer, context); + } catch (Throwable throwable) { + GTCEu.LOGGER.error("particle render error: {}", particle, throwable); + particle.setExpired(); + } + } + } + if (initialized && handler != null) { + handler.postDraw(buffer); + } + } + } + + @SubscribeEvent + public static void clientTick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END || Minecraft.getInstance().isPaused()) { + return; + } + + ClientLevel world = Minecraft.getInstance().level; + if (currentWorld != world) { + INSTANCE.clearAllEffects(currentWorld != null); + currentWorld = world; + } + + if (currentWorld != null) { + INSTANCE.updateEffects(); + } + } + + @SubscribeEvent + public static void renderWorld(RenderLevelStageEvent event) { + if (event.getStage() == RenderLevelStageEvent.Stage.AFTER_LEVEL) { + Entity entity = Minecraft.getInstance().getCameraEntity(); + INSTANCE.renderParticles(entity == null ? Minecraft.getInstance().player : entity, event.getPartialTick()); + } + } + + @SubscribeEvent + public static void debugOverlay(CustomizeGuiOverlayEvent.DebugText event) { + if (event.getLeft().size() >= 5) { + String particleTxt = event.getLeft().get(4); + particleTxt += "." + ChatFormatting.GOLD + + " PARTICLE-BACK: " + count(INSTANCE.depthEnabledParticles) + + "PARTICLE-FRONT: " + count(INSTANCE.depthDisabledParticles); + event.getLeft().set(4, particleTxt); + } + } + + private static int count(Map<@Nullable IRenderSetup, ArrayDeque> renderQueue) { + int g = 0; + for (Deque queue : renderQueue.values()) { + g += queue.size(); + } + return g; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRenderTypes.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRenderTypes.java index 0338050f0c..8392cef2b8 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRenderTypes.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRenderTypes.java @@ -17,6 +17,12 @@ public class GTRenderTypes extends RenderType { .setCullState(NO_CULL) .setShaderState(RenderStateShard.POSITION_COLOR_SHADER) .createCompositeState(false)); + private static final RenderType BLOOM_QUAD = RenderType.create("bloom_quad", + DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, false, false, + RenderType.CompositeState.builder() + .setCullState(NO_CULL) + .setShaderState(RenderStateShard.POSITION_COLOR_SHADER) + .createCompositeState(false)); private GTRenderTypes(String name, VertexFormat format, VertexFormat.Mode mode, int bufferSize, boolean affectsCrumbling, boolean sortOnUpload, Runnable setupState, Runnable clearState) { @@ -26,4 +32,8 @@ private GTRenderTypes(String name, VertexFormat format, VertexFormat.Mode mode, public static RenderType getLightRing() { return LIGHT_RING; } + + public static RenderType getBloomQuad() { + return BLOOM_QUAD; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRendererProvider.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRendererProvider.java index c70126ff93..505b60db9b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRendererProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/GTRendererProvider.java @@ -24,10 +24,7 @@ public class GTRendererProvider extends ATESRRendererProvider { private static GTRendererProvider INSTANCE; - private GTRendererProvider(BlockEntityRendererProvider.Context context) { - // ModelBellows.INSTANCE = new ModelBellows(context); - // ModelHungryChest.INSTANCE = new ModelHungryChest(context); - } + private GTRendererProvider(BlockEntityRendererProvider.Context context) {} public static GTRendererProvider getOrCreate(BlockEntityRendererProvider.Context context) { if (INSTANCE == null) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/IRenderSetup.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/IRenderSetup.java new file mode 100644 index 0000000000..895010d624 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/IRenderSetup.java @@ -0,0 +1,35 @@ +package com.gregtechceu.gtceu.client.renderer; + +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import org.jetbrains.annotations.NotNull; + +/** + *

+ * Object representation of GL setup code. Any recurring render setup / cleanup code should probably go here. + *

+ *

+ * During render, render calls with identical render setup instance will be drawn in a batch. + * Providing proper {@link Object#equals(Object) equals()} and {@link Object#hashCode() hashCode()} implementation is + * recommended for non-singleton render setup implementations. + *

+ */ +@OnlyIn(Dist.CLIENT) +public interface IRenderSetup { + + /** + * Run any pre render gl code here. + * + * @param buffer Buffer builder + */ + void preDraw(@NotNull BufferBuilder buffer); + + /** + * Run any post render gl code here. + * + * @param buffer Buffer builder + */ + void postDraw(@NotNull BufferBuilder buffer); +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java new file mode 100644 index 0000000000..9747a31b7e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -0,0 +1,212 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.ColorQuadCache; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.ChunkRenderTypeSet; +import net.minecraftforge.client.model.data.ModelData; +import net.minecraftforge.client.model.data.ModelProperty; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import lombok.Getter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public abstract class AbstractPipeModel implements BakedModel { + + public static ModelProperty THICKNESS_PROPERTY = new ModelProperty<>(); + + public static ModelProperty FRAME_MATERIAL_PROPERTY = new ModelProperty<>(); + public static ModelProperty FRAME_MASK_PROPERTY = new ModelProperty<>(); + + public static ModelProperty CLOSED_MASK_PROPERTY = new ModelProperty<>(); + public static ModelProperty BLOCKED_MASK_PROPERTY = new ModelProperty<>(); + + public static ModelProperty COLOR_PROPERTY = new ModelProperty<>(); + public static final ModelProperty MATERIAL_PROPERTY = new ModelProperty<>(); + + protected final Object2ObjectOpenHashMap frameCache = new Object2ObjectOpenHashMap<>(); + protected final Object2ObjectOpenHashMap pipeCache = new Object2ObjectOpenHashMap<>(); + + @Getter + private final ModelResourceLocation loc; + + public AbstractPipeModel(ModelResourceLocation loc) { + this.loc = loc; + } + + @Override + public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, + @NotNull RandomSource rand, @NotNull ModelData modelData, + @Nullable RenderType renderType) { + if (side == null) { + ColorData data = computeColorData(modelData); + CoverRendererPackage rendererPackage = modelData.get(CoverRendererPackage.PROPERTY); + byte coverMask = rendererPackage == null ? 0 : rendererPackage.getMask(); + List quads = getQuads(toKey(modelData), PipeBlock.readConnectionMask(state), + safeByte(modelData.get(CLOSED_MASK_PROPERTY)), safeByte(modelData.get(BLOCKED_MASK_PROPERTY)), + data, modelData.get(FRAME_MATERIAL_PROPERTY), + safeByte(modelData.get(FRAME_MASK_PROPERTY)), coverMask); + if (rendererPackage != null) renderCovers(quads, rendererPackage, rand, modelData); + return quads; + } + return Collections.emptyList(); + } + + protected void renderCovers(List quads, @NotNull CoverRendererPackage rendererPackage, + RandomSource rand, @NotNull ModelData data) { + int color = safeInt(data.get(COLOR_PROPERTY)); + if (data.get(AbstractPipeModel.MATERIAL_PROPERTY) != null) { + Material material = data.get(AbstractPipeModel.MATERIAL_PROPERTY); + if (material != null) { + int matColor = GTUtil.convertRGBtoARGB(material.getMaterialRGB()); + if (color == 0 || color == matColor) { + // unpainted + color = 0xFFFFFFFF; + } + } + } + rendererPackage.addQuads(quads, rand, new ColorData(color)); + } + + protected ColorData computeColorData(@NotNull ModelData data) { + return new ColorData(safeInt(data.get(COLOR_PROPERTY))); + } + + protected static byte safeByte(@Nullable Byte abyte) { + return abyte == null ? 0 : abyte; + } + + protected static int safeInt(@Nullable Integer integer) { + return integer == null ? 0 : integer; + } + + public @NotNull List getQuads(K key, byte connectionMask, byte closedMask, byte blockedMask, + ColorData data, + @Nullable Material frameMaterial, byte frameMask, byte coverMask) { + List quads = new ObjectArrayList<>(); + + StructureQuadCache cache = pipeCache.get(key); + if (cache == null) { + cache = constructForKey(key); + pipeCache.put(key, cache); + } + cache.addToList(quads, connectionMask, closedMask, + blockedMask, data, coverMask); + + if (frameMaterial != null) { + ResourceLocation rl = MaterialIconType.frameGt.getBlockTexturePath(frameMaterial.getMaterialIconSet(), + true); + ColorQuadCache frame = frameCache.get(rl); + if (frame == null) { + frame = new ColorQuadCache(PipeQuadHelper + .createFrame(Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(rl))); + frameCache.put(rl, frame); + } + List frameQuads = frame + .getQuads(new ColorData(GTUtil.convertRGBtoARGB(frameMaterial.getMaterialRGB()))); + for (int i = 0; i < 6; i++) { + if ((frameMask & (1 << i)) > 0) { + quads.add(frameQuads.get(i)); + } + } + } + return quads; + } + + protected abstract @NotNull K toKey(@NotNull ModelData state); + + protected final @NotNull CacheKey defaultKey(@NotNull ModelData state) { + return CacheKey.of(state.get(THICKNESS_PROPERTY)); + } + + protected abstract StructureQuadCache constructForKey(K key); + + public TextureAtlasSprite getParticleTexture(int paintColor, @Nullable Material material) { + SpriteInformation spriteInformation = getParticleSprite(material); + return spriteInformation.sprite(); + } + + @Override + public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { + return BakedModel.super.getParticleIcon(data); + } + + public abstract SpriteInformation getParticleSprite(@Nullable Material material); + + @Override + public boolean useAmbientOcclusion() { + return true; + } + + @Override + public boolean isGui3d() { + return true; + } + + @Override + public boolean isCustomRenderer() { + return false; + } + + @Nullable + protected abstract PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity); + + @Override + public @NotNull ItemOverrides getOverrides() { + return FakeItemOverrideList.INSTANCE; + } + + @Override + public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, + @NotNull ModelData data) { + return ChunkRenderTypeSet.of(RenderType.cutoutMipped()); + } + + protected static class FakeItemOverrideList extends ItemOverrides { + + public static final FakeItemOverrideList INSTANCE = new FakeItemOverrideList(); + + @Nullable + @Override + public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel level, + @Nullable LivingEntity entity, int seed) { + if (originalModel instanceof AbstractPipeModel model) { + PipeItemModel item = model.getItemModel(stack, level, entity); + if (item != null) return item; + } + return originalModel; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java new file mode 100644 index 0000000000..dd154830e6 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -0,0 +1,124 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.ActivableSQC; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ActivableCacheKey; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.config.ConfigHolder; +import com.lowdragmc.lowdraglib.client.bakedpipeline.Quad; +import com.lowdragmc.lowdraglib.client.utils.RenderUtils; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelProperty; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +@OnlyIn(Dist.CLIENT) +public class ActivablePipeModel extends AbstractPipeModel { + + private static final ResourceLocation loc = GTCEu.id("block/pipe_activable"); + + public static final ModelProperty ACTIVE_PROPERTY = new ModelProperty<>(); + + public static final ActivablePipeModel OPTICAL = new ActivablePipeModel(Textures.OPTICAL_PIPE_IN, + Textures.OPTICAL_PIPE_SIDE, Textures.OPTICAL_PIPE_SIDE_OVERLAY, Textures.OPTICAL_PIPE_SIDE_OVERLAY_ACTIVE, + false, "optical"); + public static final ActivablePipeModel LASER = new ActivablePipeModel(Textures.LASER_PIPE_IN, + Textures.LASER_PIPE_SIDE, Textures.LASER_PIPE_OVERLAY, Textures.LASER_PIPE_OVERLAY_EMISSIVE, + true, "laser"); + + private final Supplier inTex; + private final Supplier sideTex; + private final Supplier overlayTex; + private final Supplier overlayActiveTex; + + private final boolean emissiveActive; + + public ActivablePipeModel(@NotNull Supplier inTex, @NotNull Supplier sideTex, + @NotNull Supplier overlayTex, + @NotNull Supplier overlayActiveTex, boolean emissiveActive, + String variant) { + super(new ModelResourceLocation(loc, variant)); + this.inTex = inTex; + this.sideTex = sideTex; + this.overlayTex = overlayTex; + this.overlayActiveTex = overlayActiveTex; + this.emissiveActive = emissiveActive; + } + + @Override + public @NotNull List getQuads(ActivableCacheKey key, byte connectionMask, byte closedMask, + byte blockedMask, ColorData data, @Nullable Material frameMaterial, + byte frameMask, byte coverMask) { + // don't render the main shape to the bloom layer + List quads = super.getQuads(key, connectionMask, closedMask, blockedMask, data, frameMaterial, frameMask, coverMask); + + if (key.isActive() && allowActive()) { + if (emissiveActive) { + ((ActivableSQC) pipeCache.get(key)).addOverlay(quads, connectionMask, data, true); + // TODO bake this into the original quads + quads = quads.stream() + .map(quad -> Quad.from(quad).setLight(15, 15).rebake()) + .collect(Collectors.toList()); + } + ((ActivableSQC) pipeCache.get(key)).addOverlay(quads, connectionMask, data, true); + } else { + ((ActivableSQC) pipeCache.get(key)).addOverlay(quads, connectionMask, data, false); + } + return quads; + } + + @Override + public SpriteInformation getParticleSprite(@Nullable Material material) { + return sideTex.get(); + } + + @Override + public @NotNull TextureAtlasSprite getParticleTexture() { + return getParticleSprite(null).sprite(); + } + + @Override + protected StructureQuadCache constructForKey(ActivableCacheKey key) { + return ActivableSQC.create(PipeQuadHelper.create(key.getThickness()), inTex.get(), sideTex.get(), + overlayTex.get(), overlayActiveTex.get()); + } + + public boolean allowActive() { + return !ConfigHolder.INSTANCE.client.preventAnimatedCables; + } + + @Override + protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity) { + PipeBlock block = PipeBlock.getBlockFromItem(stack); + if (block == null) return null; + return new PipeItemModel<>(this, new ActivableCacheKey(block.getStructure().getRenderThickness(), false), + new ColorData(PipeBlockEntity.DEFAULT_COLOR)); + } + + public static void registerModels(BiConsumer registry) { + registry.accept(OPTICAL.getLoc(), OPTICAL); + registry.accept(LASER.getLoc(), LASER); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java new file mode 100644 index 0000000000..200a77d696 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java @@ -0,0 +1,146 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.level.block.state.BlockState; + +import com.mojang.blaze3d.vertex.PoseStack; +import org.jetbrains.annotations.NotNull; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.Nullable; + +public class PipeItemModel implements BakedModel { + + private static final Map CAMERA_TRANSFORMS = new HashMap<>(); + + static { + CAMERA_TRANSFORMS.put(ItemDisplayContext.NONE, mul(null, null, null, null)); + CAMERA_TRANSFORMS.put(ItemDisplayContext.GUI, mul(null, rotDegrees(30, -45, 0), scale(0.625f), null)); + CAMERA_TRANSFORMS.put(ItemDisplayContext.GROUND, mul(null, null, scale(0.25f), null)); + CAMERA_TRANSFORMS.put(ItemDisplayContext.FIXED, mul(null, rotDegrees(0, 90, 0), scale(0.5f), null)); + Matrix4f matrix4f = mul(null, rotDegrees(75, 45, 0), scale(0.375f), null); + CAMERA_TRANSFORMS.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, matrix4f); + CAMERA_TRANSFORMS.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, matrix4f); + matrix4f = mul(null, rotDegrees(0, 45, 0), scale(0.4f), null); + CAMERA_TRANSFORMS.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, matrix4f); + CAMERA_TRANSFORMS.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, matrix4f); + } + + private static Vector3f scale(float scale) { + return new Vector3f(scale, scale, scale); + } + + private static Quaternionf rotDegrees(float x, float y, float z) { + return quatFromXYZDegrees(new Vector3f(x, y, z)); + } + + private final AbstractPipeModel basis; + private final K key; + private final ColorData data; + + public PipeItemModel(AbstractPipeModel basis, K key, ColorData data) { + this.basis = basis; + this.key = key; + this.data = data; + } + + @Override + public @NotNull List getQuads(BlockState state, Direction side, RandomSource rand) { + byte z = 0; + return basis.getQuads(key, (byte) 0b1100, z, z, data, null, z, z); + } + + @Override + public boolean useAmbientOcclusion() { + return basis.useAmbientOcclusion(); + } + + @Override + public boolean isGui3d() { + return basis.isGui3d(); + } + + @Override + public boolean usesBlockLight() { + return basis.usesBlockLight(); + } + + @Override + public boolean isCustomRenderer() { + return false; + } + + @Override + public BakedModel applyTransform(ItemDisplayContext transformType, PoseStack poseStack, + boolean applyLeftHandTransform) { + poseStack.mulPoseMatrix(CAMERA_TRANSFORMS.get(transformType)); + return BakedModel.super.applyTransform(transformType, poseStack, applyLeftHandTransform); + } + + @Override + public TextureAtlasSprite getParticleIcon() { + return basis.getParticleIcon(); + } + + @Override + public ItemOverrides getOverrides() { + return ItemOverrides.EMPTY; + } + + public static Matrix4f mul(@Nullable Vector3f translation, @Nullable Quaternionf leftRot, @Nullable Vector3f scale, + @Nullable Quaternionf rightRot) { + Matrix4f res = new Matrix4f(), t = new Matrix4f(); + res.identity(); + if (leftRot != null) { + t.set(leftRot); + res.mul(t); + } + if (scale != null) { + t.identity(); + t.m00(scale.x); + t.m11(scale.y); + t.m22(scale.z); + res.mul(t); + } + if (rightRot != null) { + t.set(rightRot); + res.mul(t); + } + if (translation != null) res.setTranslation(translation); + return res; + } + + public static Quaternionf quatFromXYZDegrees(Vector3f xyz) { + return quatFromXYZ((float) Math.toRadians(xyz.x), (float) Math.toRadians(xyz.y), (float) Math.toRadians(xyz.z)); + } + + public static Quaternionf quatFromXYZ(Vector3f xyz) { + return quatFromXYZ(xyz.x, xyz.y, xyz.z); + } + + public static Quaternionf quatFromXYZ(float x, float y, float z) { + Quaternionf ret = new Quaternionf(0, 0, 0, 1), t = new Quaternionf(); + t.set((float) Math.sin(x / 2), 0, 0, (float) Math.cos(x / 2)); + ret.mul(t); + t.set(0, (float) Math.sin(y / 2), 0, (float) Math.cos(y / 2)); + ret.mul(t); + t.set(0, 0, (float) Math.sin(z / 2), (float) Math.cos(z / 2)); + ret.mul(t); + return ret; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java new file mode 100644 index 0000000000..024bd3b738 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java @@ -0,0 +1,84 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cache; + +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import org.jetbrains.annotations.NotNull; + +import java.util.EnumMap; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public class ActivableSQC extends StructureQuadCache { + + protected final EnumMap overlayCoords = new EnumMap<>(Direction.class); + protected final EnumMap overlayActiveCoords = new EnumMap<>(Direction.class); + + protected final SpriteInformation overlayTex; + protected final SpriteInformation overlayActiveTex; + + protected ActivableSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteInformation sideTex, + SpriteInformation overlayTex, SpriteInformation overlayActiveTex) { + super(helper, endTex, sideTex); + this.overlayTex = overlayTex; + this.overlayActiveTex = overlayActiveTex; + if (helper.getLayerCount() < 2) throw new IllegalStateException( + "Cannot create an ActivableSQC without 2 or more layers present on the helper!"); + } + + public static @NotNull ActivableSQC create(PipeQuadHelper helper, SpriteInformation endTex, + SpriteInformation sideTex, SpriteInformation overlayTex, + SpriteInformation overlayActiveTex) { + helper.initialize((facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_1)); + ActivableSQC cache = new ActivableSQC(helper, endTex, sideTex, overlayTex, overlayActiveTex); + cache.buildPrototype(); + return cache; + } + + @Override + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); + buildOverlay(quads); + buildOverlayActive(quads); + return quads; + } + + protected void buildOverlay(List list) { + helper.setTargetSprite(overlayTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.addAll(helper.visitTube(facing, 1)); + overlayCoords.put(facing, new SubListAddress(start, list.size())); + } + } + + protected void buildOverlayActive(List list) { + helper.setTargetSprite(overlayActiveTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.addAll(helper.visitTube(facing, 1)); + overlayActiveCoords.put(facing, new SubListAddress(start, list.size())); + } + } + + public void addOverlay(List list, byte overlayMask, ColorData data, boolean active) { + List quads = cache.getQuads(data); + for (Direction facing : GTUtil.DIRECTIONS) { + if (GTUtil.evalMask(facing, overlayMask)) { + if (active) { + list.addAll(overlayActiveCoords.get(facing).getSublist(quads)); + } else { + list.addAll(overlayCoords.get(facing).getSublist(quads)); + } + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java new file mode 100644 index 0000000000..be595792f4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java @@ -0,0 +1,42 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cache; + +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public final class ColorQuadCache { + + // TODO dynamic cache growth & collapse + private static final int CACHE_LIMIT = 20; + + private final List prototypes; + + private final Object2ObjectLinkedOpenHashMap> cache; + + public ColorQuadCache(List prototypes) { + this.prototypes = prototypes; + this.cache = new Object2ObjectLinkedOpenHashMap<>(); + } + + public List getQuads(ColorData data) { + List existing = cache.getAndMoveToFirst(data); + if (existing == null) { + existing = new ObjectArrayList<>(); + for (RecolorableBakedQuad quad : prototypes) { + existing.add(quad.withColor(data)); + } + cache.put(data, existing); + if (cache.size() > CACHE_LIMIT) cache.removeLast(); + } + return existing; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java new file mode 100644 index 0000000000..b1c89b646b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java @@ -0,0 +1,121 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cache; + +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.NotNull; + +import java.util.EnumMap; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public class StructureQuadCache { + + public static final float OVERLAY_DIST_1 = 0.003f; + public static final float OVERLAY_DIST_2 = 0.006f; + + protected final PipeQuadHelper helper; + + protected ColorQuadCache cache; + + protected final EnumMap tubeCoords = new EnumMap<>(Direction.class); + + protected final EnumMap coreCoords = new EnumMap<>(Direction.class); + protected final EnumMap capperCoords = new EnumMap<>(Direction.class); + protected final EnumMap capperClosedCoords = new EnumMap<>(Direction.class); + + protected final SpriteInformation endTex; + protected final SpriteInformation sideTex; + + protected StructureQuadCache(PipeQuadHelper helper, SpriteInformation endTex, SpriteInformation sideTex) { + this.helper = helper; + this.endTex = endTex; + this.sideTex = sideTex; + if (helper.getLayerCount() < 1) + throw new IllegalStateException("Cannot create an SQC without at least one layer present on the helper!"); + } + + public static @NotNull StructureQuadCache create(PipeQuadHelper helper, SpriteInformation endTex, + SpriteInformation sideTex) { + StructureQuadCache cache = new StructureQuadCache(helper.initialize(), endTex, sideTex); + cache.buildPrototype(); + return cache; + } + + protected void buildPrototype() { + this.cache = new ColorQuadCache(this.buildPrototypeInternal()); + } + + protected List buildPrototypeInternal() { + List quads = new ObjectArrayList<>(); + buildTube(quads); + buildCore(quads); + buildCapper(quads); + buildCapperClosed(quads); + return quads; + } + + protected void buildTube(List list) { + helper.setTargetSprite(sideTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.addAll(helper.visitTube(facing)); + tubeCoords.put(facing, new SubListAddress(start, list.size())); + } + } + + protected void buildCore(List list) { + helper.setTargetSprite(sideTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.add(helper.visitCore(facing)); + coreCoords.put(facing, new SubListAddress(start, start + 1)); + } + } + + protected void buildCapper(List list) { + helper.setTargetSprite(endTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.add(helper.visitCapper(facing)); + capperCoords.put(facing, new SubListAddress(start, start + 1)); + } + } + + protected void buildCapperClosed(List list) { + helper.setTargetSprite(sideTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.add(helper.visitCapper(facing)); + capperClosedCoords.put(facing, new SubListAddress(start, start + 1)); + } + } + + public void addToList(List list, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, + byte coverMask) { + List quads = cache.getQuads(data); + for (Direction facing : GTUtil.DIRECTIONS) { + if (GTUtil.evalMask(facing, connectionMask)) { + list.addAll(tubeCoords.get(facing).getSublist(quads)); + if (!GTUtil.evalMask(facing, coverMask)) { + if (GTUtil.evalMask(facing, closedMask)) { + list.addAll(capperClosedCoords.get(facing).getSublist(quads)); + } else { + list.addAll(capperCoords.get(facing).getSublist(quads)); + } + } + } else { + list.addAll(coreCoords.get(facing).getSublist(quads)); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/SubListAddress.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/SubListAddress.java new file mode 100644 index 0000000000..9241556796 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/SubListAddress.java @@ -0,0 +1,12 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cache; + +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public record SubListAddress(int startInclusive, int endExclusive) { + + public @NotNull List getSublist(@NotNull List list) { + return list.subList(startInclusive, endExclusive); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java new file mode 100644 index 0000000000..a564027989 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java @@ -0,0 +1,21 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cover; + +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import java.util.EnumSet; +import java.util.List; + +@FunctionalInterface +@OnlyIn(Dist.CLIENT) +public interface CoverRenderer { + + void addQuads(List quads, Direction side, RandomSource rand, EnumSet renderPlate, + boolean renderBackside, + ColorData data); +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java new file mode 100644 index 0000000000..e2877423a8 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java @@ -0,0 +1,157 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cover; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.ColorQuadCache; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.SubListAddress; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.UVMapper; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; +import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.world.phys.shapes.VoxelShape; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public class CoverRendererBuilder { + + private static final float OVERLAY_DIST_1 = 0.003f; + private static final float OVERLAY_DIST_2 = 0.006f; + + private static final ColorQuadCache PLATE_QUADS; + private static final EnumMap PLATE_COORDS = new EnumMap<>(Direction.class); + + public static final EnumMap PLATE_AABBS = new EnumMap<>(Direction.class); + private static final EnumMap> PLATE_BOXES = new EnumMap<>(Direction.class); + private static final EnumMap> OVERLAY_BOXES_1 = new EnumMap<>( + Direction.class); + private static final EnumMap> OVERLAY_BOXES_2 = new EnumMap<>( + Direction.class); + + private static final UVMapper defaultMapper = UVMapper.standard(0); + + static { + for (Direction facing : GTUtil.DIRECTIONS) { + PLATE_AABBS.put(facing, ICoverable.getCoverPlateBox(facing, 1d / 16)); + } + for (var value : PLATE_AABBS.entrySet()) { + // make sure that plates render slightly below any normal block quad + // TODO replace .bounds() calls with actual VoxelShape support + PLATE_BOXES.put(value.getKey(), + QuadHelper.fullOverlay(value.getKey(), value.getValue().bounds(), -OVERLAY_DIST_1)); + OVERLAY_BOXES_1.put(value.getKey(), + QuadHelper.fullOverlay(value.getKey(), value.getValue().bounds(), OVERLAY_DIST_1)); + OVERLAY_BOXES_2.put(value.getKey(), + QuadHelper.fullOverlay(value.getKey(), value.getValue().bounds(), OVERLAY_DIST_2)); + } + PLATE_QUADS = buildPlates(new SpriteInformation(defaultPlateSprite(), 0)); + } + + private static @NotNull TextureAtlasSprite defaultPlateSprite() { + return Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS) + .apply(GTCEu.id("block/casings/voltage/lv/side")); + } + + public static ColorQuadCache buildPlates(SpriteInformation sprite) { + List quads = new ObjectArrayList<>(); + UVMapper mapper = UVMapper.standard(0); + for (Direction facing : GTUtil.DIRECTIONS) { + PLATE_COORDS.put(facing, buildPlates(quads, facing, mapper, sprite)); + } + return new ColorQuadCache(quads); + } + + protected static SubListAddress buildPlates(List quads, Direction facing, + UVMapper mapper, SpriteInformation sprite) { + int start = quads.size(); + Pair box = PLATE_BOXES.get(facing); + for (Direction dir : Direction.values()) { + quads.add(QuadHelper.buildQuad(dir, box, mapper, sprite, DefaultVertexFormat.BLOCK)); + } + return new SubListAddress(start, quads.size()); + } + + protected static void addPlates(List quads, List plateQuads, EnumSet plates) { + for (Direction facing : plates) { + quads.add(plateQuads.get(facing.ordinal())); + } + } + + protected final TextureAtlasSprite sprite; + protected final TextureAtlasSprite spriteEmissive; + + protected UVMapper mapper = defaultMapper; + protected UVMapper mapperEmissive = defaultMapper; + + protected ColorQuadCache plateQuads = PLATE_QUADS; + + public CoverRendererBuilder(@NotNull TextureAtlasSprite sprite, @Nullable TextureAtlasSprite spriteEmissive) { + this.sprite = sprite; + this.spriteEmissive = spriteEmissive; + } + + public CoverRendererBuilder setMapper(@NotNull UVMapper mapper) { + this.mapper = mapper; + return this; + } + + public CoverRendererBuilder setMapperEmissive(@NotNull UVMapper mapperEmissive) { + this.mapperEmissive = mapperEmissive; + return this; + } + + public CoverRendererBuilder setPlateQuads(ColorQuadCache cache) { + this.plateQuads = cache; + return this; + } + + protected static List getPlates(Direction facing, ColorData data, ColorQuadCache plateQuads) { + return PLATE_COORDS.get(facing).getSublist(plateQuads.getQuads(data)); + } + + public CoverRenderer build() { + EnumMap> spriteQuads = new EnumMap<>(Direction.class); + EnumMap> spriteEmissiveQuads = spriteEmissive != null ? + new EnumMap<>(Direction.class) : null; + for (Direction facing : GTUtil.DIRECTIONS) { + spriteQuads.put(facing, ImmutablePair.of( + QuadHelper.buildQuad(facing, OVERLAY_BOXES_1.get(facing), mapper, sprite), + QuadHelper.buildQuad(facing.getOpposite(), OVERLAY_BOXES_1.get(facing), mapper, sprite))); + if (spriteEmissive != null) spriteEmissiveQuads.put(facing, ImmutablePair.of( + QuadHelper.buildQuad(facing, OVERLAY_BOXES_2.get(facing), mapperEmissive, spriteEmissive), + QuadHelper.buildQuad(facing.getOpposite(), OVERLAY_BOXES_2.get(facing), mapperEmissive, + spriteEmissive))); + } + + return (quads, side, rand, renderPlate, renderBackside, data) -> { + addPlates(quads, getPlates(side, data, plateQuads), renderPlate); + quads.add(spriteQuads.get(side).getLeft()); + if (renderBackside) quads.add(spriteQuads.get(side).getRight()); + + if (spriteEmissiveQuads != null) { + quads.add(spriteEmissiveQuads.get(side).getLeft()); + if (renderBackside) quads.add(spriteEmissiveQuads.get(side).getRight()); + } + }; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java new file mode 100644 index 0000000000..2c33b52716 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java @@ -0,0 +1,56 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cover; + +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelProperty; + +import org.jetbrains.annotations.NotNull; + +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public final class CoverRendererPackage { + + public static final ModelProperty PROPERTY = new ModelProperty<>(); + + public static final CoverRendererPackage EMPTY = new CoverRendererPackage(false); + + private final EnumMap renderers = new EnumMap<>(Direction.class); + private final EnumSet plates = EnumSet.allOf(Direction.class); + + private final boolean renderBackside; + + public CoverRendererPackage(boolean renderBackside) { + this.renderBackside = renderBackside; + } + + public void addRenderer(CoverRenderer renderer, @NotNull Direction facing) { + renderers.put(facing, renderer); + plates.remove(facing); + } + + public void addQuads(List quads, RandomSource rand, ColorData data) { + for (var renderer : renderers.entrySet()) { + EnumSet plates = EnumSet.copyOf(this.plates); + // force front and back plates to render + plates.add(renderer.getKey()); + plates.add(renderer.getKey().getOpposite()); + renderer.getValue().addQuads(quads, renderer.getKey(), rand, plates, renderBackside, data); + } + } + + public byte getMask() { + byte mask = 0; + for (Direction facing : renderers.keySet()) { + mask |= 1 << facing.ordinal(); + } + return mask; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/OverlayLayerDefinition.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/OverlayLayerDefinition.java new file mode 100644 index 0000000000..34581b01c2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/OverlayLayerDefinition.java @@ -0,0 +1,17 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.quad; + +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +@FunctionalInterface +@OnlyIn(Dist.CLIENT) +public interface OverlayLayerDefinition { + + ImmutablePair computeBox(@Nullable Direction facing, float x1, float y1, float z1, float x2, + float y2, float z2); +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java new file mode 100644 index 0000000000..f4e3a5e288 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -0,0 +1,151 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.quad; + +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.Contract; +import org.joml.Vector3f; + +import java.util.EnumMap; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public final class PipeQuadHelper { + + private SpriteInformation targetSprite; + + private final List> coreBoxList = new ObjectArrayList<>(); + private final List>> sideBoxesList = new ObjectArrayList<>(); + + private float[] definition; + + public PipeQuadHelper(float x, float y, float z, float small, float large) { + float xS = (x + small) * 16; + float xL = (x + large) * 16; + float yS = (y + small) * 16; + float yL = (y + large) * 16; + float zS = (z + small) * 16; + float zL = (z + large) * 16; + definition = new float[] { xS, xL, yS, yL, zS, zL }; + } + + @Contract("_ -> this") + public PipeQuadHelper initialize(OverlayLayerDefinition... overlayLayers) { + if (definition != null) { + float xS = definition[0]; + float xL = definition[1]; + float yS = definition[2]; + float yL = definition[3]; + float zS = definition[4]; + float zL = definition[5]; + definition = null; + generateBox(xS, xL, yS, yL, zS, zL, + (facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.toPair(x1, y1, z1, x2, y2, z2)); + for (OverlayLayerDefinition definition : overlayLayers) { + generateBox(xS, xL, yS, yL, zS, zL, definition); + } + } + return this; + } + + public int getLayerCount() { + return coreBoxList.size(); + } + + private void generateBox(float xS, float xL, float yS, float yL, float zS, float zL, + OverlayLayerDefinition definition) { + coreBoxList.add(definition.computeBox(null, xS, yS, zS, xL, yL, zL)); + EnumMap> sideBoxes = new EnumMap<>(Direction.class); + sideBoxes.put(Direction.DOWN, definition.computeBox(Direction.DOWN, xS, 0, zS, xL, yS, zL)); + sideBoxes.put(Direction.UP, definition.computeBox(Direction.UP, xS, yL, zS, xL, 16, zL)); + sideBoxes.put(Direction.NORTH, definition.computeBox(Direction.NORTH, xS, yS, 0, xL, yL, zS)); + sideBoxes.put(Direction.SOUTH, definition.computeBox(Direction.SOUTH, xS, yS, zL, xL, yL, 16)); + sideBoxes.put(Direction.WEST, definition.computeBox(Direction.WEST, 0, yS, zS, xS, yL, zL)); + sideBoxes.put(Direction.EAST, definition.computeBox(Direction.EAST, xL, yS, zS, 16, yL, zL)); + sideBoxesList.add(sideBoxes); + } + + public static PipeQuadHelper create(float thickness, double x, double y, double z) { + float small = 0.5f - thickness / 2; + float large = 0.5f + thickness / 2; + return new PipeQuadHelper((float) x, (float) y, (float) z, small, large); + } + + public static PipeQuadHelper create(float thickness) { + return create(thickness, 0, 0, 0); + } + + public void setTargetSprite(SpriteInformation sprite) { + this.targetSprite = sprite; + } + + public RecolorableBakedQuad visitCore(Direction facing) { + return visitCore(facing, 0); + } + + public RecolorableBakedQuad visitCore(Direction facing, int overlayLayer) { + return visitQuad(facing, coreBoxList.get(overlayLayer), UVMapper.standard(0)); + } + + public List visitTube(Direction facing) { + return visitTube(facing, 0); + } + + public List visitTube(Direction facing, int overlayLayer) { + List list = new ObjectArrayList<>(); + Pair box = sideBoxesList.get(overlayLayer).get(facing); + switch (facing.getAxis()) { + case X -> { + UVMapper mapper = UVMapper.standard(0); + list.add(visitQuad(Direction.UP, box, mapper)); + list.add(visitQuad(Direction.DOWN, box, mapper)); + list.add(visitQuad(Direction.SOUTH, box, mapper)); + list.add(visitQuad(Direction.NORTH, box, UVMapper.standard(180))); + } + case Y -> { + UVMapper mapper = UVMapper.standard(0); + list.add(visitQuad(Direction.EAST, box, UVMapper.standard(270))); + list.add(visitQuad(Direction.WEST, box, UVMapper.standard(270))); + list.add(visitQuad(Direction.SOUTH, box, mapper)); + list.add(visitQuad(Direction.NORTH, box, mapper)); + } + case Z -> { + list.add(visitQuad(Direction.UP, box, UVMapper.standard(180))); + list.add(visitQuad(Direction.DOWN, box, UVMapper.standard(0))); + list.add(visitQuad(Direction.EAST, box, UVMapper.standard(270))); + list.add(visitQuad(Direction.WEST, box, UVMapper.standard(90))); + } + } + return list; + } + + public RecolorableBakedQuad visitCapper(Direction facing) { + return visitCapper(facing, 0); + } + + public RecolorableBakedQuad visitCapper(Direction facing, int overlayLayer) { + return visitQuad(facing, sideBoxesList.get(overlayLayer).get(facing), UVMapper.standard(0)); + } + + public RecolorableBakedQuad visitQuad(Direction normal, Pair box, UVMapper uv) { + return QuadHelper.buildQuad(normal, box, uv, targetSprite, DefaultVertexFormat.BLOCK); + } + + public static List createFrame(TextureAtlasSprite sprite) { + PipeQuadHelper helper = PipeQuadHelper.create(0.998f).initialize(); + helper.setTargetSprite(new SpriteInformation(sprite, 0)); + List list = new ObjectArrayList<>(); + for (Direction facing : GTUtil.DIRECTIONS) { + list.add(helper.visitCore(facing)); + } + return list; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java new file mode 100644 index 0000000000..33b5bebd71 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -0,0 +1,211 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.quad; + +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.client.util.StaticFaceBakery; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.BlockElementFace; +import net.minecraft.client.renderer.block.model.FaceBakery; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BlockModelRotation; +import net.minecraft.core.Direction; +import net.minecraft.world.phys.AABB; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexFormatElement; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +@OnlyIn(Dist.CLIENT) +public final class QuadHelper { + + private static final FaceBakery BAKERY = new FaceBakery(); + + private QuadHelper() {} + + public static RecolorableBakedQuad buildQuad(Direction normal, Pair box, + UVMapper uv, SpriteInformation targetSprite, + VertexFormat format) { + BlockElementFace face = new BlockElementFace(null, -1, targetSprite.sprite().contents().name().toString(), + uv.map(normal, box)); + BakedQuad quad = StaticFaceBakery.bakeQuad(box.getLeft(), box.getRight(), face, targetSprite.sprite(), normal, + BlockModelRotation.X0_Y0, null, false, 15); + RecolorableBakedQuad.Builder builder = new RecolorableBakedQuad.Builder(format); + builder.setTexture(targetSprite); + putBakedQuad(builder, quad); + return builder.build(); + } + + public static BakedQuad buildQuad(Direction normal, Pair box, + UVMapper uv, TextureAtlasSprite targetSprite) { + BlockElementFace face = new BlockElementFace(null, -1, targetSprite.contents().name().toString(), + uv.map(normal, box)); + return StaticFaceBakery.bakeQuad(box.getLeft(), box.getRight(), face, targetSprite, normal, + BlockModelRotation.X0_Y0, + null, false, 15); + } + + @Contract("_ -> new") + public static @NotNull ImmutablePair toPair(@NotNull AABB bb) { + return ImmutablePair.of(new Vector3f((float) bb.minX * 16, (float) bb.minY * 16, (float) bb.minZ * 16), + new Vector3f((float) bb.maxX * 16, (float) bb.maxY * 16, (float) bb.maxZ * 16)); + } + + @Contract("_, _, _, _, _, _ -> new") + public static @NotNull ImmutablePair toPair(float x1, float y1, float z1, float x2, float y2, + float z2) { + return ImmutablePair.of(new Vector3f(x1, y1, z1), new Vector3f(x2, y2, z2)); + } + + @Contract("_, _, _ -> new") + public static @NotNull ImmutablePair capOverlay(@Nullable Direction facing, + @NotNull AABB bb, float g) { + return capOverlay(facing, (float) bb.minX * 16, (float) bb.minY * 16, (float) bb.minZ * 16, + (float) bb.maxX * 16, (float) bb.maxY * 16, + (float) bb.maxZ * 16, g); + } + + @Contract("_, _, _, _, _, _, _, _ -> new") + public static @NotNull ImmutablePair capOverlay(@Nullable Direction facing, float x1, float y1, + float z1, float x2, float y2, float z2, + float g) { + if (facing == null) return toPair(x1 - g, y1 - g, z1 - g, x2 + g, y2 + g, z2 + g); + return switch (facing.getAxis()) { + case X -> toPair(x1 - g, y1, z1, x2 + g, y2, z2); + case Y -> toPair(x1, y1 - g, z1, x2, y2 + g, z2); + case Z -> toPair(x1, y1, z1 - g, x2, y2, z2 + g); + }; + } + + @Contract("_, _, _ -> new") + public static @NotNull ImmutablePair tubeOverlay(@Nullable Direction facing, + @NotNull AABB bb, float g) { + return tubeOverlay(facing, (float) bb.minX * 16, (float) bb.minY * 16, (float) bb.minZ * 16, + (float) bb.maxX * 16, (float) bb.maxY * 16, + (float) bb.maxZ * 16, g); + } + + @Contract("_, _, _, _, _, _, _, _ -> new") + public static @NotNull ImmutablePair tubeOverlay(@Nullable Direction facing, float x1, + float y1, float z1, float x2, float y2, + float z2, float g) { + if (facing == null) return toPair(x1, y1, z1, x2, y2, z2); + return switch (facing.getAxis()) { + case X -> toPair(x1, y1 - g, z1 - g, x2, y2 + g, z2 + g); + case Y -> toPair(x1 - g, y1, z1 - g, x2 + g, y2, z2 + g); + case Z -> toPair(x1 - g, y1 - g, z1, x2 + g, y2 + g, z2); + }; + } + + @Contract("_, _, _ -> new") + public static @NotNull ImmutablePair fullOverlay(@Nullable Direction facing, + @NotNull AABB bb, float g) { + return fullOverlay(facing, (float) bb.minX * 16, (float) bb.minY * 16, (float) bb.minZ * 16, + (float) bb.maxX * 16, (float) bb.maxY * 16, + (float) bb.maxZ * 16, g); + } + + @Contract("_, _, _, _, _, _, _, _ -> new") + public static @NotNull ImmutablePair fullOverlay(@Nullable Direction facing, float x1, + float y1, float z1, float x2, float y2, + float z2, float g) { + return toPair(x1 - g, y1 - g, z1 - g, x2 + g, y2 + g, z2 + g); + } + + public static void putBakedQuad(RecolorableBakedQuad.Builder consumer, BakedQuad quad) { + consumer.setQuadOrientation(quad.getDirection()); + if (quad.isTinted()) { + consumer.setQuadTint(quad.getTintIndex()); + } + consumer.setShade(quad.isShade()); + int[] data = new int[4]; + VertexFormat formatFrom = consumer.getVertexFormat(); + VertexFormat formatTo = DefaultVertexFormat.BLOCK; + int countFrom = formatFrom.getElements().size(); + int countTo = formatTo.getElements().size(); + int[] eMap = mapFormats(formatFrom, formatTo); + for (int v = 0; v < 4; v++) { + for (int e = 0; e < countFrom; e++) { + if (eMap[e] != countTo) { + unpack(quad.getVertices(), data, formatTo, v, eMap[e]); + consumer.put(e, data); + } else { + consumer.put(e); + } + } + } + } + + private static final ConcurrentMap, int[]> formatMaps = new ConcurrentHashMap<>(); + + public static int[] mapFormats(VertexFormat from, VertexFormat to) { + return formatMaps.computeIfAbsent(Pair.of(from, to), pair -> generateMapping(pair.getLeft(), pair.getRight())); + } + + private static int[] generateMapping(VertexFormat from, VertexFormat to) { + int fromCount = from.getElements().size(); + int toCount = to.getElements().size(); + int[] eMap = new int[fromCount]; + + for (int e = 0; e < fromCount; e++) { + VertexFormatElement expected = from.getElements().get(e); + int e2; + for (e2 = 0; e2 < toCount; e2++) { + VertexFormatElement current = to.getElements().get(e2); + if (expected.getUsage() == current.getUsage() && expected.getIndex() == current.getIndex()) { + break; + } + } + eMap[e] = e2; + } + return eMap; + } + + public static void unpack(int[] from, int[] to, VertexFormat formatFrom, int v, int e) { + int length = 4 < to.length ? 4 : to.length; + VertexFormatElement element = formatFrom.getElements().get(e); + int vertexStart = v * formatFrom.getIntegerSize() + formatFrom.getOffset(e); + int count = element.getElementCount(); + VertexFormatElement.Type type = element.getType(); + int size = type.getSize(); + int mask = (256 << (8 * (size - 1))) - 1; + for (int i = 0; i < length; i++) { + if (i < count) { + int pos = vertexStart + size * i; + int index = pos >> 2; + int offset = pos & 3; + int bits = from[index]; + bits = bits >>> (offset * 8); + if ((pos + size - 1) / 4 != index) { + bits |= from[index + 1] << ((4 - offset) * 8); + } + bits &= mask; + if (type == VertexFormatElement.Type.FLOAT) { + to[i] = bits; + } else if (type == VertexFormatElement.Type.UBYTE || type == VertexFormatElement.Type.USHORT) { + to[i] = Float.floatToRawIntBits((float) bits / mask); + } else if (type == VertexFormatElement.Type.UINT) { + to[i] = Float.floatToRawIntBits((float) ((double) (bits & 0xFFFFFFFFL) / 0xFFFFFFFFL)); + } else if (type == VertexFormatElement.Type.BYTE) { + to[i] = Float.floatToRawIntBits(((float) (byte) bits) / (mask >> 1)); + } else if (type == VertexFormatElement.Type.SHORT) { + to[i] = Float.floatToRawIntBits(((float) (short) bits) / (mask >> 1)); + } else if (type == VertexFormatElement.Type.INT) { + to[i] = Float.floatToRawIntBits((float) ((double) (bits & 0xFFFFFFFFL) / (0xFFFFFFFFL >> 1))); + } + } else { + to[i] = 0; + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java new file mode 100644 index 0000000000..e2333451d0 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java @@ -0,0 +1,244 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.quad; + +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.IQuadTransformer; + +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexFormatElement; +import lombok.Getter; +import lombok.Setter; + +import static net.minecraftforge.client.model.IQuadTransformer.*; + +@OnlyIn(Dist.CLIENT) +public class RecolorableBakedQuad extends BakedQuad { + + private final SpriteInformation spriteInformation; + private final VertexFormat format; + + public RecolorableBakedQuad(int[] unpackedData, int tint, Direction orientation, + SpriteInformation texture, boolean applyDiffuseLighting, boolean hasAmbientOcclusion, + VertexFormat format) { + super(unpackedData, tint, orientation, texture.sprite(), applyDiffuseLighting, hasAmbientOcclusion); + this.spriteInformation = texture; + this.format = format; + } + + public RecolorableBakedQuad withColor(ColorData data) { + if (!spriteInformation.colorable()) return this; + int argb = data.colorsARGB()[spriteInformation.colorID()]; + + int[] newData = new int[format.getIntegerSize() * 4]; + + float a = ((argb >> 24) & 0xFF) / 255f; // alpha + float r = ((argb >> 16) & 0xFF) / 255f; // red + float g = ((argb >> 8) & 0xFF) / 255f; // green + float b = ((argb) & 0xFF) / 255f; // blue + float[] array = new float[] { r, g, b, a }; + for (int v = 0; v < 4; v++) { + for (int e = 0; e < format.getElements().size(); e++) { + if (format.getElements().get(e).getUsage() == VertexFormatElement.Usage.COLOR) { + newData[v * format.getIntegerSize() + IQuadTransformer.COLOR] = argb; + } else { + int offset = findOffset(format.getElements().get(e)); + newData[v * format.getIntegerSize() + offset] = this.vertices[v * format.getIntegerSize() + offset]; + } + } + } + return new RecolorableBakedQuad(newData, this.tintIndex, this.direction, this.spriteInformation, + this.isShade(), this.hasAmbientOcclusion(), this.format); + } + + public static RecolorableBakedQuad.Builder of(BakedQuad quad, VertexFormat format) { + Builder builder = new Builder(format); + QuadHelper.putBakedQuad(builder, quad); + return builder; + } + + public static class Builder implements VertexConsumer { + + @Getter + private final VertexFormat vertexFormat; + private final int[] unpackedData; + @Setter + private int quadTint = -1; + @Setter + private Direction quadOrientation; + @Setter + private SpriteInformation texture; + @Setter + private boolean shade = true; + @Setter + private boolean hasAmbientOcclusion = true; + + private int vertices = 0; + private int elements = 0; + private boolean full = false; + private boolean contractUVs = false; + + public Builder(VertexFormat vertexFormat) { + this.vertexFormat = vertexFormat; + unpackedData = new int[vertexFormat.getIntegerSize() * 4]; + } + + @Override + public VertexConsumer vertex(double x, double y, double z) { + int offset = vertices * vertexFormat.getIntegerSize() + POSITION; + unpackedData[offset] = Float.floatToRawIntBits((float) x); + unpackedData[offset + 1] = Float.floatToRawIntBits((float) y); + unpackedData[offset + 2] = Float.floatToRawIntBits((float) z); + addElement(); + return this; + } + + @Override + public VertexConsumer color(int red, int green, int blue, int alpha) { + int offset = vertices * vertexFormat.getIntegerSize() + COLOR; + unpackedData[offset] = ((alpha & 0xFF) << 24) | + ((blue & 0xFF) << 16) | + ((green & 0xFF) << 8) | + (red & 0xFF); + addElement(); + return this; + } + + @Override + public VertexConsumer uv(float u, float v) { + int offset = vertices * vertexFormat.getIntegerSize() + UV0; + unpackedData[offset] = Float.floatToRawIntBits(u); + unpackedData[offset + 1] = Float.floatToRawIntBits(v); + addElement(); + return this; + } + + @Override + public VertexConsumer overlayCoords(int u, int v) { + if (UV1 >= 0) { + int offset = vertices * vertexFormat.getIntegerSize() + UV1; + unpackedData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16); + addElement(); + } + return this; + } + + @Override + public VertexConsumer uv2(int u, int v) { + int offset = vertices * vertexFormat.getIntegerSize() + UV2; + unpackedData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16); + addElement(); + return this; + } + + @Override + public VertexConsumer normal(float x, float y, float z) { + int offset = vertices * vertexFormat.getIntegerSize() + NORMAL; + unpackedData[offset] = ((int) (x * 127.0f) & 0xFF) | + (((int) (y * 127.0f) & 0xFF) << 8) | + (((int) (z * 127.0f) & 0xFF) << 16); + addElement(); + return this; + } + + @Override + public void endVertex() {} + + @Override + public void defaultColor(int defaultR, int defaultG, int defaultB, int defaultA) {} + + @Override + public void unsetDefaultColor() {} + + public void put(int element, int... data) { + for (int i = 0; i < 4; i++) { + if (i < data.length) { + unpackedData[vertices * vertexFormat.getIntegerSize() + element] = data[i]; + } else { + unpackedData[vertices * vertexFormat.getIntegerSize() + element] = 0; + } + } + addElement(); + } + + private void addElement() { + elements++; + if (elements == vertexFormat.getElements().size()) { + vertices++; + elements = 0; + } + if (vertices == 4) { + full = true; + } + } + + public RecolorableBakedQuad build() { + if (!full) { + throw new IllegalStateException("not enough data"); + } + if (texture == null) { + throw new IllegalStateException("texture not set"); + } + if (contractUVs) { + float tX = texture.sprite().contents().width() / (texture.sprite().getU1() - texture.sprite().getU0()); + float tY = texture.sprite().contents().height() / (texture.sprite().getV1() - texture.sprite().getV0()); + float tS = Math.max(tX, tY); + float ep = 1f / (tS * 0x100); + int uve = 0; + while (uve < vertexFormat.getElements().size()) { + VertexFormatElement e = vertexFormat.getElements().get(uve); + if (e.getUsage() == VertexFormatElement.Usage.UV && e.getIndex() == 0) { + break; + } + uve++; + } + if (uve == vertexFormat.getElements().size()) { + throw new IllegalStateException("Can't contract UVs: format doesn't contain UVs"); + } + float[] uvc = new float[4]; + for (int v = 0; v < 4; v++) { + for (int i = 0; i < 4; i++) { + uvc[i] += Float.intBitsToFloat(unpackedData[v * uve + i] / 4); + } + } + for (int v = 0; v < 4; v++) { + for (int i = 0; i < 4; i++) { + float uo = Float.intBitsToFloat(unpackedData[v * uve + i]); + float eps = 1f / 0x100; + float un = uo * (1 - eps) + uvc[i] * eps; + float ud = uo - un; + float aud = ud; + if (aud < 0) aud = -aud; + if (aud < ep) // not moving a fraction of a pixel + { + float udc = uo - uvc[i]; + if (udc < 0) udc = -udc; + if (udc < 2 * ep) // center is closer than 2 fractions of a pixel, don't move too close + { + un = (uo + uvc[i]) / 2; + } else // move at least by a fraction + { + un = uo + (ud < 0 ? ep : -ep); + } + } + unpackedData[v * uve + i] = Float.floatToRawIntBits(un); + } + } + } + return new RecolorableBakedQuad(unpackedData, quadTint, quadOrientation, texture, shade, + hasAmbientOcclusion, vertexFormat); + } + } + + private static int findOffset(VertexFormatElement element) { + // Divide by 4 because we want the int offset + var index = DefaultVertexFormat.BLOCK.getElements().indexOf(element); + return index < 0 ? -1 : DefaultVertexFormat.BLOCK.getOffset(index) / 4; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java new file mode 100644 index 0000000000..516f6f3777 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.quad; + +import net.minecraft.client.renderer.block.model.BlockFaceUV; +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import org.apache.commons.lang3.tuple.Pair; +import org.joml.Vector3f; + +@FunctionalInterface +@OnlyIn(Dist.CLIENT) +public interface UVMapper { + + static UVMapper standard(int rot) { + return (normal, box) -> { + Vector3f small = box.getLeft(); + Vector3f large = box.getRight(); + return switch (normal.getAxis()) { + case X -> new BlockFaceUV(new float[] { small.y, large.z, large.y, small.z }, rot); + case Y -> new BlockFaceUV(new float[] { small.x, large.z, large.x, small.z }, rot); + case Z -> new BlockFaceUV(new float[] { small.x, large.y, large.x, small.y }, rot); + }; + }; + } + + BlockFaceUV map(Direction normal, Pair box); +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java new file mode 100644 index 0000000000..d51d817024 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import org.jetbrains.annotations.Nullable; + +@OnlyIn(Dist.CLIENT) +public class ActivableCacheKey extends CacheKey { + + private final boolean active; + + public ActivableCacheKey(float thickness, boolean active) { + super(thickness); + this.active = active; + } + + public static ActivableCacheKey of(@Nullable Float thickness, @Nullable Boolean active) { + float thick = thickness == null ? 0.5f : thickness; + boolean act = active != null && active; + return new ActivableCacheKey(thick, act); + } + + public boolean isActive() { + return active; + } + + // activeness is merely a way to pass information onwards, it does not result in separate mappings. +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/CacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/CacheKey.java new file mode 100644 index 0000000000..e81e9771f6 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/CacheKey.java @@ -0,0 +1,54 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import net.minecraft.util.StringRepresentable; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +@OnlyIn(Dist.CLIENT) +public class CacheKey implements StringRepresentable { + + protected final float thickness; + + private final int hash; + + public CacheKey(float thickness) { + this.thickness = thickness; + this.hash = computeHash(); + } + + public static CacheKey of(@Nullable Float thickness) { + float thick = thickness == null ? 0.5f : thickness; + return new CacheKey(thick); + } + + public float getThickness() { + return thickness; + } + + protected int computeHash() { + return Objects.hash(thickness); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (CacheKey) obj; + return Float.floatToIntBits(this.thickness) == Float.floatToIntBits(that.thickness); + } + + @Override + public final int hashCode() { + return hash; + } + + @Override + public @NotNull String getSerializedName() { + return String.valueOf(Float.floatToIntBits(thickness)); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java new file mode 100644 index 0000000000..24bf91eeac --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java @@ -0,0 +1,7 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +public record ColorData(int... colorsARGB) {} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformation.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformation.java new file mode 100644 index 0000000000..818527f0b8 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformation.java @@ -0,0 +1,13 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +public record SpriteInformation(TextureAtlasSprite sprite, int colorID) { + + public boolean colorable() { + return colorID >= 0; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/DrawUtil.java b/src/main/java/com/gregtechceu/gtceu/client/util/DrawUtil.java index 33971070d4..9d1c4473e8 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/DrawUtil.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/DrawUtil.java @@ -63,4 +63,22 @@ private static void fillHorizontalGradient(GuiGraphics graphics, VertexConsumer consumer.vertex(matrix4f, (float) x2, (float) y2, (float) z).color(r2, g2, b2, a2).endVertex(); consumer.vertex(matrix4f, (float) x2, (float) y1, (float) z).color(r2, g2, b2, a2).endVertex(); } + + public static int interpolateColor(int color1, int color2, float blend) { + int a1 = color1 >> 24 & 255; + int r1 = color1 >> 16 & 255; + int g1 = color1 >> 8 & 255; + int b1 = color1 & 255; + + int a2 = color2 >> 24 & 255; + int r2 = color2 >> 16 & 255; + int g2 = color2 >> 8 & 255; + int b2 = color2 & 255; + + int a = (int) (a1 * (1 - blend) + a2 * blend); + int r = (int) (r1 * (1 - blend) + r2 * blend); + int g = (int) (g1 * (1 - blend) + g2 * blend); + int b = (int) (b1 * (1 - blend) + b2 * blend); + return a << 24 | r << 16 | g << 8 | b; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java b/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java new file mode 100644 index 0000000000..aedb2c3411 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java @@ -0,0 +1,85 @@ +package com.gregtechceu.gtceu.client.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; + +import lombok.Getter; +import lombok.experimental.Accessors; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +/** + * Collection of various information for rendering purposes. + */ +@Accessors(fluent = true) +public final class EffectRenderContext { + + private static final EffectRenderContext instance = new EffectRenderContext(); + + public static EffectRenderContext getInstance() { + return instance; + } + + @Getter + private final Frustum camera = new Frustum(Minecraft.getInstance().levelRenderer.getFrustum()); + + @Nullable + private Entity renderViewEntity; + @Getter + private float partialTicks; + @Getter + private double cameraX; + @Getter + private double cameraY; + @Getter + private double cameraZ; + @NotNull + @Getter + private Vec3 cameraViewDir = Vec3.ZERO; + @Getter + private float rotationY; + @Getter + private float rotationX; + @Getter + private float rotationYZ; + @Getter + private float rotationXY; + @Getter + private float rotationXZ; + + @NotNull + public EffectRenderContext update(@NotNull Entity renderViewEntity, float partialTicks) { + this.renderViewEntity = renderViewEntity; + this.partialTicks = partialTicks; + + this.cameraX = renderViewEntity.xOld + + (renderViewEntity.getX() - renderViewEntity.xOld) * partialTicks; + this.cameraY = renderViewEntity.yOld + + (renderViewEntity.getY() - renderViewEntity.yOld) * partialTicks; + this.cameraZ = renderViewEntity.zOld + + (renderViewEntity.getZ() - renderViewEntity.zOld) * partialTicks; + this.cameraViewDir = renderViewEntity.getViewVector(partialTicks); + + this.rotationY = Minecraft.getInstance().gameRenderer.getMainCamera().getYRot(); + this.rotationX = Minecraft.getInstance().gameRenderer.getMainCamera().getXRot(); + // this.rotationYZ = ActiveRenderInfo.getRotationYZ(); + // this.rotationXY = ActiveRenderInfo.getRotationXY(); + // this.rotationXZ = ActiveRenderInfo.getRotationXZ(); + + this.camera.prepare(this.cameraX, this.cameraY, this.cameraZ); + + return this; + } + + /** + * @return render view entity + */ + @NotNull + public Entity renderViewEntity() { + return Objects.requireNonNull(renderViewEntity, "renderViewEntity not available yet"); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java index 5acfe490fb..875f620552 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java @@ -2,9 +2,11 @@ import net.minecraft.core.Direction; import net.minecraft.util.Mth; +import net.minecraft.world.phys.AABB; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import org.joml.Matrix4f; @@ -88,4 +90,110 @@ public static void renderRing(PoseStack poseStack, VertexConsumer buffer, float } } + + public static void renderCubeFrame(BufferBuilder buffer, double minX, double minY, double minZ, double maxX, + double maxY, double maxZ, float r, float g, float b, float a) { + buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); + + buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); + + buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); + + buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); + + buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); + + buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); + + buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); + } + + public static void renderCubeFace(VertexConsumer buffer, AABB cuboid, float r, float g, float b, float a, + boolean shade) { + renderCubeFace(buffer, cuboid.minX, cuboid.minY, cuboid.minZ, cuboid.maxX, cuboid.maxY, cuboid.maxZ, r, g, + b, a, shade); + } + + public static void renderCubeFace(VertexConsumer buffer, double minX, double minY, double minZ, double maxX, + double maxY, double maxZ, float red, float green, float blue, float alpha) { + renderCubeFace(buffer, minX, minY, minZ, maxX, maxY, maxZ, red, green, blue, alpha, false); + } + + public static void renderCubeFace(VertexConsumer buffer, double minX, double minY, double minZ, double maxX, + double maxY, double maxZ, float red, float green, float blue, float a, + boolean shade) { + float r = red, g = green, b = blue; + + if (shade) { + r *= 0.6; + g *= 0.6; + b *= 0.6; + } + buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); + + if (shade) { + r = red * 0.5f; + g = green * 0.5f; + b = blue * 0.5f; + } + buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); + + if (shade) { + r = red; + g = green; + b = blue; + } + buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); + + if (shade) { + r = red * 0.8f; + g = green * 0.8f; + b = blue * 0.8f; + } + buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java index db5a45e0fb..6a65b59998 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java @@ -68,6 +68,11 @@ public boolean canPipePassThrough() { return false; } + @Override + public boolean forcePipeRenderConnection() { + return false; + } + @Nullable public BlockState getAppearance(BlockState sourceState, BlockPos sourcePos) { return facadeState; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java index 4d3d20a995..7403461e1a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java @@ -27,7 +27,6 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import lombok.Getter; @@ -95,6 +94,11 @@ public boolean canConnectRedstone() { return true; } + @Override + public void onRedstoneInputSignalChange(int newSignalStrength) { + updateInput(); + } + @Override public void onNeighborChanged(Block block, BlockPos fromPos, boolean isMoving) { super.onNeighborChanged(block, fromPos, isMoving); @@ -183,10 +187,7 @@ public List getAllowedModes() { } private int getInputSignal() { - Level level = coverHolder.getLevel(); - BlockPos sourcePos = coverHolder.getPos().relative(attachedSide); - - return level.getSignal(sourcePos, attachedSide); + return coverHolder.getInputRedstoneSignal(attachedSide, true); } ////////////////////////////////////// diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java index ce103e774b..5763abcc7e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java @@ -49,6 +49,11 @@ public boolean canPipePassThrough() { return !workingEnabled; } + @Override + public boolean forcePipeRenderConnection() { + return false; + } + @Override public InteractionResult onSoftMalletClick(Player playerIn, InteractionHand hand, BlockHitResult hitResult) { this.workingEnabled = !this.workingEnabled; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java new file mode 100644 index 0000000000..89f8cddfba --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java @@ -0,0 +1,252 @@ +package com.gregtechceu.gtceu.common.cover.filter; + +import com.gregtechceu.gtceu.api.blockentity.IDirtyNotifiable; +import com.gregtechceu.gtceu.api.cover.filter.Filter; +import com.lowdragmc.lowdraglib.misc.ItemStackTransfer; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public abstract class BaseFilterContainer extends ItemStackTransfer { + + private int maxTransferSize = 1; + private int transferSize; + private @Nullable Filter currentFilter; + private @Nullable Runnable onFilterInstanceChange; + private final IDirtyNotifiable dirtyNotifiable; + + protected BaseFilterContainer(IDirtyNotifiable dirtyNotifiable) { + super(); + this.dirtyNotifiable = dirtyNotifiable; + } + + public boolean test(Object toTest) { + return !hasFilter() || getFilter().test(toTest); + } + + public MatchResult match(Object toMatch) { + if (!hasFilter()) + return MatchResult.create(true, toMatch, -1); + + return getFilter().match(toMatch); + } + + public int getTransferLimit(Object stack) { + if (!hasFilter() || isBlacklistFilter()) { + return getTransferSize(); + } + return getFilter().getTransferLimit(stack, getTransferSize()); + } + + @Override + public int getSlotLimit(int slot) { + return 1; + } + + public void onFilterInstanceChange() { + dirtyNotifiable.markAsDirty(); + if (onFilterInstanceChange != null) { + onFilterInstanceChange.run(); + } + } + + public void setOnFilterInstanceChange(@Nullable Runnable onFilterInstanceChange) { + this.onFilterInstanceChange = onFilterInstanceChange; + } + + public final @NotNull ItemStack getFilterStack() { + return this.getStackInSlot(0); + } + + @Override + public void setStackInSlot(int slot, @NotNull ItemStack stack) { + if (ItemStack.areItemStacksEqual(stack, getFilterStack())) + return; + + if (stack.isEmpty()) { + setFilter(null); + } else if (isItemValid(stack)) { + setFilter(BaseFilter.getFilterFromStack(stack)); + } + + super.setStackInSlot(slot, stack); + } + + @Override + public boolean isItemValid(int slot, @NotNull ItemStack stack) { + return isItemValid(stack); + } + + protected abstract boolean isItemValid(ItemStack stack); + + protected abstract String getFilterName(); + + @Override + public @NotNull ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { + if (!isItemValid(stack)) return stack; + var remainder = super.insertItem(slot, stack, simulate); + if (!simulate) setFilter(BaseFilter.getFilterFromStack(stack)); + return remainder; + } + + @Override + public @NotNull ItemStack extractItem(int slot, int amount, boolean simulate) { + var extracted = super.extractItem(slot, amount, simulate); + if (!extracted.isEmpty()) { + setFilter(null); + } + return extracted; + } + + public final void setFilterStack(ItemStack stack) { + setStackInSlot(0, stack); + } + + public int getMaxTransferSize() { + return !showGlobalTransferLimitSlider() && hasFilter() ? currentFilter.getMaxTransferSize() : + this.maxTransferSize; + } + + public void setMaxTransferSize(int maxTransferSize) { + this.maxTransferSize = MathHelper.clamp(maxTransferSize, 1, Integer.MAX_VALUE); + this.transferSize = MathHelper.clamp(this.transferSize, 1, this.maxTransferSize); + if (hasFilter()) currentFilter.setMaxTransferSize(this.maxTransferSize); + } + + public final boolean hasFilter() { + return currentFilter != null; + } + + public final @Nullable Filter getFilter() { + return currentFilter; + } + + public final void setFilter(@Nullable Filter newFilter) { + this.currentFilter = newFilter; + if (hasFilter()) { + this.currentFilter.setDirtyNotifiable(this.dirtyNotifiable); + this.currentFilter.setMaxTransferSize(this.maxTransferSize); + } + if (onFilterInstanceChange != null) { + this.onFilterInstanceChange.run(); + } + } + + public boolean showGlobalTransferLimitSlider() { + return this.maxTransferSize > 0 && (!hasFilter() || getFilter().showGlobalTransferLimitSlider()); + } + + public void setBlacklistFilter(boolean blacklistFilter) { + if (hasFilter()) getFilter().setBlacklistFilter(blacklistFilter); + onFilterInstanceChange(); + } + + public final boolean isBlacklistFilter() { + return hasFilter() && getFilter().isBlacklistFilter(); + } + + public int getTransferSize() { + if (!showGlobalTransferLimitSlider()) { + return getMaxTransferSize(); + } + return this.transferSize; + } + + public int getTransferLimit(int slotIndex) { + if (isBlacklistFilter() || !hasFilter()) { + return getTransferSize(); + } + return this.currentFilter.getTransferLimit(slotIndex, getTransferSize()); + } + + public void setTransferSize(int transferSize) { + this.transferSize = MathHelper.clamp(transferSize, 1, getMaxTransferSize()); + onFilterInstanceChange(); + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tagCompound = new CompoundTag(); + tagCompound.put("FilterInventory", super.serializeNBT()); + tagCompound.putInt("TransferStackSize", getTransferSize()); + return tagCompound; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + super.deserializeNBT(nbt.getCompound("FilterInventory")); + setFilter(BaseFilter.getFilterFromStack(getFilterStack())); + if (nbt.contains("TransferStackSize")) + this.transferSize = nbt.getInt("TransferStackSize"); + } + + public void handleLegacyNBT(CompoundTag nbt) { + // for filters as covers, the stack is set manually, and "FilterInventory" doesn't exist to be deserialized + // also, ItemStackHandler's deserialization doesn't use setStackInSlot, so I have to do that manually here + if (nbt.contains("FilterInventory")) { + super.deserializeNBT(nbt.getCompound("FilterInventory")); + setFilter(BaseFilter.getFilterFromStack(getFilterStack())); + } + + if (hasFilter()) + getFilter().getFilterReader().handleLegacyNBT(nbt); + } + + /** Uses Cleanroom MUI */ + public IWidget initUI(ModularPanel main, PanelSyncManager manager) { + PanelSyncHandler panel = manager.panel("filter_panel", main, (syncManager, syncHandler) -> { + var filter = hasFilter() ? getFilter() : BaseFilter.ERROR_FILTER; + filter.setMaxTransferSize(getMaxTransferSize()); + return filter.createPopupPanel(syncManager); + }); + + var filterButton = new ButtonWidget<>(); + filterButton.setEnabled(hasFilter()); + + return new Row().coverChildrenHeight() + .marginBottom(2).widthRel(1f) + .child(new ItemSlot() + .slot(SyncHandlers.itemSlot(this, 0) + .filter(this::isItemValid) + .singletonSlotGroup(101) + .changeListener((newItem, onlyAmountChanged, client, init) -> { + if (!isItemValid(newItem) && panel.isPanelOpen()) { + panel.closePanel(); + } + })) + .size(18).marginRight(2) + .background(GTGuiTextures.SLOT, GTGuiTextures.FILTER_SLOT_OVERLAY.asIcon().size(16))) + .child(filterButton + .background(GTGuiTextures.MC_BUTTON, GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) + .hoverBackground(GuiTextures.MC_BUTTON_HOVERED, + GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) + .setEnabledIf(w -> hasFilter()) + .onMousePressed(i -> { + if (!panel.isPanelOpen()) { + panel.openPanel(); + } else { + panel.closePanel(); + } + Interactable.playButtonClickSound(); + return true; + })) + .child(IKey.dynamic(this::getFilterName) + .alignment(Alignment.CenterRight).asWidget() + .left(36).right(0).height(18)); + } + + public void writeInitialSyncData(FriendlyByteBuf packetBuffer) { + packetBuffer.writeItemStack(this.getFilterStack()); + packetBuffer.writeInt(this.maxTransferSize); + packetBuffer.writeInt(this.transferSize); + } + + public void readInitialSyncData(@NotNull FriendlyByteBuf packetBuffer) { + var stack = packetBuffer.readItem(); + this.setFilterStack(stack); + this.setMaxTransferSize(packetBuffer.readInt()); + this.setTransferSize(packetBuffer.readInt()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index 8ea9fd9630..00f2a86152 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -1,11 +1,16 @@ package com.gregtechceu.gtceu.common.data; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.blockentity.*; import net.minecraft.world.level.block.entity.SignBlockEntity; import com.tterrag.registrate.util.entry.BlockEntityEntry; import com.tterrag.registrate.util.entry.BlockEntry; +import com.tterrag.registrate.util.nullness.NonNullSupplier; + +import java.util.Arrays; +import java.util.stream.Stream; import static com.gregtechceu.gtceu.common.registry.GTRegistration.REGISTRATE; @@ -14,23 +19,32 @@ * @date 2023/2/13 * @implNote GTBlockEntities */ +@SuppressWarnings("unchecked") public class GTBlockEntities { - @SuppressWarnings("unchecked") + public static final BlockEntityEntry NEW_PIPE = REGISTRATE + .blockEntity("pipe", PipeBlockEntity::new) + .validBlocks(Stream.concat(Arrays.stream(GTBlocks.DUCT_PIPES), + Stream.concat(Arrays.stream(GTBlocks.OPTICAL_PIPES), + Stream.concat(Arrays.stream(GTBlocks.LASER_PIPES), + Stream.concat(GTBlocks.ITEM_PIPE_BLOCKS.values().stream(), + Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), + GTBlocks.FLUID_PIPE_BLOCKS.values().stream()))))) + .toArray(NonNullSupplier[]::new)) + .register(); + public static final BlockEntityEntry CABLE = REGISTRATE .blockEntity("cable", CableBlockEntity::create) .onRegister(CableBlockEntity::onBlockEntityRegister) .validBlocks(GTBlocks.CABLE_BLOCKS.values().toArray(BlockEntry[]::new)) .register(); - @SuppressWarnings("unchecked") public static final BlockEntityEntry FLUID_PIPE = REGISTRATE .blockEntity("fluid_pipe", FluidPipeBlockEntity::new) .onRegister(FluidPipeBlockEntity::onBlockEntityRegister) .validBlocks(GTBlocks.FLUID_PIPE_BLOCKS.values().toArray(BlockEntry[]::new)) .register(); - @SuppressWarnings("unchecked") public static final BlockEntityEntry ITEM_PIPE = REGISTRATE .blockEntity("item_pipe", ItemPipeBlockEntity::create) .onRegister(ItemPipeBlockEntity::onBlockEntityRegister) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java index d743e72068..ba5c378c1d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java @@ -140,7 +140,9 @@ public static CoverDefinition register(String id, CoverDefinition.CoverBehaviour public static CoverDefinition register(String id, CoverDefinition.CoverBehaviourProvider behaviorCreator, ICoverRenderer coverRenderer) { - var definition = new CoverDefinition(GTCEu.id(id), behaviorCreator, coverRenderer); + var definition = new CoverDefinition(GTCEu.id(id), behaviorCreator, + (quads, side, rand, renderPlate, renderBackside, colorData) -> coverRenderer.renderCover(quads, side, + rand, null, null, null, null, null)); GTRegistries.COVERS.register(GTCEu.id(id), definition); return definition; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java index f44ae6b71b..f5e3f5dc2b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipes.java @@ -57,7 +57,7 @@ public static void recipeAddition(Consumer originalConsumer) { AirScrubberRecipes.init(consumer); ChemistryRecipes.init(consumer); - MetaBlockEntityMachineRecipeLoader.init(consumer); + MetaTileEntityMachineRecipeLoader.init(consumer); MiscRecipeLoader.init(consumer); VanillaStandardRecipes.init(consumer); WoodMachineRecipes.init(consumer); @@ -72,7 +72,7 @@ public static void recipeAddition(Consumer originalConsumer) { CircuitRecipes.init(consumer); ComponentRecipes.init(consumer); - MetaBlockEntityLoader.init(consumer); + MetaTileEntityLoader.init(consumer); // GCyM GCyMRecipes.init(consumer); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java b/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java index 93608a0a91..118139121c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/trait/miner/SteamMinerLogic.java @@ -9,9 +9,9 @@ public class SteamMinerLogic extends MinerLogic { * Creates the logic for steam miners * * @param metaBlockEntity the {@link IRecipeLogicMachine} this logic belongs to - * @param fortune the fortune amount to apply when mining ores - * @param speed the speed in ticks per block mined - * @param maximumRadius the maximum radius (square shaped) the miner can mine in + * @param fortune the fortune amount to apply when mining ores + * @param speed the speed in ticks per block mined + * @param maximumRadius the maximum radius (square shaped) the miner can mine in */ public SteamMinerLogic(IRecipeLogicMachine metaBlockEntity, int fortune, int speed, int maximumRadius) { super(metaBlockEntity, fortune, speed, maximumRadius); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java index f2af6bd781..d8a943a49a 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java @@ -77,7 +77,7 @@ private static void processRestrictivePipe(TagPrefix pipePrefix, Material materi 'P', new UnificationEntry(unrestrictive, material), 'R', ChemicalHelper.get(ring, Iron)); } - private static void processPipeTiny(TagPrefix pipePrefix, Material material, IMaterialProperty property, + private static void processPipeTiny(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; ItemStack pipeStack = ChemicalHelper.get(pipePrefix, material); @@ -104,7 +104,7 @@ private static void processPipeTiny(TagPrefix pipePrefix, Material material, IMa } } - private static void processPipeSmall(TagPrefix pipePrefix, Material material, IMaterialProperty property, + private static void processPipeSmall(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; ItemStack pipeStack = ChemicalHelper.get(pipePrefix, material); @@ -131,7 +131,7 @@ private static void processPipeSmall(TagPrefix pipePrefix, Material material, IM } } - private static void processPipeNormal(TagPrefix pipePrefix, Material material, IMaterialProperty property, + private static void processPipeNormal(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; ItemStack pipeStack = ChemicalHelper.get(pipePrefix, material); @@ -158,7 +158,7 @@ private static void processPipeNormal(TagPrefix pipePrefix, Material material, I } } - private static void processPipeLarge(TagPrefix pipePrefix, Material material, IMaterialProperty property, + private static void processPipeLarge(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; ItemStack pipeStack = ChemicalHelper.get(pipePrefix, material); @@ -185,7 +185,7 @@ private static void processPipeLarge(TagPrefix pipePrefix, Material material, IM } } - private static void processPipeHuge(TagPrefix pipePrefix, Material material, IMaterialProperty property, + private static void processPipeHuge(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; ItemStack pipeStack = ChemicalHelper.get(pipePrefix, material); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java index d488d801ed..4c5c987a97 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CreateRecipeLoader.java @@ -10,7 +10,7 @@ import java.util.function.Consumer; import static com.gregtechceu.gtceu.data.recipe.CraftingComponent.*; -import static com.gregtechceu.gtceu.data.recipe.misc.MetaBlockEntityLoader.registerMachineRecipe; +import static com.gregtechceu.gtceu.data.recipe.misc.MetaTileEntityLoader.registerMachineRecipe; /** * @author KilaBash diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java index 5d8ba9791c..93bcbf9ccd 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java @@ -31,7 +31,7 @@ import static com.gregtechceu.gtceu.data.recipe.CraftingComponent.HULL; import static com.gregtechceu.gtceu.data.recipe.CraftingComponent.PUMP; -public class MetaBlockEntityLoader { +public class MetaTileEntityLoader { public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "casing_ulv", GTBlocks.MACHINE_CASING_ULV.asStack(), "PPP", diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java index 5070ebb41a..01850659c4 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java @@ -30,7 +30,7 @@ import static com.gregtechceu.gtceu.common.data.GTRecipeTypes.ASSEMBLER_RECIPES; import static com.gregtechceu.gtceu.common.data.GTRecipeTypes.ASSEMBLY_LINE_RECIPES; -public class MetaBlockEntityMachineRecipeLoader { +public class MetaTileEntityMachineRecipeLoader { public static void init(Consumer provider) { // this needs to exist here now :) diff --git a/src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java b/src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java new file mode 100644 index 0000000000..193a93ec3d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java @@ -0,0 +1,41 @@ +package com.gregtechceu.gtceu.utils; + +import lombok.Getter; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.Level; + +import java.util.Objects; + +public class DimensionFacingPos { + + @Getter + private final BlockPos pos; + @Getter + private final Direction facing; + @Getter + private final ResourceKey dimension; + private final int hashCode; + + public DimensionFacingPos(BlockPos pos, Direction facing, ResourceKey dimension) { + this.pos = pos; + this.facing = facing; + this.dimension = dimension; + this.hashCode = Objects.hash(pos, facing, dimension); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DimensionFacingPos that = (DimensionFacingPos) o; + return dimension == that.dimension && Objects.equals(pos, that.pos) && + facing == that.facing; + } + + @Override + public int hashCode() { + return hashCode; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java index 3a065f4742..478065c3b2 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java @@ -37,23 +37,24 @@ import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.RedStoneWireBlock; +import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.Tags; import com.mojang.blaze3d.platform.InputConstants; import com.mojang.datafixers.util.Pair; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; +import java.util.function.LongPredicate; import static com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey.HAZARD; @@ -150,6 +151,19 @@ public static float getExplosionPower(long voltage) { return getTierByVoltage(voltage) + 1; } + public static int getRedstonePower(Level world, BlockPos blockPos, Direction side) { + BlockPos offsetPos = blockPos.relative(side); + int worldPower = world.getDirectSignal(offsetPos, side); + if (worldPower < 15) { + BlockState offsetState = world.getBlockState(offsetPos); + if (offsetState.getBlock() instanceof RedStoneWireBlock) { + int wirePower = offsetState.getValue(RedStoneWireBlock.POWER); + return Math.max(worldPower, wirePower); + } + } + return worldPower; + } + /** * @param array Array sorted with natural order * @param value Value to search for @@ -386,6 +400,19 @@ public static DyeColor determineDyeColor(int rgbColor) { return distances.get(min); } + public static long binarySearch(long minValue, long maxValue, LongPredicate test, boolean ascending) { + while (maxValue - minValue > 1) { + long middle = (minValue + maxValue) / 2; + // XOR + if (test.test(middle) ^ !ascending) { + maxValue = middle; + } else { + minValue = maxValue; + } + } + return ascending ? maxValue : minValue; + } + public static int convertRGBtoARGB(int colorValue) { return convertRGBtoARGB(colorValue, 0xFF); } @@ -396,6 +423,60 @@ public static int convertRGBtoARGB(int colorValue, int opacity) { return opacity << 24 | colorValue; } + public static int[] convertARGBtoArray(int argb) { + int a = argb >> 24 & 255; + int r = argb >> 16 & 255; + int g = argb >> 8 & 255; + int b = argb & 255; + return new int[] { a, r, g, b }; + } + + @Contract(pure = true) + public static boolean evalMask(@NotNull Enum anEnum, byte mask) { + return (mask & (1 << anEnum.ordinal())) > 0; + } + + @Contract(pure = true) + public static boolean evalMask(@NotNull Enum anEnum, @NotNull BitSet mask) { + return mask.get(anEnum.ordinal()); + } + + @Contract(pure = true) + @NotNull + public static > EnumSet maskToSet(@NotNull Class enumClass, byte mask) { + EnumSet set = EnumSet.noneOf(enumClass); + for (T anEnum : enumClass.getEnumConstants()) { + if (evalMask(anEnum, mask)) set.add(anEnum); + } + return set; + } + + @Contract(pure = true) + @NotNull + public static > EnumSet maskToSet(@NotNull Class enumClass, @NotNull BitSet mask) { + EnumSet set = EnumSet.noneOf(enumClass); + for (T anEnum : enumClass.getEnumConstants()) { + if (evalMask(anEnum, mask)) set.add(anEnum); + } + return set; + } + + @Contract(pure = true) + @NotNull + public static BitSet setToMask(@NotNull EnumSet enumSet) { + BitSet mask = new BitSet(); + for (Enum anEnum : enumSet) { + mask.set(anEnum.ordinal()); + } + return mask; + } + + @Contract(pure = true, value = "-> new") + @NotNull + public static Set createWeakHashSet() { + return Collections.newSetFromMap(new WeakHashMap<>()); + } + /** * @param material the material to use * @return the correct "molten" fluid for a material @@ -527,4 +608,21 @@ public static void addPotionTooltip(List> effects 100 * probability)); }); } + + /** + * Forces the initialization of a class; this includes things like loading its static fields. + * This can be useful because a statement like {@code AClass.class} does not initialize a class. + *
+ *
+ * Does nothing if the class is already initialized. + * + * @param clazz the class object to initialize. + */ + public static void forceInitialization(Class clazz) { + try { + Class.forName(clazz.getName(), true, clazz.getClassLoader()); + } catch (ClassNotFoundException e) { + throw new AssertionError(e); // Can't happen + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java b/src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java new file mode 100644 index 0000000000..589848c5dc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java @@ -0,0 +1,88 @@ +package com.gregtechceu.gtceu.utils; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.utils.function.Task; +import net.minecraft.world.level.Level; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.level.LevelEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Mod.EventBusSubscriber(modid = GTCEu.MOD_ID) +public class TaskScheduler { + + @Nullable + public static TaskScheduler get(Level world) { + return tasksPerWorld.get(world); + } + + private static final Map tasksPerWorld = new HashMap<>(); + + private final List tasks = new ArrayList<>(); + private final List scheduledTasks = new ArrayList<>(); + private boolean running = false; + + public static void scheduleTask(Level world, Task task) { + if (world.isClientSide) { + throw new IllegalArgumentException("Attempt to schedule task on client world!"); + } + tasksPerWorld.computeIfAbsent(world, k -> new TaskScheduler()).scheduleTask(task); + } + + public void scheduleTask(Task task) { + if (running) { + scheduledTasks.add(task); + } else { + tasks.add(task); + } + } + + public void unload() { + tasks.clear(); + scheduledTasks.clear(); + } + + @SubscribeEvent + public static void onWorldUnload(LevelEvent.Unload event) { + if (!event.getLevel().isClientSide()) { + tasksPerWorld.remove(event.getLevel()); + } + } + + @SubscribeEvent + public static void onWorldTick(TickEvent.LevelTickEvent event) { + if (!event.level.isClientSide && event.phase == TickEvent.Phase.START) { + TaskScheduler scheduler = get(event.level); + if (scheduler != null) { + if (!scheduler.scheduledTasks.isEmpty()) { + scheduler.tasks.addAll(scheduler.scheduledTasks); + scheduler.scheduledTasks.clear(); + } + scheduler.running = true; + scheduler.tasks.removeIf(task -> !task.run()); + scheduler.running = false; + } + } + } + + public static Task weakTask(Task task) { + return new Task() { + + private final WeakReference ref = new WeakReference<>(task); + + @Override + public boolean run() { + Task task = this.ref.get(); + if (task == null) return false; + else return task.run(); + } + }; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/utils/function/Task.java b/src/main/java/com/gregtechceu/gtceu/utils/function/Task.java new file mode 100644 index 0000000000..723fd57497 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/utils/function/Task.java @@ -0,0 +1,12 @@ +package com.gregtechceu.gtceu.utils.function; + +@FunctionalInterface +public interface Task { + + /** + * Run the actions of this Task. Will be infinitely run each world tick until false is returned. + * + * @return {@code true} if the task should be run again, otherwise {@code false} + */ + boolean run(); +} From 5a6d38481a5280fcd562b4282176d12a91ef09df Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 22 Aug 2024 10:30:51 +0300 Subject: [PATCH 04/70] pipenets --- .../api/blockentity/ISyncedBlockEntity.java | 8 +- .../blockentity/MetaMachineBlockEntity.java | 14 +- .../api/capability/GTCapabilityHelper.java | 5 +- .../api/capability/IEnergyContainer.java | 6 +- .../gtceu/api/capability/ILaserContainer.java | 2 +- .../gtceu/api/capability/ILaserRelay.java | 13 ++ .../api/capability/compat/EUToFEProvider.java | 2 +- .../data/IComputationDataAccess.java | 12 ++ .../capability/data/IComputationProvider.java | 26 +++ .../api/capability/data/IComputationUser.java | 16 ++ .../api/capability/data/IDataAccess.java | 52 +++++ .../api/capability/data/IHatchDataAccess.java | 9 + .../capability/data/IStandardDataAccess.java | 12 ++ .../data/query/DataAccessFormat.java | 54 +++++ .../data/query/DataQueryFormat.java | 25 +++ .../data/query/DataQueryObject.java | 32 +++ .../capability/data/query/IBridgeable.java | 9 + .../data/query/RecipeDataQuery.java | 31 +++ .../api/capability/forge/GTCapability.java | 9 +- .../gtceu/api/cover/filter/Filter.java | 2 + .../gtceu/api/cover/filter/ItemFilter.java | 4 + .../properties/PipeNetProperties.java | 7 +- .../gtceu/api/graphnet/GraphNetBacker.java | 12 +- .../gtceu/api/graphnet/IGraphNet.java | 2 +- .../graphnet/pipenet/IPipeNetNodeHandler.java | 7 +- .../api/graphnet/pipenet/WorldPipeNet.java | 10 +- .../graphnet/pipenet/WorldPipeNetNode.java | 7 +- .../physical/IPipeMaterialStructure.java | 2 +- .../physical/block/MaterialPipeBlockItem.java | 2 +- .../pipenet/physical/block/PipeBlock.java | 11 +- .../physical/block/PipeMaterialBlock.java | 2 +- .../physical/tile/PipeBlockEntity.java | 2 +- .../physical/tile/PipeCoverHolder.java | 2 + .../gtceu/api/graphnet/worldnet/WorldNet.java | 6 +- .../api/machine/IMachineBlockEntity.java | 3 +- .../api/machine/MachineCoverContainer.java | 53 +++++ .../gtceu/api/machine/MetaMachine.java | 5 + .../feature/multiblock/IMultiPart.java | 1 + .../trait/NotifiableEnergyContainer.java | 4 +- .../trait/NotifiableLaserContainer.java | 18 +- .../gtceu/api/misc/EnergyContainerList.java | 4 +- .../gtceu/api/misc/LaserContainerList.java | 4 +- .../gregtechceu/gtceu/client/ClientProxy.java | 14 +- .../renderer/pipe/AbstractPipeModel.java | 17 +- .../renderer/pipe/ActivablePipeModel.java | 71 ++++--- .../client/renderer/pipe/CableModel.java | 147 +++++++++++++ .../renderer/pipe/cache/ExtraCappedSQC.java | 79 +++++++ .../pipe/util/SpriteInformationWrapper.java | 36 ++++ .../KineticMachineBlockEntity.java | 10 + .../blockentity/LaserPipeBlockEntity.java | 2 +- .../blockentity/OpticalPipeBlockEntity.java | 3 +- .../gtceu/common/cover/CoverSolarPanel.java | 2 +- .../cover/filter/BaseFilterContainer.java | 63 +++--- .../electric/BatteryBufferMachine.java | 4 +- .../machine/electric/ChargerMachine.java | 2 +- .../part/OpticalDataHatchMachine.java | 79 ++++--- .../CreativeEnergyContainerMachine.java | 21 +- .../pipelike/block/cable/CableBlock.java | 99 +++++++++ .../pipelike/block/cable/CableStructure.java | 99 +++++++++ .../pipelike/block/laser/LaserPipeBlock.java | 43 ++++ .../pipelike/block/laser/LaserStructure.java | 75 +++++++ .../optical/IOpticalTransferController.java | 43 ++++ .../block/optical/OpticalPipeBlock.java | 43 ++++ .../block/optical/OpticalStructure.java | 61 ++++++ .../pipelike/cable/EnergyNetHandler.java | 6 +- .../pipelike/handlers/LaserNetHandler.java | 61 ++++++ .../pipelike/handlers/OpticalNetHandler.java | 57 +++++ .../pipelike/laser/LaserNetHandler.java | 4 +- .../common/pipelike/laser/LaserNetWalker.java | 3 +- .../common/pipelike/net/SlowActiveWalker.java | 108 ++++++++++ .../net/energy/EnergyCapabilityObject.java | 197 ++++++++++++++++++ .../pipelike/net/energy/EnergyFlowData.java | 8 + .../pipelike/net/energy/EnergyFlowLogic.java | 76 +++++++ .../pipelike/net/energy/EnergyGroupData.java | 60 ++++++ .../net/energy/EnergyTraverseData.java | 166 +++++++++++++++ .../net/energy/IEnergyTransferController.java | 45 ++++ .../net/energy/SuperconductorLogic.java | 22 ++ .../net/energy/VoltageLimitLogic.java | 26 +++ .../pipelike/net/energy/VoltageLossLogic.java | 26 +++ .../pipelike/net/energy/WorldEnergyNet.java | 73 +++++++ .../net/laser/ILaserTransferController.java | 42 ++++ .../net/laser/LaserCapabilityObject.java | 87 ++++++++ .../pipelike/net/laser/WorldLaserNet.java | 55 +++++ .../net/optical/DataCapabilityObject.java | 96 +++++++++ .../pipelike/net/optical/WorldOpticalNet.java | 55 +++++ .../gtceu/config/ConfigHolder.java | 5 + .../gregtechceu/gtceu/core/MixinHelpers.java | 8 + .../mixins/SpriteResourceLoaderMixin.java | 35 ++++ .../com/gregtechceu/gtceu/utils/GTUtil.java | 7 + src/main/resources/gtceu.mixins.json | 1 + 90 files changed, 2668 insertions(+), 181 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/ILaserRelay.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationProvider.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationUser.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/IHatchDataAccess.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IBridgeable.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java index b12522c93e..1dd2544a15 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/ISyncedBlockEntity.java @@ -31,7 +31,7 @@ public interface ISyncedBlockEntity { * * @param buf the buffer to write data to */ - void writeInitialSyncData(@NotNull FriendlyByteBuf buf); + default void writeInitialSyncData(@NotNull FriendlyByteBuf buf) {} /** * Used to receive Server -> Client sync data. @@ -49,7 +49,7 @@ public interface ISyncedBlockEntity { * * @param buf the buffer to read data from */ - void receiveInitialSyncData(@NotNull FriendlyByteBuf buf); + default void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) {} /** * Used to send an anonymous Server -> Client packet. @@ -70,7 +70,7 @@ public interface ISyncedBlockEntity { * @param dataWriter a consumer which writes packet data to a buffer. * @see gregtech.api.capability.GregtechDataCodes */ - void writeCustomData(int discriminator, @NotNull Consumer<@NotNull FriendlyByteBuf> dataWriter); + default void writeCustomData(int discriminator, @NotNull Consumer<@NotNull FriendlyByteBuf> dataWriter) {} /** * Used to receive an anonymous Server -> Client packet. @@ -90,5 +90,5 @@ public interface ISyncedBlockEntity { * @param buf the buffer containing the packet data. * @see gregtech.api.capability.GregtechDataCodes */ - void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf); + default void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java index 0047290076..301c3eb272 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.capability.*; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; @@ -59,7 +60,7 @@ * @date 2023/2/17 * @implNote MetaMachineBlockEntity */ -public class MetaMachineBlockEntity extends BlockEntity implements IMachineBlockEntity { +public class MetaMachineBlockEntity extends NeighborCacheBlockEntity implements IMachineBlockEntity { public final MultiManagedStorage managedStorage = new MultiManagedStorage(); @Getter @@ -71,7 +72,7 @@ public class MetaMachineBlockEntity extends BlockEntity implements IMachineBlock private final long offset = GTValues.RNG.nextInt(20); protected MetaMachineBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); + super(type, pos, blockState, true); this.metaMachine = getDefinition().createMetaMachine(this); } @@ -266,10 +267,10 @@ public static LazyOptional getCapability(MetaMachine machine, @NotNull Ca return GTCapability.CAPABILITY_COMPUTATION_PROVIDER.orEmpty(cap, LazyOptional.of(() -> list.get(0))); } } else if (cap == GTCapability.CAPABILITY_DATA_ACCESS) { - if (machine instanceof IDataAccessHatch computationProvider) { + if (machine instanceof IDataAccess computationProvider) { return GTCapability.CAPABILITY_DATA_ACCESS.orEmpty(cap, LazyOptional.of(() -> computationProvider)); } - var list = getCapabilitiesFromTraits(machine.getTraits(), side, IDataAccessHatch.class); + var list = getCapabilitiesFromTraits(machine.getTraits(), side, IDataAccess.class); if (!list.isEmpty()) { return GTCapability.CAPABILITY_DATA_ACCESS.orEmpty(cap, LazyOptional.of(() -> list.get(0))); } @@ -323,6 +324,11 @@ public AABB getRenderBoundingBox() { return new AABB(worldPosition.offset(-1, 0, -1), worldPosition.offset(2, 2, 2)); } + @Override + public void markAsDirty() { + this.setChanged(); + } + @Override protected void saveAdditional(CompoundTag tag) { super.saveAdditional(tag); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java b/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java index 4cea0f02cb..9a62f5659e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.api.capability; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMaintenanceMachine; import com.gregtechceu.gtceu.api.machine.trait.RecipeLogic; @@ -90,7 +91,7 @@ public static IMaintenanceMachine getMaintenanceMachine(Level level, BlockPos po } @Nullable - public static ILaserContainer getLaser(Level level, BlockPos pos, @Nullable Direction side) { + public static ILaserRelay getLaser(Level level, BlockPos pos, @Nullable Direction side) { return getBlockEntityCapability(GTCapability.CAPABILITY_LASER, level, pos, side); } @@ -101,7 +102,7 @@ public static IOpticalComputationProvider getOpticalComputationProvider(Level le } @Nullable - public static IDataAccessHatch getDataAccess(Level level, BlockPos pos, @Nullable Direction side) { + public static IDataAccess getDataAccess(Level level, BlockPos pos, @Nullable Direction side) { return getBlockEntityCapability(GTCapability.CAPABILITY_DATA_ACCESS, level, pos, side); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IEnergyContainer.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IEnergyContainer.java index 7440cf1c5f..c615b62d49 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IEnergyContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/IEnergyContainer.java @@ -14,7 +14,7 @@ public interface IEnergyContainer extends IEnergyInfoProvider { * @param amperage packet size (energy to add / input amperage) * @return amount of used amperes. 0 if not accepted anything. */ - long acceptEnergyFromNetwork(Direction side, long voltage, long amperage); + long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate); /** * @return if this container accepts energy from the given side @@ -31,7 +31,7 @@ default boolean outputsEnergy(Direction side) { /** * This changes the amount stored. * This should only be used internally (f.e. draining while working or filling while generating). - * For transfer between blocks use {@link #acceptEnergyFromNetwork(Direction, long, long)}!!! + * For transfer between blocks use {@link #acceptEnergyFromNetwork(Direction, long, long, boolean)}!!! * * @param differenceAmount amount of energy to add (>0) or remove (<0) * @return amount of energy added or removed @@ -135,7 +135,7 @@ default boolean isOneProbeHidden() { IEnergyContainer DEFAULT = new IEnergyContainer() { @Override - public long acceptEnergyFromNetwork(Direction Direction, long l, long l1) { + public long acceptEnergyFromNetwork(Direction Direction, long l, long l1, boolean simulate) { return 0; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/ILaserContainer.java b/src/main/java/com/gregtechceu/gtceu/api/capability/ILaserContainer.java index fbfcb5ed16..2d400c4f67 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/ILaserContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/ILaserContainer.java @@ -3,4 +3,4 @@ /** * It is its own separate interface to make piping work easier */ -public interface ILaserContainer extends IEnergyContainer {} +public interface ILaserContainer extends IEnergyContainer, ILaserRelay {} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/ILaserRelay.java b/src/main/java/com/gregtechceu/gtceu/api/capability/ILaserRelay.java new file mode 100644 index 0000000000..5208fe874f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/ILaserRelay.java @@ -0,0 +1,13 @@ +package com.gregtechceu.gtceu.api.capability; + +public interface ILaserRelay { + + /** + * Receive a laser pulse. + * + * @param laserVoltage the voltage of the laser. + * @param laserAmperage the amperage of the laser. + * @return how much amperage was received. + */ + long receiveLaser(long laserVoltage, long laserAmperage); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/compat/EUToFEProvider.java b/src/main/java/com/gregtechceu/gtceu/api/capability/compat/EUToFEProvider.java index c14b7f7291..3aac7237a9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/compat/EUToFEProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/compat/EUToFEProvider.java @@ -51,7 +51,7 @@ public GTEnergyWrapper(IEnergyStorage energyStorage) { } @Override - public long acceptEnergyFromNetwork(Direction facing, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction facing, long voltage, long amperage, boolean simulate) { int receive = 0; // Try to use the internal buffer before consuming a new packet diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java new file mode 100644 index 0000000000..ae330c09f2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java @@ -0,0 +1,12 @@ +package com.gregtechceu.gtceu.api.capability.data; + +import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; +import org.jetbrains.annotations.NotNull; + +public interface IComputationDataAccess extends IHatchDataAccess { + + @Override + default @NotNull DataAccessFormat getFormat() { + return DataAccessFormat.COMPUTATION; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationProvider.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationProvider.java new file mode 100644 index 0000000000..f4cdeb6967 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationProvider.java @@ -0,0 +1,26 @@ +package com.gregtechceu.gtceu.api.capability.data; + +public interface IComputationProvider { + + /** + * Returns whether this provider supports bridging. If false, CWU will not be requested through + * network switches with multiple inputs. + * + * @return whether bridging is supported. + */ + boolean supportsBridging(); + + /** + * Called to supply CWU to a requester. + * + * @param requested the requested CWU + * @param simulate whether to simulate the request + * @return the amount of CWU supplied. + */ + long supplyCWU(long requested, boolean simulate); + + /** + * @return the maximum CWU that can be supplied in a single tick. + */ + long maxCWUt(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationUser.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationUser.java new file mode 100644 index 0000000000..6602cb89e5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationUser.java @@ -0,0 +1,16 @@ +package com.gregtechceu.gtceu.api.capability.data; + +/** + * Used for {@link gregtech.api.capability.impl.ComputationRecipeLogic} + */ +public interface IComputationUser { + + /** + * Called to request CWU for recipe logic. + * + * @param requested the requested CWU + * @param simulate whether to simulate the request + * @return the amount of CWU supplied. + */ + long requestCWU(long requested, boolean simulate); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java new file mode 100644 index 0000000000..9c29568da9 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java @@ -0,0 +1,52 @@ +package com.gregtechceu.gtceu.api.capability.data; + +import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; +import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; +import org.jetbrains.annotations.NotNull; + +public interface IDataAccess { + + /** + * Queries this {@link IDataAccess} with the specified query. + * + * @param queryObject the object representing the query. Can be cached in a weak set created by + * {@link com.gregtechceu.gtceu.utils.GTUtil#createWeakHashSet()} in order to prevent endless recursion. + * @return if the query has been cancelled + */ + boolean accessData(@NotNull DataQueryObject queryObject); + + /** + * @return the {@link DataAccessFormat} this {@link IDataAccess} uses. + */ + @NotNull + DataAccessFormat getFormat(); + + /** + * @param queryObject a query object + * @return whether this {@link IDataAccess} supports the query object. + */ + default boolean supportsQuery(@NotNull DataQueryObject queryObject) { + return getFormat().supportsFormat(queryObject.getFormat()); + } + + /** + * Provides standardized logic for querying a collection of {@link IDataAccess}es. + * + * @param accesses the {@link IDataAccess}es to query. + * @param query the object representing the query. + * @return if the query has been cancelled + */ + static boolean accessData(@NotNull Iterable accesses, + @NotNull DataQueryObject query) { + boolean walk = false; + boolean cancelled = false; + for (IDataAccess access : accesses) { + query.setShouldTriggerWalker(false); + cancelled = access.accessData(query); + if (!walk) walk = query.shouldTriggerWalker(); + if (cancelled) break; + } + query.setShouldTriggerWalker(walk); + return cancelled; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IHatchDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IHatchDataAccess.java new file mode 100644 index 0000000000..91e5a0b227 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IHatchDataAccess.java @@ -0,0 +1,9 @@ +package com.gregtechceu.gtceu.api.capability.data; + +public interface IHatchDataAccess extends IDataAccess { + + /** + * @return if this hatch transmits data through cables + */ + boolean isTransmitter(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java new file mode 100644 index 0000000000..d8627d87ee --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java @@ -0,0 +1,12 @@ +package com.gregtechceu.gtceu.api.capability.data; + +import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; +import org.jetbrains.annotations.NotNull; + +public interface IStandardDataAccess extends IHatchDataAccess { + + @Override + default @NotNull DataAccessFormat getFormat() { + return DataAccessFormat.STANDARD; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java new file mode 100644 index 0000000000..5a56f42de2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java @@ -0,0 +1,54 @@ +package com.gregtechceu.gtceu.api.capability.data.query; + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import net.minecraft.util.StringRepresentable; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.Set; + +public final class DataAccessFormat implements StringRepresentable { + + public static final DataAccessFormat STANDARD = create("gtceu.data_format.access.standard", + DataQueryFormat.RECIPE); + public static final DataAccessFormat COMPUTATION = create("gtceu.data_format.access.computation", + DataQueryFormat.COMPUTATION); + + public static final DataAccessFormat UNIVERSAL = new DataAccessFormat("gtceu.data_format.access.universal", + null); + + private final Set supportedFormats; + + public static DataAccessFormat create(@NotNull String name, DataQueryFormat... allowedFormats) { + return new DataAccessFormat(name, new ObjectOpenHashSet<>(allowedFormats)); + } + + private final @NotNull String name; + + private DataAccessFormat(@NotNull String name, Set supportedFormats) { + this.name = name; + this.supportedFormats = supportedFormats; + } + + @Override + public @NotNull String getSerializedName() { + return name; + } + + @Contract("_ -> this") + public DataAccessFormat support(DataQueryFormat format) { + if (supportedFormats != null) this.supportedFormats.add(format); + return this; + } + + @Contract("_ -> this") + public DataAccessFormat notSupport(DataQueryFormat format) { + if (supportedFormats != null) this.supportedFormats.remove(format); + return this; + } + + public boolean supportsFormat(DataQueryFormat format) { + if (supportedFormats == null) return true; + else return supportedFormats.contains(format); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java new file mode 100644 index 0000000000..538f26a63c --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java @@ -0,0 +1,25 @@ +package com.gregtechceu.gtceu.api.capability.data.query; + +import net.minecraft.util.StringRepresentable; +import org.jetbrains.annotations.NotNull; + +public final class DataQueryFormat implements StringRepresentable { + + public static final DataQueryFormat RECIPE = create("gtceu.data_format.query.recipe"); + public static final DataQueryFormat COMPUTATION = create("gtceu.data_format.query.computation"); + + public static DataQueryFormat create(@NotNull String name) { + return new DataQueryFormat(name); + } + + private final @NotNull String name; + + private DataQueryFormat(@NotNull String name) { + this.name = name; + } + + @Override + public @NotNull String getSerializedName() { + return name; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java new file mode 100644 index 0000000000..b11063de9e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java @@ -0,0 +1,32 @@ +package com.gregtechceu.gtceu.api.capability.data.query; + +import org.jetbrains.annotations.NotNull; + +public abstract class DataQueryObject { + + private static int ID = 0; + + private final int id; + + private boolean shouldTriggerWalker = false; + + public DataQueryObject() { + this.id = ID++; + } + + public void setShouldTriggerWalker(boolean shouldTriggerWalker) { + this.shouldTriggerWalker = shouldTriggerWalker; + } + + public boolean shouldTriggerWalker() { + return shouldTriggerWalker; + } + + @NotNull + public abstract DataQueryFormat getFormat(); + + @Override + public int hashCode() { + return id; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IBridgeable.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IBridgeable.java new file mode 100644 index 0000000000..6747257a32 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IBridgeable.java @@ -0,0 +1,9 @@ +package com.gregtechceu.gtceu.api.capability.data.query; + +public interface IBridgeable { + + /** + * Called when a query has traversed a multiblock with more than one reception point and continued onward. + */ + void setBridged(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java new file mode 100644 index 0000000000..83c81e6493 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java @@ -0,0 +1,31 @@ +package com.gregtechceu.gtceu.api.capability.data.query; + +import com.gregtechceu.gtceu.api.recipe.GTRecipe; +import lombok.Getter; +import org.jetbrains.annotations.NotNull; + +public class RecipeDataQuery extends DataQueryObject { + + @Getter + private final GTRecipe recipe; + + private boolean found = false; + + public RecipeDataQuery(GTRecipe recipe) { + this.recipe = recipe; + } + + @Override + public @NotNull DataQueryFormat getFormat() { + return DataQueryFormat.RECIPE; + } + + public void setFound() { + this.found = true; + this.setShouldTriggerWalker(true); + } + + public boolean isFound() { + return found; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java b/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java index 89535cd5ca..8bc5d33459 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.capability.forge; import com.gregtechceu.gtceu.api.capability.*; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMaintenanceMachine; import com.gregtechceu.gtceu.api.machine.trait.RecipeLogic; @@ -33,11 +34,11 @@ public class GTCapability { .get(new CapabilityToken<>() {}); public static final Capability CAPABILITY_MAINTENANCE_MACHINE = CapabilityManager .get(new CapabilityToken<>() {}); - public static final Capability CAPABILITY_LASER = CapabilityManager + public static final Capability CAPABILITY_LASER = CapabilityManager .get(new CapabilityToken<>() {}); public static final Capability CAPABILITY_COMPUTATION_PROVIDER = CapabilityManager .get(new CapabilityToken<>() {}); - public static final Capability CAPABILITY_DATA_ACCESS = CapabilityManager + public static final Capability CAPABILITY_DATA_ACCESS = CapabilityManager .get(new CapabilityToken<>() {}); public static final Capability CAPABILITY_HAZARD_CONTAINER = CapabilityManager .get(new CapabilityToken<>() {}); @@ -56,9 +57,9 @@ public static void register(RegisterCapabilitiesEvent event) { event.register(IElectricItem.class); event.register(ICleanroomReceiver.class); event.register(IMaintenanceMachine.class); - event.register(ILaserContainer.class); + event.register(ILaserRelay.class); event.register(IOpticalComputationProvider.class); - event.register(IDataAccessHatch.class); + event.register(IDataAccess.class); event.register(IMedicalConditionTracker.class); event.register(IHazardParticleContainer.class); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java index a97ab05f7c..f0e84e5c62 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java @@ -23,4 +23,6 @@ public interface Filter> extends Predicate { default boolean isBlackList() { return false; } + + default void setBlackList(boolean blackList) {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java index 8c59307724..a1fcd32b17 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java @@ -41,6 +41,10 @@ default boolean supportsAmounts() { return !isBlackList(); } + default int getMaxStackSize() { + return 1; + } + /** * An empty item filter that allows all items.
* ONLY TO BE USED FOR ITEM MATCHING! All other functionality will throw an exception. diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java index 1c33883a8b..85c8a36fcd 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java @@ -8,6 +8,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; @@ -57,7 +58,7 @@ public boolean generatesStructure(IPipeStructure structure) { } @Override - public @NotNull Collection getOrCreateFromNets(LevelAccessor level, BlockPos pos, + public @NotNull Collection getOrCreateFromNets(ServerLevel level, BlockPos pos, IPipeStructure structure) { List list = new ObjectArrayList<>(); for (IPipeNetMaterialProperty p : properties.values()) { @@ -70,7 +71,7 @@ public boolean generatesStructure(IPipeStructure structure) { } @Override - public @NotNull Collection getFromNets(LevelAccessor level, BlockPos pos, + public @NotNull Collection getFromNets(ServerLevel level, BlockPos pos, IPipeStructure structure) { List list = new ObjectArrayList<>(); for (IPipeNetMaterialProperty p : properties.values()) { @@ -83,7 +84,7 @@ public boolean generatesStructure(IPipeStructure structure) { } @Override - public void removeFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure) { + public void removeFromNets(ServerLevel level, BlockPos pos, IPipeStructure structure) { for (IPipeNetMaterialProperty p : properties.values()) { if (p.supportsStructure(structure)) p.removeFromNet(level, pos, structure); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java index 3c59fe7f63..4f59b2be57 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java @@ -59,7 +59,7 @@ public void addNode(NetNode node) { GraphVertex vertex = new GraphVertex(node); getGraph().addVertex(vertex); this.vertexMap.put(node.getEquivalencyData(), vertex); - backedNet.markDirty(); + backedNet.setDirty(); } @Nullable @@ -82,7 +82,7 @@ public boolean removeNode(@Nullable NetNode node) { if (group != null) { group.splitNode(node); } else this.removeVertex(node.wrapper); - backedNet.markDirty(); + backedNet.setDirty(); return true; } else return false; } @@ -92,7 +92,7 @@ public void removeVertex(GraphVertex vertex) { if (this.getGraph().removeVertex(vertex)) { this.vertexMap.remove(vertex.wrapped.getEquivalencyData()); vertex.wrapped.onRemove(); - backedNet.markDirty(); + backedNet.setDirty(); } } @@ -103,7 +103,7 @@ public NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, double if (graphEdge != null) { getGraph().setEdgeWeight(graphEdge, weight); NetGroup.mergeEdge(source, target); - backedNet.markDirty(); + backedNet.setDirty(); } return graphEdge == null ? null : graphEdge.wrapped; } @@ -126,7 +126,7 @@ public boolean removeEdge(@NotNull NetNode source, NetNode target) { public GraphEdge removeEdge(GraphVertex source, GraphVertex target) { GraphEdge edge = this.getGraph().removeEdge(source, target); if (edge != null) { - backedNet.markDirty(); + backedNet.setDirty(); } return edge; } @@ -134,7 +134,7 @@ public GraphEdge removeEdge(GraphVertex source, GraphVertex target) { @ApiStatus.Internal public boolean removeEdge(GraphEdge edge) { if (this.getGraph().removeEdge(edge)) { - backedNet.markDirty(); + backedNet.setDirty(); return true; } return false; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java index e62db59e7a..1c14c54f20 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java @@ -209,5 +209,5 @@ default NetEdge getNewEdge() { * Should only be used by the internal {@link GraphNetBacker} backing this graphnet. */ @ApiStatus.Internal - void markDirty(); + void setDirty(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java index 6e5852f6a7..fc1f2d37a1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java @@ -4,6 +4,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; @@ -17,12 +18,12 @@ public interface IPipeNetNodeHandler { @NotNull - Collection getOrCreateFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure); + Collection getOrCreateFromNets(ServerLevel level, BlockPos pos, IPipeStructure structure); @NotNull - Collection getFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure); + Collection getFromNets(ServerLevel level, BlockPos pos, IPipeStructure structure); - void removeFromNets(LevelAccessor level, BlockPos pos, IPipeStructure structure); + void removeFromNets(ServerLevel level, BlockPos pos, IPipeStructure structure); void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, @NotNull TooltipFlag flagIn, diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index 51606dc35e..b736543a8e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -40,13 +40,13 @@ public abstract class WorldPipeNet extends WorldNet { private static final Object2ObjectOpenHashMap, Set> dimensionNets = new Object2ObjectOpenHashMap<>(); - public WorldPipeNet(String name, Function graphBuilder, + public WorldPipeNet(Function graphBuilder, AlgorithmBuilder... algorithmBuilders) { - super(name, graphBuilder, algorithmBuilders); + super(graphBuilder, algorithmBuilders); } - public WorldPipeNet(String name, boolean directed, AlgorithmBuilder... algorithmBuilders) { - super(name, directed, algorithmBuilders); + public WorldPipeNet(boolean directed, AlgorithmBuilder... algorithmBuilders) { + super(directed, algorithmBuilders); } @Override @@ -83,7 +83,7 @@ protected void updatePredicationInternal(@NotNull WorldPipeNetNode node, @NotNul dirty |= predicateEdge(edge, node, tile.getCoverHolder().getCoverAtSide(facing), neighborNode, neighbor.getCoverHolder().getCoverAtSide(facing.getOpposite())); } - if (dirty) markDirty(); + if (dirty) this.setDirty(); } /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java index 3af9762fd3..b25c99491f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -1,10 +1,14 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet; +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.IWorldPipeNetTile; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNetNode; +import com.gregtechceu.gtceu.common.data.GTBlockEntities; +import com.gregtechceu.gtceu.common.data.GTBlocks; +import com.gregtechceu.gtceu.common.data.GTMaterials; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; @@ -16,7 +20,8 @@ public final class WorldPipeNetNode extends WorldNetNode { - private static final PipeBlockEntity FALLBACK = new PipeBlockEntity(); + private static final PipeBlockEntity FALLBACK = new PipeBlockEntity(GTBlockEntities.NEW_PIPE.get(), BlockPos.ZERO, + GTBlocks.ITEM_PIPE_BLOCKS.get(TagPrefix.pipeNormalItem, GTMaterials.Aluminium).getDefaultState()); @Nullable MultiNodeHelper overlapHelper; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java index e1d1ca323e..706ddfc421 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeMaterialStructure.java @@ -4,5 +4,5 @@ public interface IPipeMaterialStructure extends IPipeStructure { - TagPrefix getTagPrefix(); + TagPrefix getPrefix(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index 5003cbd81f..8b7cc3e235 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -22,6 +22,6 @@ public MaterialPipeBlockItem(Item.Properties properties, PipeMaterialBlock block @Override public Component getName(ItemStack stack) { Material material = getBlock().material; - return material == null ? Component.literal("unnamed") : getBlock().getStructure().getTagPrefix().getLocalizedName(material); + return material == null ? Component.literal("unnamed") : getBlock().getStructure().getPrefix().getLocalizedName(material); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 0deffae4ba..660be46111 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -28,6 +28,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; @@ -68,7 +69,7 @@ import java.lang.ref.WeakReference; import java.util.*; -public abstract class PipeBlock extends Block implements EntityBlock, IBlockRendererProvider { +public abstract class PipeBlock extends Block implements EntityBlock { public static final BooleanProperty NORTH = BooleanProperty.create("north"); public static final BooleanProperty EAST = BooleanProperty.create("east"); @@ -330,16 +331,16 @@ protected boolean allowsBlocking() { } public static Collection getNodesForTile(PipeBlockEntity tile) { - assert !tile.getLevel().isClientSide; + assert tile.getLevel() instanceof ServerLevel; return tile.getBlockType().getHandler(tile.getLevel(), tile.getBlockPos()) - .getOrCreateFromNets(tile.getLevel(), tile.getBlockPos(), tile.getStructure()); + .getOrCreateFromNets((ServerLevel) tile.getLevel(), tile.getBlockPos(), tile.getStructure()); } @Override public void destroy(LevelAccessor level, BlockPos pos, BlockState state) { super.destroy(level, pos, state); - if (!level.isClientSide()) { - getHandler(level, pos).removeFromNets(level, pos, getStructure()); + if (level instanceof ServerLevel serverLevel) { + getHandler(level, pos).removeFromNets(serverLevel, pos, getStructure()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index fee31966aa..79a140a03f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -59,7 +59,7 @@ public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List writeCustomData(UPDATE_PIPE_LOGIC, buf -> { buf.writeVarInt(networkID); - buf.writeString(e.getName()); + buf.writeUtf(e.getSerializedName()); buf.writeBoolean(r); buf.writeBoolean(f); if (!r) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java index 5fe4eb1319..9ff59262de 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -83,7 +83,9 @@ public boolean removeCover(boolean dropItself, Direction side, @Nullable Player return ICoverable.super.removeCover(side, player); } + @Override public void onLoad() { + ICoverable.super.onLoad(); for (Direction side : GTUtil.DIRECTIONS) { this.sidedRedstoneInput[side.get3DDataValue()] = GTUtil.getRedstonePower(getLevel(), getPos(), side); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java index 5c02567f92..598c394bbd 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -37,13 +37,13 @@ public abstract class WorldNet extends SavedData implements IGraphNet, GenericGr private Level level; private ResourceKey fallbackDimension; - public WorldNet(String name, @NotNull Function graphBuilder, + public WorldNet(@NotNull Function graphBuilder, AlgorithmBuilder... algorithmBuilders) { this.backer = new GraphNetBacker(this, graphBuilder.apply(this), algorithmBuilders); } - public WorldNet(String name, boolean directed, AlgorithmBuilder... algorithmBuilders) { - this(name, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), + public WorldNet(boolean directed, AlgorithmBuilder... algorithmBuilders) { + this(directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), algorithmBuilders); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java index 0f59590c2c..44e5478437 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.machine; import com.gregtechceu.gtceu.api.block.IMachineBlock; +import com.gregtechceu.gtceu.api.blockentity.INeighborCache; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.common.machine.owner.IMachineOwner; @@ -20,7 +21,7 @@ * Also delivers most of the Information about TileEntities. */ public interface IMachineBlockEntity extends IToolGridHighLight, IAsyncAutoSyncBlockEntity, IRPCBlockEntity, - IAutoPersistBlockEntity { + IAutoPersistBlockEntity, INeighborCache { default BlockEntity self() { return (BlockEntity) this; diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java index 78c122c0eb..f5847db34e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java @@ -23,9 +23,13 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.shapes.VoxelShape; import lombok.Getter; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -49,6 +53,8 @@ public class MachineCoverContainer implements ICoverable, IEnhancedManaged { deserializeMethod = "deserializeCoverUid") private CoverBehavior up, down, north, south, west, east; + private final int[] sidedRedstoneInput = new int[6]; + public MachineCoverContainer(MetaMachine machine) { this.machine = machine; } @@ -73,6 +79,14 @@ public void onChanged() { } } + @Override + public void onLoad() { + ICoverable.super.onLoad(); + for (Direction side : GTUtil.DIRECTIONS) { + this.sidedRedstoneInput[side.get3DDataValue()] = GTUtil.getRedstonePower(getLevel(), getPos(), side); + } + } + @Override public Level getLevel() { return machine.getLevel(); @@ -126,6 +140,11 @@ public boolean canPlaceCoverOnSide(CoverDefinition definition, Direction side) { return true; } + @Override + public boolean acceptsCovers() { + return up == null || down == null || north == null || south == null || west == null || east == null; + } + @Override public double getCoverPlateThickness() { return 0; @@ -164,6 +183,34 @@ public CoverBehavior getCoverAtSide(Direction side) { }; } + @Override + public @Nullable BlockEntity getNeighbor(@NotNull Direction side) { + return machine.getNeighbor(side); + } + + @Override + public int getInputRedstoneSignal(@NotNull Direction side, boolean ignoreCover) { + if (!ignoreCover && getCoverAtSide(side) != null) { + return 0; // covers block input redstone signal for machine + } + return sidedRedstoneInput[side.get3DDataValue()]; + } + + public void updateInputRedstoneSignals() { + for (Direction side : GTUtil.DIRECTIONS) { + int redstoneValue = GTUtil.getRedstonePower(getLevel(), getPos(), side); + int currentValue = sidedRedstoneInput[side.get3DDataValue()]; + if (redstoneValue != currentValue) { + this.sidedRedstoneInput[side.get3DDataValue()] = redstoneValue; + CoverBehavior cover = getCoverAtSide(side); + if (cover != null) { + cover.onRedstoneInputSignalChange(redstoneValue); + } + } + } + } + + @Override public void setCoverAtSide(@Nullable CoverBehavior coverBehavior, Direction side) { switch (side) { @@ -220,4 +267,10 @@ private CoverBehavior deserializeCoverUid(CompoundTag uid) { GTCEu.LOGGER.error("couldn't find cover definition {}", definitionId); throw new RuntimeException(); } + + @Override + public @NotNull LazyOptional getCapability(@NotNull Capability capability, @Nullable Direction arg) { + // FIXME + return LazyOptional.empty(); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/MetaMachine.java b/src/main/java/com/gregtechceu/gtceu/api/machine/MetaMachine.java index abdf3fbd3e..6244f8c5a5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/MetaMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/MetaMachine.java @@ -57,6 +57,7 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.Shapes; @@ -179,6 +180,10 @@ public long getOffsetTimer() { return holder.getOffsetTimer(); } + public @Nullable BlockEntity getNeighbor(@NotNull Direction side) { + return holder.getNeighbor(side); + } + public void markDirty() { holder.getSelf().setChanged(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/feature/multiblock/IMultiPart.java b/src/main/java/com/gregtechceu/gtceu/api/machine/feature/multiblock/IMultiPart.java index fd65c979f5..b6526ffbf0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/feature/multiblock/IMultiPart.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/feature/multiblock/IMultiPart.java @@ -122,6 +122,7 @@ default boolean beforeWorking(IWorkableMultiController controller) { * @return modified recipe. * null -- this recipe is unavailable */ + @Nullable default GTRecipe modifyRecipe(GTRecipe recipe) { return recipe; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableEnergyContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableEnergyContainer.java index 21e0770f46..54339410b9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableEnergyContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableEnergyContainer.java @@ -172,7 +172,7 @@ public void serverTick() { machine.getPos().relative(side), oppositeSide); if (energyContainer != null && energyContainer.inputsEnergy(oppositeSide)) { amperesUsed += energyContainer.acceptEnergyFromNetwork(oppositeSide, outputVoltage, - outputAmperes - amperesUsed); + outputAmperes - amperesUsed, false); if (amperesUsed == outputAmperes) break; } } @@ -255,7 +255,7 @@ private boolean handleForgeEnergyItem(IEnergyStorage energyStorage, boolean simu } @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { var latestTimeStamp = getMachine().getOffsetTimer(); if (lastTimeStamp < latestTimeStamp) { amps = 0; diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableLaserContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableLaserContainer.java index b1e65e8fb1..21767ad2c6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableLaserContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableLaserContainer.java @@ -2,7 +2,9 @@ import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ILaserContainer; +import com.gregtechceu.gtceu.api.capability.ILaserRelay; import com.gregtechceu.gtceu.api.machine.MetaMachine; +import com.gregtechceu.gtceu.api.machine.feature.IExplosionMachine; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; @@ -45,11 +47,10 @@ public void serverTick() { if (!outputsEnergy(side)) continue; BlockEntity tileEntity = getMachine().getLevel().getBlockEntity(getMachine().getPos().relative(side)); Direction oppositeSide = side.getOpposite(); - ILaserContainer laserContainer = GTCapabilityHelper.getLaser(getMachine().getLevel(), + ILaserRelay laserContainer = GTCapabilityHelper.getLaser(getMachine().getLevel(), getMachine().getPos().relative(side), oppositeSide); if (tileEntity != null && laserContainer != null) { - if (laserContainer == null || !laserContainer.inputsEnergy(oppositeSide)) continue; - amperesUsed += laserContainer.acceptEnergyFromNetwork(oppositeSide, outputVoltage, + amperesUsed += laserContainer.receiveLaser(outputVoltage, outputAmperes - amperesUsed); if (amperesUsed == outputAmperes) break; } @@ -58,4 +59,15 @@ public void serverTick() { setEnergyStored(getEnergyStored() - amperesUsed * outputVoltage); } } + + @Override + public long receiveLaser(long laserVoltage, long laserAmperage) { + if (getInputVoltage() == 0) return 0; + long allowedAmps = getEnergyCanBeInserted() / laserVoltage; + addEnergy(laserVoltage * allowedAmps); + // over voltage explosion + if (laserVoltage > getInputVoltage() && getMachine() instanceof IExplosionMachine explosionMachine) + explosionMachine.doExplosion(GTUtil.getExplosionPower(laserVoltage)); + return allowedAmps; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/misc/EnergyContainerList.java b/src/main/java/com/gregtechceu/gtceu/api/misc/EnergyContainerList.java index f4b0c6c0aa..d2462854c3 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/misc/EnergyContainerList.java +++ b/src/main/java/com/gregtechceu/gtceu/api/misc/EnergyContainerList.java @@ -131,11 +131,11 @@ private static boolean isPowerOfFour(long l) { } @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { long amperesUsed = 0L; List energyContainerList = this.energyContainerList; for (IEnergyContainer iEnergyContainer : energyContainerList) { - amperesUsed += iEnergyContainer.acceptEnergyFromNetwork(null, voltage, amperage); + amperesUsed += iEnergyContainer.acceptEnergyFromNetwork(null, voltage, amperage, simulate); if (amperage == amperesUsed) { return amperesUsed; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java b/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java index 210a52d848..d31f38b863 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java +++ b/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java @@ -15,11 +15,11 @@ public LaserContainerList(List energyContainerList) { } @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { long amperesUsed = 0L; List energyContainerList = this.energyContainerList; for (ILaserContainer iEnergyContainer : energyContainerList) { - amperesUsed += iEnergyContainer.acceptEnergyFromNetwork(null, voltage, amperage); + amperesUsed += iEnergyContainer.acceptEnergyFromNetwork(null, voltage, amperage, false); if (amperage == amperesUsed) { return amperesUsed; } diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index 336acbcfc7..3d8763a93c 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -10,6 +10,8 @@ import com.gregtechceu.gtceu.client.particle.HazardParticle; import com.gregtechceu.gtceu.client.renderer.entity.GTBoatRenderer; import com.gregtechceu.gtceu.client.renderer.entity.GTExplosiveRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; import com.gregtechceu.gtceu.common.CommonProxy; import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTEntityTypes; @@ -28,11 +30,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.client.event.EntityRenderersEvent; -import net.minecraftforge.client.event.RegisterGuiOverlaysEvent; -import net.minecraftforge.client.event.RegisterKeyMappingsEvent; -import net.minecraftforge.client.event.RegisterParticleProvidersEvent; +import net.minecraftforge.client.event.*; import net.minecraftforge.eventbus.api.SubscribeEvent; import com.google.common.collect.BiMap; @@ -94,4 +92,10 @@ public void onRegisterGuiOverlays(RegisterGuiOverlaysEvent event) { public void onRegisterParticleProviders(RegisterParticleProvidersEvent event) { event.registerSpriteSet(GTParticleTypes.HAZARD_PARTICLE.get(), HazardParticle.Provider::new); } + + @SubscribeEvent + public void registerModifiedModels(ModelEvent.ModifyBakingResult event) { + ActivablePipeModel.registerModels(event.getModels()::put); + CableModel.registerModels(event.getModels()::put); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index 9747a31b7e..c89a61546b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -66,6 +66,11 @@ public AbstractPipeModel(ModelResourceLocation loc) { this.loc = loc; } + @Override + public List getQuads(@Nullable BlockState state, @Nullable Direction direction, RandomSource random) { + return List.of(); + } + @Override public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData modelData, @@ -160,7 +165,7 @@ public TextureAtlasSprite getParticleTexture(int paintColor, @Nullable Material @Override public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { - return BakedModel.super.getParticleIcon(data); + return getParticleTexture(data.get(COLOR_PROPERTY), data.get(MATERIAL_PROPERTY)); } public abstract SpriteInformation getParticleSprite(@Nullable Material material); @@ -180,6 +185,16 @@ public boolean isCustomRenderer() { return false; } + @Override + public boolean usesBlockLight() { + return true; + } + + @Override + public TextureAtlasSprite getParticleIcon() { + return getParticleSprite(null).sprite(); + } + @Nullable protected abstract PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java index dd154830e6..0d08749393 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -11,20 +11,19 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.config.ConfigHolder; +import com.gregtechceu.gtceu.utils.SupplierMemoizer; import com.lowdragmc.lowdraglib.client.bakedpipeline.Quad; -import com.lowdragmc.lowdraglib.client.utils.RenderUtils; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.model.data.ModelProperty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -41,29 +40,38 @@ public class ActivablePipeModel extends AbstractPipeModel { public static final ModelProperty ACTIVE_PROPERTY = new ModelProperty<>(); - public static final ActivablePipeModel OPTICAL = new ActivablePipeModel(Textures.OPTICAL_PIPE_IN, - Textures.OPTICAL_PIPE_SIDE, Textures.OPTICAL_PIPE_SIDE_OVERLAY, Textures.OPTICAL_PIPE_SIDE_OVERLAY_ACTIVE, + public static final ActivablePipeModel OPTICAL = new ActivablePipeModel(() -> GTCEu.id("block/pipe/pipe_optical_in"), + () -> GTCEu.id("block/pipe/pipe_optical_side"), + () -> GTCEu.id("block/pipe/pipe_optical_side_overlay"), + () -> GTCEu.id("block/pipe/pipe_optical_side_overlay_active"), false, "optical"); - public static final ActivablePipeModel LASER = new ActivablePipeModel(Textures.LASER_PIPE_IN, - Textures.LASER_PIPE_SIDE, Textures.LASER_PIPE_OVERLAY, Textures.LASER_PIPE_OVERLAY_EMISSIVE, + public static final ActivablePipeModel LASER = new ActivablePipeModel(() -> GTCEu.id("block/pipe/pipe_laser_in"), + () -> GTCEu.id("block/pipe/pipe_laser_side"), + () -> GTCEu.id("block/pipe/pipe_laser_side_overlay"), + () -> GTCEu.id("block/pipe/pipe_laser_side_overlay_emissive"), true, "laser"); - private final Supplier inTex; - private final Supplier sideTex; - private final Supplier overlayTex; - private final Supplier overlayActiveTex; + private final SupplierMemoizer.MemoizedSupplier inTex; + private final SupplierMemoizer.MemoizedSupplier sideTex; + private final SupplierMemoizer.MemoizedSupplier overlayTex; + private final SupplierMemoizer.MemoizedSupplier overlayActiveTex; + + private SpriteInformation inSprite; + private SpriteInformation sideSprite; + private SpriteInformation overlaySprite; + private SpriteInformation overlayActiveSprite; private final boolean emissiveActive; - public ActivablePipeModel(@NotNull Supplier inTex, @NotNull Supplier sideTex, - @NotNull Supplier overlayTex, - @NotNull Supplier overlayActiveTex, boolean emissiveActive, + public ActivablePipeModel(@NotNull Supplier inTex, @NotNull Supplier sideTex, + @NotNull Supplier overlayTex, + @NotNull Supplier overlayActiveTex, boolean emissiveActive, String variant) { super(new ModelResourceLocation(loc, variant)); - this.inTex = inTex; - this.sideTex = sideTex; - this.overlayTex = overlayTex; - this.overlayActiveTex = overlayActiveTex; + this.inTex = SupplierMemoizer.memoize(inTex); + this.sideTex = SupplierMemoizer.memoize(sideTex); + this.overlayTex = SupplierMemoizer.memoize(overlayTex); + this.overlayActiveTex = SupplierMemoizer.memoize(overlayActiveTex); this.emissiveActive = emissiveActive; } @@ -90,19 +98,32 @@ public ActivablePipeModel(@NotNull Supplier inTex, @NotNull S } @Override - public SpriteInformation getParticleSprite(@Nullable Material material) { - return sideTex.get(); + protected @NotNull ActivableCacheKey toKey(@NotNull ModelData state) { + return ActivableCacheKey.of(state.get(THICKNESS_PROPERTY), state.get(ACTIVE_PROPERTY)); } @Override - public @NotNull TextureAtlasSprite getParticleTexture() { - return getParticleSprite(null).sprite(); + public SpriteInformation getParticleSprite(@Nullable Material material) { + return sideSprite; } @Override protected StructureQuadCache constructForKey(ActivableCacheKey key) { - return ActivableSQC.create(PipeQuadHelper.create(key.getThickness()), inTex.get(), sideTex.get(), - overlayTex.get(), overlayActiveTex.get()); + if (inSprite == null && inTex != null) { + inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex.get()), -1); + } + if (sideSprite == null && sideTex != null) { + sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex.get()), -1); + } + if (overlaySprite == null && overlayTex != null) { + overlaySprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayTex.get()), 0); + } + if (overlayActiveSprite == null && overlayActiveTex != null) { + overlayActiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayActiveTex.get()), 0); + } + + return ActivableSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, sideSprite, + overlaySprite, overlayActiveSprite); } public boolean allowActive() { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java new file mode 100644 index 0000000000..f0c1126865 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java @@ -0,0 +1,147 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconSet; +import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.ExtraCappedSQC; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.gregtechceu.gtceu.utils.SupplierMemoizer; +import com.lowdragmc.lowdraglib.client.model.ModelFactory; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelData; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +public class CableModel extends AbstractPipeModel { + + public static final int DEFAULT_INSULATION_COLOR = 0xFF404040; + + private static final ResourceLocation loc = GTCEu.id("block/cable"); + + public static final CableModel INSTANCE = new CableModel("wire"); + public static final CableModel[] INSULATED_INSTANCES = new CableModel[5]; + + + @OnlyIn(Dist.CLIENT) + public static final Supplier WIRE = () -> MaterialIconType.wire + .getBlockTexturePath(MaterialIconSet.DULL, true).withSuffix("_side"); + @OnlyIn(Dist.CLIENT) + public static final Supplier INSULATION_FULL = () -> GTCEu.id("block/cable/insulation_5"); + + static { + for (int i = 0; i < INSULATED_INSTANCES.length; i++) { + final int finalI = i; + INSULATED_INSTANCES[i] = new CableModel(() -> GTCEu.id("block/cable/insulation_%s".formatted(finalI)), + INSULATION_FULL, "insulated_" + i); + } + } + + private final SupplierMemoizer.MemoizedSupplier wireTex; + private final SupplierMemoizer.MemoizedSupplier insulationTex; + private final SupplierMemoizer.MemoizedSupplier fullInsulationTex; + + private SpriteInformation wireSprite; + private SpriteInformation insulationSprite; + private SpriteInformation fullInsulationSprite; + + public CableModel(@NotNull Supplier wireTex, @Nullable Supplier insulationTex, + @Nullable Supplier fullInsulationTex, String variant) { + super(new ModelResourceLocation(loc, variant)); + this.wireTex = SupplierMemoizer.memoize(wireTex); + this.insulationTex = SupplierMemoizer.memoize(insulationTex); + this.fullInsulationTex = SupplierMemoizer.memoize(fullInsulationTex); + } + + public CableModel(@Nullable Supplier insulationTex, + @Nullable Supplier fullInsulationTex, String variant) { + this(WIRE, insulationTex, fullInsulationTex, variant); + } + + public CableModel(String variant) { + this(null, null, variant); + } + + @Override + protected ColorData computeColorData(@NotNull ModelData ext) { + if (insulationTex == null) return super.computeColorData(ext); + Material material = ext.get(AbstractPipeModel.MATERIAL_PROPERTY); + int insulationColor = safeInt(ext.get(COLOR_PROPERTY)); + if (material != null) { + int matColor = GTUtil.convertRGBtoARGB(material.getMaterialRGB()); + if (insulationColor == 0 || insulationColor == matColor) { + // unpainted + insulationColor = DEFAULT_INSULATION_COLOR; + } + return new ColorData(matColor, insulationColor); + } + return new ColorData(0, 0); + } + + @Override + public SpriteInformation getParticleSprite(@Nullable Material material) { + return wireSprite; + } + + @Override + protected @NotNull CacheKey toKey(@NotNull ModelData state) { + return defaultKey(state); + } + + @Override + protected StructureQuadCache constructForKey(CacheKey key) { + if (fullInsulationSprite == null && fullInsulationTex != null) { + fullInsulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(fullInsulationTex.get()), 1); + } + if (insulationSprite == null && insulationTex != null) { + insulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(insulationTex.get()), 1); + } + if (wireSprite == null && wireTex != null) { + wireSprite = new SpriteInformation(ModelFactory.getBlockSprite(wireTex.get()), 0); + } + + SpriteInformation sideTex = fullInsulationSprite != null ? fullInsulationSprite : wireSprite; + if (insulationSprite == null) { + return StructureQuadCache.create(PipeQuadHelper.create(key.getThickness()), wireSprite, sideTex); + } else { + return ExtraCappedSQC.create(PipeQuadHelper.create(key.getThickness()), wireSprite, sideTex, + insulationSprite); + } + } + + @Override + protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, + LivingEntity entity) { + PipeBlock block = PipeBlock.getBlockFromItem(stack); + if (block == null) return null; + Material mater = block instanceof PipeMaterialBlock mat ? mat.material : null; + return new PipeItemModel<>(this, new CacheKey(block.getStructure().getRenderThickness()), + new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : + PipeBlockEntity.DEFAULT_COLOR, DEFAULT_INSULATION_COLOR)); + } + + public static void registerModels(BiConsumer registry) { + registry.accept(INSTANCE.getLoc(), INSTANCE); + for (CableModel model : INSULATED_INSTANCES) { + registry.accept(model.getLoc(), model); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java new file mode 100644 index 0000000000..a858846864 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java @@ -0,0 +1,79 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cache; + +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import org.jetbrains.annotations.NotNull; + +import java.util.EnumMap; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public class ExtraCappedSQC extends StructureQuadCache { + + protected final EnumMap extraCapperCoords = new EnumMap<>(Direction.class); + + protected final SpriteInformation extraEndTex; + + protected ExtraCappedSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteInformation sideTex, + SpriteInformation extraEndTex) { + super(helper, endTex, sideTex); + this.extraEndTex = extraEndTex; + if (helper.getLayerCount() < 2) throw new IllegalStateException( + "Cannot create an ExtraCappedSQC without 2 or more layers present on the helper!"); + } + + public static @NotNull ExtraCappedSQC create(PipeQuadHelper helper, SpriteInformation endTex, + SpriteInformation sideTex, SpriteInformation extraEndTex) { + helper.initialize((facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.capOverlay(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_1)); + ExtraCappedSQC cache = new ExtraCappedSQC(helper, endTex, sideTex, extraEndTex); + cache.buildPrototype(); + return cache; + } + + @Override + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); + buildExtraCapper(quads); + return quads; + } + + protected void buildExtraCapper(List list) { + helper.setTargetSprite(extraEndTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.add(helper.visitCapper(facing, 1)); + extraCapperCoords.put(facing, new SubListAddress(start, list.size())); + } + } + + @Override + public void addToList(List list, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, + byte coverMask) { + List quads = cache.getQuads(data); + for (Direction facing : GTUtil.DIRECTIONS) { + if (GTUtil.evalMask(facing, connectionMask)) { + list.addAll(tubeCoords.get(facing).getSublist(quads)); + if (!GTUtil.evalMask(facing, coverMask)) { + if (GTUtil.evalMask(facing, closedMask)) { + list.addAll(capperClosedCoords.get(facing).getSublist(quads)); + } else { + list.addAll(capperCoords.get(facing).getSublist(quads)); + list.addAll(extraCapperCoords.get(facing).getSublist(quads)); + } + } + } else { + list.addAll(coreCoords.get(facing).getSublist(quads)); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java new file mode 100644 index 0000000000..5efe903e13 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java @@ -0,0 +1,36 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; + +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class SpriteInformationWrapper implements Supplier, Consumer, + BiConsumer { + + private SpriteInformation sprite; + + @Override + public void accept(TextureAtlasSprite sprite, Integer colorID) { + accept(new SpriteInformation(sprite, colorID)); + } + + @Override + public void accept(SpriteInformation spriteInformation) { + this.sprite = spriteInformation; + } + + @Override + public SpriteInformation get() { + return this.sprite; + } + + public static SpriteInformationWrapper[] array(int size) { + SpriteInformationWrapper[] array = new SpriteInformationWrapper[size]; + for (int i = 0; i < size; i++) { + array[i] = new SpriteInformationWrapper(); + } + return array; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java index 1d46782939..fdfbfd360e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java @@ -317,4 +317,14 @@ protected void read(CompoundTag compound, boolean clientPacket) { super.read(compound, clientPacket); workingSpeed = compound.contains("workingSpeed") ? compound.getFloat("workingSpeed") : 0; } + + @Override + public void onNeighborChanged(@NotNull Direction facing) { + + } + + @Override + public void markAsDirty() { + this.setChanged(); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java index 0d35e2cd4b..3101fbdd37 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java @@ -197,7 +197,7 @@ public ManagedFieldHolder getFieldHolder() { private static class DefaultLaserContainer implements ILaserContainer { @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { return 0; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java index d366aaea2e..a874ae5ff0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.capability.IDataAccessHatch; import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.pipenet.IPipeNode; @@ -40,7 +41,7 @@ public class OpticalPipeBlockEntity extends PipeBlockEntity handlers = new EnumMap<>(Direction.class); // the OpticalNetHandler can only be created on the server, so we have an empty placeholder for the client - private final IDataAccessHatch clientDataHandler = new DefaultDataHandler(); + private final IDataAccess clientDataHandler = new DefaultDataHandler(); private final IOpticalComputationProvider clientComputationHandler = new DefaultComputationHandler(); private WeakReference currentPipeNet = new WeakReference<>(null); private OpticalNetHandler defaultHandler; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java b/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java index 62c622a8e9..a8517d07c5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java @@ -50,7 +50,7 @@ protected void update() { if (GTUtil.canSeeSunClearly(level, blockPos)) { IEnergyContainer energyContainer = getEnergyContainer(); if (energyContainer != null) { - energyContainer.acceptEnergyFromNetwork(null, EUt, 1); + energyContainer.acceptEnergyFromNetwork(null, EUt, 1, false); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java index 89f8cddfba..15a046f158 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java @@ -1,10 +1,11 @@ package com.gregtechceu.gtceu.common.cover.filter; import com.gregtechceu.gtceu.api.blockentity.IDirtyNotifiable; -import com.gregtechceu.gtceu.api.cover.filter.Filter; +import com.gregtechceu.gtceu.api.cover.filter.ItemFilter; import com.lowdragmc.lowdraglib.misc.ItemStackTransfer; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -13,7 +14,7 @@ public abstract class BaseFilterContainer extends ItemStackTransfer { private int maxTransferSize = 1; private int transferSize; - private @Nullable Filter currentFilter; + private @Nullable ItemFilter currentFilter; private @Nullable Runnable onFilterInstanceChange; private final IDirtyNotifiable dirtyNotifiable; @@ -22,22 +23,22 @@ protected BaseFilterContainer(IDirtyNotifiable dirtyNotifiable) { this.dirtyNotifiable = dirtyNotifiable; } - public boolean test(Object toTest) { + public boolean test(ItemStack toTest) { return !hasFilter() || getFilter().test(toTest); } - public MatchResult match(Object toMatch) { + public boolean match(ItemStack toMatch) { if (!hasFilter()) - return MatchResult.create(true, toMatch, -1); + return true; - return getFilter().match(toMatch); + return getFilter().test(toMatch); } - public int getTransferLimit(Object stack) { + public int getTransferLimit(ItemStack stack) { if (!hasFilter() || isBlacklistFilter()) { return getTransferSize(); } - return getFilter().getTransferLimit(stack, getTransferSize()); + return getFilter().testItemCount(stack); } @Override @@ -62,13 +63,13 @@ public void setOnFilterInstanceChange(@Nullable Runnable onFilterInstanceChange) @Override public void setStackInSlot(int slot, @NotNull ItemStack stack) { - if (ItemStack.areItemStacksEqual(stack, getFilterStack())) + if (ItemStack.isSameItemSameTags(stack, getFilterStack())) return; if (stack.isEmpty()) { - setFilter(null); + setItemFilter(null); } else if (isItemValid(stack)) { - setFilter(BaseFilter.getFilterFromStack(stack)); + setItemFilter(ItemFilter.loadFilter(stack)); } super.setStackInSlot(slot, stack); @@ -87,7 +88,7 @@ public boolean isItemValid(int slot, @NotNull ItemStack stack) { public @NotNull ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { if (!isItemValid(stack)) return stack; var remainder = super.insertItem(slot, stack, simulate); - if (!simulate) setFilter(BaseFilter.getFilterFromStack(stack)); + if (!simulate) setItemFilter(ItemFilter.loadFilter(stack)); return remainder; } @@ -105,29 +106,29 @@ public final void setFilterStack(ItemStack stack) { } public int getMaxTransferSize() { - return !showGlobalTransferLimitSlider() && hasFilter() ? currentFilter.getMaxTransferSize() : + return !showGlobalTransferLimitSlider() && hasFilter() ? currentFilter.getMaxStackSize() : this.maxTransferSize; } public void setMaxTransferSize(int maxTransferSize) { - this.maxTransferSize = MathHelper.clamp(maxTransferSize, 1, Integer.MAX_VALUE); - this.transferSize = MathHelper.clamp(this.transferSize, 1, this.maxTransferSize); - if (hasFilter()) currentFilter.setMaxTransferSize(this.maxTransferSize); + this.maxTransferSize = Mth.clamp(maxTransferSize, 1, Integer.MAX_VALUE); + this.transferSize = Mth.clamp(this.transferSize, 1, this.maxTransferSize); + //if (hasFilter()) currentFilter.setMaxTransferSize(this.maxTransferSize); } public final boolean hasFilter() { return currentFilter != null; } - public final @Nullable Filter getFilter() { + public final @Nullable ItemFilter getFilter() { return currentFilter; } - public final void setFilter(@Nullable Filter newFilter) { + public final void setItemFilter(@Nullable ItemFilter newFilter) { this.currentFilter = newFilter; if (hasFilter()) { - this.currentFilter.setDirtyNotifiable(this.dirtyNotifiable); - this.currentFilter.setMaxTransferSize(this.maxTransferSize); + this.currentFilter.setOnUpdated($ -> this.dirtyNotifiable.markAsDirty()); + //this.currentFilter.setMaxTransferSize(this.maxTransferSize); } if (onFilterInstanceChange != null) { this.onFilterInstanceChange.run(); @@ -135,16 +136,16 @@ public final void setFilter(@Nullable Filter newFilter) { } public boolean showGlobalTransferLimitSlider() { - return this.maxTransferSize > 0 && (!hasFilter() || getFilter().showGlobalTransferLimitSlider()); + return this.maxTransferSize > 0 && (!hasFilter()/* || getFilter().showGlobalTransferLimitSlider()*/); } public void setBlacklistFilter(boolean blacklistFilter) { - if (hasFilter()) getFilter().setBlacklistFilter(blacklistFilter); + if (hasFilter()) getFilter().setBlackList(blacklistFilter); onFilterInstanceChange(); } public final boolean isBlacklistFilter() { - return hasFilter() && getFilter().isBlacklistFilter(); + return hasFilter() && getFilter().isBlackList(); } public int getTransferSize() { @@ -158,11 +159,11 @@ public int getTransferLimit(int slotIndex) { if (isBlacklistFilter() || !hasFilter()) { return getTransferSize(); } - return this.currentFilter.getTransferLimit(slotIndex, getTransferSize()); + return this.currentFilter.testItemCount(getStackInSlot(slotIndex)); } public void setTransferSize(int transferSize) { - this.transferSize = MathHelper.clamp(transferSize, 1, getMaxTransferSize()); + this.transferSize = Mth.clamp(transferSize, 1, getMaxTransferSize()); onFilterInstanceChange(); } @@ -177,7 +178,7 @@ public CompoundTag serializeNBT() { @Override public void deserializeNBT(CompoundTag nbt) { super.deserializeNBT(nbt.getCompound("FilterInventory")); - setFilter(BaseFilter.getFilterFromStack(getFilterStack())); + setItemFilter(ItemFilter.loadFilter(getFilterStack())); if (nbt.contains("TransferStackSize")) this.transferSize = nbt.getInt("TransferStackSize"); } @@ -187,14 +188,13 @@ public void handleLegacyNBT(CompoundTag nbt) { // also, ItemStackHandler's deserialization doesn't use setStackInSlot, so I have to do that manually here if (nbt.contains("FilterInventory")) { super.deserializeNBT(nbt.getCompound("FilterInventory")); - setFilter(BaseFilter.getFilterFromStack(getFilterStack())); + setItemFilter(ItemFilter.loadFilter(getFilterStack())); } - - if (hasFilter()) - getFilter().getFilterReader().handleLegacyNBT(nbt); } /** Uses Cleanroom MUI */ + // TODO ui + /* public IWidget initUI(ModularPanel main, PanelSyncManager manager) { PanelSyncHandler panel = manager.panel("filter_panel", main, (syncManager, syncHandler) -> { var filter = hasFilter() ? getFilter() : BaseFilter.ERROR_FILTER; @@ -236,9 +236,10 @@ public IWidget initUI(ModularPanel main, PanelSyncManager manager) { .alignment(Alignment.CenterRight).asWidget() .left(36).right(0).height(18)); } + */ public void writeInitialSyncData(FriendlyByteBuf packetBuffer) { - packetBuffer.writeItemStack(this.getFilterStack()); + packetBuffer.writeItem(this.getFilterStack()); packetBuffer.writeInt(this.maxTransferSize); packetBuffer.writeInt(this.transferSize); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/BatteryBufferMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/BatteryBufferMachine.java index 76ee3aac4e..870edea8a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/BatteryBufferMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/BatteryBufferMachine.java @@ -232,7 +232,7 @@ public void serverTick() { long outAmps = 0L; if (genAmps > 0) { - outAmps = energyContainer.acceptEnergyFromNetwork(outFacing.getOpposite(), voltage, genAmps); + outAmps = energyContainer.acceptEnergyFromNetwork(outFacing.getOpposite(), voltage, genAmps, false); if (outAmps == 0 && internalAmps == 0) return; } @@ -260,7 +260,7 @@ public void serverTick() { } @Override - public long acceptEnergyFromNetwork(@Nullable Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(@Nullable Direction side, long voltage, long amperage, boolean simulate) { var latestTimeStamp = getMachine().getOffsetTimer(); if (lastTimeStamp < latestTimeStamp) { amps = 0; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/ChargerMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/ChargerMachine.java index 8586ca2f59..6e4c01eb98 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/ChargerMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/ChargerMachine.java @@ -194,7 +194,7 @@ protected EnergyBatteryTrait(int inventorySize) { } @Override - public long acceptEnergyFromNetwork(@Nullable Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(@Nullable Direction side, long voltage, long amperage, boolean simulate) { var latestTimeStamp = getMachine().getOffsetTimer(); if (lastTimeStamp < latestTimeStamp) { amps = 0; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java index 8f9719c6b0..4e51eafa8f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java @@ -1,16 +1,19 @@ package com.gregtechceu.gtceu.common.machine.multiblock.part; -import com.gregtechceu.gtceu.api.capability.IDataAccessHatch; -import com.gregtechceu.gtceu.api.capability.IOpticalDataAccessHatch; import com.gregtechceu.gtceu.api.capability.IWorkable; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; +import com.gregtechceu.gtceu.api.capability.data.IStandardDataAccess; +import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; +import com.gregtechceu.gtceu.api.capability.data.query.IBridgeable; +import com.gregtechceu.gtceu.api.capability.data.query.RecipeDataQuery; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiController; import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.machine.multiblock.part.MultiblockPartMachine; import com.gregtechceu.gtceu.api.recipe.GTRecipe; -import com.gregtechceu.gtceu.common.blockentity.OpticalPipeBlockEntity; +import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; @@ -22,14 +25,16 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.Set; import javax.annotation.ParametersAreNonnullByDefault; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault -public class OpticalDataHatchMachine extends MultiblockPartMachine implements IOpticalDataAccessHatch { +public class OpticalDataHatchMachine extends MultiblockPartMachine implements IStandardDataAccess { + + private final Set recentQueries = GTUtil.createWeakHashSet(); @Getter private final boolean isTransmitter; @@ -40,61 +45,44 @@ public OpticalDataHatchMachine(IMachineBlockEntity holder, boolean isTransmitter } @Override - public boolean isRecipeAvailable(@NotNull GTRecipe recipe, @NotNull Collection seen) { - seen.add(this); + public boolean accessData(@NotNull DataQueryObject queryObject) { + if (!supportsQuery(queryObject) || !recentQueries.add(queryObject)) return false; if (!getControllers().isEmpty()) { if (isTransmitter()) { IMultiController controller = getControllers().get(0); - if (!(controller instanceof IWorkable workable) || !workable.isActive()) return false; + if (!controller.isFormed() || (controller instanceof IWorkable workable && !workable.isActive())) return false; - List dataAccesses = new ArrayList<>(); - List transmitters = new ArrayList<>(); + List dataAccesses = new ArrayList<>(); + List reception = new ArrayList<>(); for (var part : controller.getParts()) { Block block = part.self().getBlockState().getBlock(); - if (part instanceof IDataAccessHatch hatch && PartAbility.DATA_ACCESS.isApplicable(block)) { + if (part instanceof IDataAccess hatch && PartAbility.DATA_ACCESS.isApplicable(block)) { dataAccesses.add(hatch); } - if (part instanceof IDataAccessHatch hatch && + if (part instanceof IStandardDataAccess hatch && PartAbility.OPTICAL_DATA_RECEPTION.isApplicable(block)) { - transmitters.add(hatch); + reception.add(hatch); } } - return isRecipeAvailable(dataAccesses, seen, recipe) || - isRecipeAvailable(transmitters, seen, recipe); - } else { - BlockEntity tileEntity = getLevel().getBlockEntity(getPos().relative(getFrontFacing())); - if (tileEntity == null) return false; + if (IDataAccess.accessData(dataAccesses, queryObject)) + return true; - if (tileEntity instanceof OpticalPipeBlockEntity) { - // noinspection DataFlowIssue - IDataAccessHatch cap = tileEntity.getCapability(GTCapability.CAPABILITY_DATA_ACCESS, - getFrontFacing().getOpposite()).orElse(null); - // noinspection ConstantValue - return cap != null && cap.isRecipeAvailable(recipe, seen); + if (queryObject instanceof IBridgeable bridgeable && reception.size() > 1) { + bridgeable.setBridged(); } + return IDataAccess.accessData(reception, queryObject); + } else { + BlockEntity tileEntity = getNeighbor(getFrontFacing()); + if (tileEntity == null) return false; + IDataAccess cap = tileEntity.getCapability(GTCapability.CAPABILITY_DATA_ACCESS, + getFrontFacing().getOpposite()).resolve().orElse(null); + return cap != null && cap.accessData(queryObject); } } return false; } - private static boolean isRecipeAvailable(@NotNull Iterable hatches, - @NotNull Collection seen, - @NotNull GTRecipe recipe) { - for (IDataAccessHatch hatch : hatches) { - if (seen.contains(hatch)) continue; - if (hatch.isRecipeAvailable(recipe, seen)) { - return true; - } - } - return false; - } - - @Override - public boolean isCreative() { - return false; - } - @Override public boolean shouldOpenUI(Player player, InteractionHand hand, BlockHitResult hit) { return false; @@ -107,6 +95,13 @@ public boolean canShared() { @Override public GTRecipe modifyRecipe(GTRecipe recipe) { - return IOpticalDataAccessHatch.super.modifyRecipe(recipe); + // creative hatches do not need to check, they always have the recipe + // TODO creative data access hatch + //if (this.isCreative()) return recipe; + RecipeDataQuery query = new RecipeDataQuery(recipe); + + // hatches need to have the recipe available + if (this.accessData(query)) return recipe; + return null; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeEnergyContainerMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeEnergyContainerMachine.java index 98f5aa3cfb..ce55f0a6c3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeEnergyContainerMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeEnergyContainerMachine.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.IEnergyContainer; import com.gregtechceu.gtceu.api.capability.ILaserContainer; +import com.gregtechceu.gtceu.api.capability.ILaserRelay; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MetaMachine; @@ -87,17 +88,22 @@ protected void updateEnergyTick() { } ampsReceived = 0; if (!active || !source || voltage <= 0 || amps <= 0) return; - int ampsUsed = 0; + long ampsUsed = 0; for (var facing : GTUtil.DIRECTIONS) { var opposite = facing.getOpposite(); IEnergyContainer container = GTCapabilityHelper.getEnergyContainer(getLevel(), getPos().relative(facing), opposite); // Try to get laser capability - if (container == null) - container = GTCapabilityHelper.getLaser(getLevel(), getPos().relative(facing), opposite); + if (container == null) { + ILaserRelay relay = GTCapabilityHelper.getLaser(getLevel(), getPos().relative(facing), opposite); + if (relay != null) { + ampsUsed += relay.receiveLaser(voltage, amps - ampsUsed); + } + + } if (container != null && container.inputsEnergy(opposite) && container.getEnergyCanBeInserted() > 0) { - ampsUsed += container.acceptEnergyFromNetwork(opposite, voltage, amps - ampsUsed); + ampsUsed += container.acceptEnergyFromNetwork(opposite, voltage, amps - ampsUsed, false); if (ampsUsed >= amps) { break; } @@ -107,7 +113,7 @@ protected void updateEnergyTick() { } @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { if (source || !active || ampsReceived >= amps) { return 0; } @@ -244,4 +250,9 @@ public ModularUI createUI(Player entityPlayer) { .setBackground(ColorPattern.BLACK.rectTexture()) .setValue(GTValues.VNF[setTier])); } + + @Override + public long receiveLaser(long laserVoltage, long laserAmperage) { + return acceptEnergyFromNetwork(null, laserVoltage, laserAmperage, false); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java new file mode 100644 index 0000000000..44bdae9210 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -0,0 +1,99 @@ +package com.gregtechceu.gtceu.common.pipelike.block.cable; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.item.tool.GTToolType; +import com.gregtechceu.gtceu.common.data.GTDamageTypes; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowData; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.SuperconductorLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.WorldEnergyNet; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; + +import java.util.Map; + +public class CableBlock extends PipeMaterialBlock implements IBurnable { + + private static final Map> CACHE = new Object2ObjectOpenHashMap<>(); + + public CableBlock(BlockBehaviour.Properties properties, CableStructure structure, Material material) { + super(properties, structure, material); + CACHE.compute(material, (k, v) -> { + if (v == null) v = new Object2ObjectOpenHashMap<>(); + v.put(structure, this); + return v; + }); + } + + @Override + public CableStructure getStructure() { + return (CableStructure) super.getStructure(); + } + + @Override + public GTToolType getToolClass() { + return GTToolType.WIRE_CUTTER; + } + + @Override + protected String getConnectLangKey() { + return "gregtech.tool_action.wire_cutter.connect"; + } + + @Override + public void partialBurn(BlockState state, Level world, BlockPos pos) { + CableStructure structure = getStructure(); + if (structure.partialBurnStructure() != null) { + CableBlock newBlock = CACHE.get(material).get(structure.partialBurnStructure()); + BlockState newState = newBlock.defaultBlockState() + .setValue(NORTH, state.getValue(NORTH)) + .setValue(EAST, state.getValue(EAST)) + .setValue(SOUTH, state.getValue(SOUTH)) + .setValue(WEST, state.getValue(WEST)) + .setValue(UP, state.getValue(UP)) + .setValue(DOWN, state.getValue(DOWN)); + world.setBlockAndUpdate(pos, newState); + } + } + + @Override + public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { + super.entityInside(state, level, pos, entity); + if (!(level instanceof ServerLevel serverLevel) || getStructure().isInsulated() || !(entity instanceof LivingEntity living)) return; + PipeBlockEntity tile = getBlockEntity(level, pos); + if (tile != null && tile.getFrameMaterial() == null && tile.getOffsetTimer() % 10 == 0) { + WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(pos); + if (node != null) { + if (node.getData().getLogicEntryNullable(SuperconductorLogic.INSTANCE) != null) return; + EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + if (logic != null) { + long tick = Platform.getMinecraftServer().getTickCount(); + long cumulativeDamage = 0; + for (EnergyFlowData data : logic.getFlow(tick)) { + cumulativeDamage += (GTUtil.getTierByVoltage(data.voltage()) + 1) * data.amperage() * 4; + } + if (cumulativeDamage != 0) { + living.hurt(GTDamageTypes.ELECTRIC.source(serverLevel), cumulativeDamage); + // TODO advancement + //if (living instanceof ServerPlayer serverPlayer) { + // AdvancementTriggers.ELECTROCUTION_DEATH.trigger(serverPlayer); + //} + } + } + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java new file mode 100644 index 0000000000..b0c4c88abc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -0,0 +1,99 @@ +package com.gregtechceu.gtceu.common.pipelike.block.cable; + +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IInsulatable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; + +public record CableStructure(String name, int material, int costFactor, TagPrefix prefix, + @Nullable CableStructure partialBurnStructure, @Nullable Integer partialBurnThreshold, + float renderThickness, AbstractPipeModel model) + implements IPipeMaterialStructure, IInsulatable { + + public static final int INSULATION_BURN_TEMP = 1000; + + public static final CableStructure WIRE_SINGLE = new CableStructure("wire_single", 1, 2, TagPrefix.wireGtSingle, + null, null, 0.125f, CableModel.INSTANCE); + public static final CableStructure WIRE_DOUBLE = new CableStructure("wire_double", 2, 2, TagPrefix.wireGtDouble, + null, null, 0.25f, CableModel.INSTANCE); + public static final CableStructure WIRE_QUADRUPLE = new CableStructure("wire_quadruple", 4, 3, + TagPrefix.wireGtQuadruple, null, null, 0.375f, CableModel.INSTANCE); + public static final CableStructure WIRE_OCTAL = new CableStructure("wire_octal", 8, 3, TagPrefix.wireGtOctal, null, + null, 0.5f, CableModel.INSTANCE); + public static final CableStructure WIRE_HEX = new CableStructure("wire_hex", 16, 3, TagPrefix.wireGtHex, null, null, + 0.75f, CableModel.INSTANCE); + + public static final CableStructure CABLE_SINGLE = new CableStructure("cable_single", 1, 1, TagPrefix.cableGtSingle, + WIRE_SINGLE, INSULATION_BURN_TEMP, 0.25f, CableModel.INSULATED_INSTANCES[0]); + public static final CableStructure CABLE_DOUBLE = new CableStructure("cable_double", 2, 1, TagPrefix.cableGtDouble, + WIRE_DOUBLE, INSULATION_BURN_TEMP, 0.375f, CableModel.INSULATED_INSTANCES[1]); + public static final CableStructure CABLE_QUADRUPLE = new CableStructure("cable_quadruple", 4, 1, + TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, CableModel.INSULATED_INSTANCES[2]); + public static final CableStructure CABLE_OCTAL = new CableStructure("cable_octal", 8, 1, TagPrefix.cableGtOctal, + WIRE_OCTAL, INSULATION_BURN_TEMP, 0.75f, CableModel.INSULATED_INSTANCES[3]); + public static final CableStructure CABLE_HEX = new CableStructure("cable_hex", 16, 1, TagPrefix.cableGtHex, + WIRE_HEX, INSULATION_BURN_TEMP, 1f, CableModel.INSULATED_INSTANCES[4]); + + public CableStructure(String name, int material, int costFactor, TagPrefix prefix, + @Nullable CableStructure partialBurnStructure, @Nullable Integer partialBurnThreshold, + float renderThickness, AbstractPipeModel model) { + this.name = name; + this.material = material; + this.costFactor = costFactor; + this.prefix = prefix; + this.partialBurnStructure = partialBurnStructure; + this.partialBurnThreshold = partialBurnThreshold; + this.renderThickness = renderThickness; + this.model = model; + PipeStructureRegistry.register(this); + } + + @Override + public @NotNull String getSerializedName() { + return name; + } + + @Override + public TagPrefix getPrefix() { + return prefix; + } + + @Override + public float getRenderThickness() { + return renderThickness; + } + + @Override + public AbstractPipeModel getModel() { + return model; + } + + @Override + public boolean isPaintable() { + return true; + } + + @Override + public boolean isInsulated() { + return partialBurnStructure != null; + } + + public static void registerDefaultStructures(Consumer register) { + register.accept(WIRE_SINGLE); + register.accept(WIRE_DOUBLE); + register.accept(WIRE_QUADRUPLE); + register.accept(WIRE_OCTAL); + register.accept(WIRE_HEX); + register.accept(CABLE_SINGLE); + register.accept(CABLE_DOUBLE); + register.accept(CABLE_QUADRUPLE); + register.accept(CABLE_OCTAL); + register.accept(CABLE_HEX); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java new file mode 100644 index 0000000000..cb84df4abc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java @@ -0,0 +1,43 @@ +package com.gregtechceu.gtceu.common.pipelike.block.laser; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; +import com.gregtechceu.gtceu.api.item.tool.GTToolType; +import com.gregtechceu.gtceu.common.pipelike.handlers.LaserNetHandler; +import net.minecraft.core.BlockPos; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.state.BlockBehaviour; +import org.jetbrains.annotations.NotNull; + +public class LaserPipeBlock extends PipeActivableBlock { + + public LaserPipeBlock(BlockBehaviour.Properties properties, LaserStructure structure) { + super(properties, structure); + } + + @Override + public GTToolType getToolClass() { + return GTToolType.WIRE_CUTTER; + } + + @Override + protected String getConnectLangKey() { + return "gtceu.tool_action.wire_cutter.connect"; + } + + @Override + protected boolean allowsBlocking() { + return false; + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + return LaserNetHandler.INSTANCE; + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(@NotNull ItemStack stack) { + return LaserNetHandler.INSTANCE; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java new file mode 100644 index 0000000000..25df66cd0f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -0,0 +1,75 @@ +package com.gregtechceu.gtceu.common.pipelike.block.laser; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +public record LaserStructure(String name, float renderThickness, boolean mirror, ActivablePipeModel model) + implements IPipeStructure { + + public static final LaserStructure NORMAL = new LaserStructure("laser_pipe_normal", 0.375f, + false, ActivablePipeModel.LASER); + public static final LaserStructure MIRROR = new LaserStructure("laser_pipe_mirror", 0.5f, + true, ActivablePipeModel.LASER); + + public LaserStructure(String name, float renderThickness, boolean mirror, ActivablePipeModel model) { + this.name = name; + this.renderThickness = renderThickness; + this.mirror = mirror; + this.model = model; + PipeStructureRegistry.register(this); + } + + @Override + public boolean canConnectTo(Direction side, byte connectionMask) { + if (mirror) { + byte connectionCount = 0; + for (Direction facing : GTUtil.DIRECTIONS) { + if (facing == side) continue; + if (GTUtil.evalMask(facing, connectionMask)) { + if (facing.getOpposite() == side) return false; // must be a bent connection + connectionCount++; + } + if (connectionCount > 1) return false; + } + } else { + for (Direction facing : GTUtil.DIRECTIONS) { + if (facing == side) continue; + if (GTUtil.evalMask(facing, connectionMask)) { + return facing.getOpposite() == side; + } + } + } + return true; + } + + @Override + public @NotNull String getSerializedName() { + return name; + } + + @Override + public float getRenderThickness() { + return renderThickness; + } + + @Override + public boolean isPaintable() { + return true; + } + + @Override + public AbstractPipeModel getModel() { + return model; + } + + public static void registerDefaultStructures(Consumer register) { + register.accept(NORMAL); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java new file mode 100644 index 0000000000..4d3c8ea171 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java @@ -0,0 +1,43 @@ +package com.gregtechceu.gtceu.common.pipelike.block.optical; + +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; +import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface IOpticalTransferController { + + TransferControl CONTROL = new TransferControl<>("Laser") { + + @Override + public @NotNull IOpticalTransferController get(@Nullable Object potentialHolder) { + if (!(potentialHolder instanceof TransferControlProvider holder)) return DEFAULT; + IOpticalTransferController found = holder.getControllerForControl(CONTROL); + return found == null ? DEFAULT : found; + } + + @Override + public @NotNull IOpticalTransferController getNoPassage() { + return NO_PASSAGE; + } + }; + + IOpticalTransferController DEFAULT = new IOpticalTransferController() {}; + + IOpticalTransferController NO_PASSAGE = new IOpticalTransferController() { + + @Override + public boolean queryHandler(DataQueryObject query, IDataAccess handler) { + return false; + } + }; + + /** + * @return whether the request should be cancelled + */ + default boolean queryHandler(DataQueryObject query, IDataAccess handler) { + return handler.accessData(query); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java new file mode 100644 index 0000000000..efdfe7ada0 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java @@ -0,0 +1,43 @@ +package com.gregtechceu.gtceu.common.pipelike.block.optical; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; +import com.gregtechceu.gtceu.api.item.tool.GTToolType; +import com.gregtechceu.gtceu.common.pipelike.handlers.OpticalNetHandler; +import net.minecraft.core.BlockPos; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.state.BlockBehaviour; +import org.jetbrains.annotations.NotNull; + +public class OpticalPipeBlock extends PipeActivableBlock { + + public OpticalPipeBlock(BlockBehaviour.Properties properties, OpticalStructure structure) { + super(properties, structure); + } + + @Override + public GTToolType getToolClass() { + return GTToolType.WIRE_CUTTER; + } + + @Override + protected String getConnectLangKey() { + return "gregtech.tool_action.wire_cutter.connect"; + } + + @Override + protected boolean allowsBlocking() { + return false; + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + return OpticalNetHandler.INSTANCE; + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(@NotNull ItemStack stack) { + return OpticalNetHandler.INSTANCE; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java new file mode 100644 index 0000000000..3ffe41a23e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -0,0 +1,61 @@ +package com.gregtechceu.gtceu.common.pipelike.block.optical; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +public record OpticalStructure(String name, float renderThickness, ActivablePipeModel model) implements IPipeStructure { + + public static final OpticalStructure INSTANCE = new OpticalStructure("optical_pipe_normal", 0.375f, + ActivablePipeModel.OPTICAL); + + public OpticalStructure(String name, float renderThickness, ActivablePipeModel model) { + this.name = name; + this.renderThickness = renderThickness; + this.model = model; + PipeStructureRegistry.register(this); + } + + @Override + public boolean canConnectTo(Direction side, byte connectionMask) { + byte connectionCount = 0; + for (Direction facing : GTUtil.DIRECTIONS) { + if (facing == side) continue; + if (GTUtil.evalMask(facing, connectionMask)) { + connectionCount++; + } + if (connectionCount > 1) return false; + } + return true; + } + + @Override + public @NotNull String getSerializedName() { + return name; + } + + @Override + public float getRenderThickness() { + return renderThickness; + } + + @Override + public boolean isPaintable() { + return true; + } + + @Override + public AbstractPipeModel getModel() { + return model; + } + + public static void registerDefaultStructures(Consumer register) { + register.accept(INSTANCE); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java index 5501d80610..649f4845b3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java @@ -40,7 +40,7 @@ public long getEnergyCanBeInserted() { } @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { if (transfer) return 0; if (side == null) { if (facing == null) return 0; @@ -88,7 +88,7 @@ public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) if (cableBroken) continue; transfer = true; - long amps = dest.acceptEnergyFromNetwork(facing, pathVoltage, amperage - amperesUsed); + long amps = dest.acceptEnergyFromNetwork(facing, pathVoltage, amperage - amperesUsed, false); transfer = false; if (amps == 0) continue; @@ -139,7 +139,7 @@ public long changeEnergy(long energyToAdd) { GTCEu.LOGGER.warn("Do not use changeEnergy() for cables! Use acceptEnergyFromNetwork()"); return acceptEnergyFromNetwork(null, energyToAdd / getInputAmperage(), - energyToAdd / getInputVoltage()) * getInputVoltage(); + energyToAdd / getInputVoltage(), false) * getInputVoltage(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java new file mode 100644 index 0000000000..cc05e66129 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java @@ -0,0 +1,61 @@ +package com.gregtechceu.gtceu.common.pipelike.handlers; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserStructure; +import com.gregtechceu.gtceu.common.pipelike.net.laser.WorldLaserNet; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.LevelAccessor; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public final class LaserNetHandler implements IPipeNetNodeHandler { + + public static final LaserNetHandler INSTANCE = new LaserNetHandler(); + + @Override + public @NotNull Collection getOrCreateFromNets(ServerLevel world, BlockPos pos, + IPipeStructure structure) { + if (structure instanceof LaserStructure) { + return Collections.singletonList(WorldLaserNet.getWorldNet(world).getOrCreateNode(pos)); + } + return Collections.emptyList(); + } + + @Override + public @NotNull Collection getFromNets(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof LaserStructure) { + WorldPipeNetNode node = WorldLaserNet.getWorldNet(world).getNode(pos); + if (node != null) return Collections.singletonList(node); + } + return Collections.emptyList(); + } + + @Override + public void removeFromNets(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof LaserStructure) { + WorldLaserNet net = WorldLaserNet.getWorldNet(world); + WorldPipeNetNode node = net.getNode(pos); + if (node != null) net.removeNode(node); + } + } + + @Override + public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeStructure structure) { + if (structure instanceof LaserStructure laser && laser.mirror()) { + tooltip.add(Component.translatable("block.gtceu.laser_pipe_mirror.tooltip")); + return; + } + tooltip.add(Component.translatable("block.gtceu.normal_laser_pipe.tooltip")); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java new file mode 100644 index 0000000000..aa8512194f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java @@ -0,0 +1,57 @@ +package com.gregtechceu.gtceu.common.pipelike.handlers; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; +import com.gregtechceu.gtceu.common.pipelike.net.optical.WorldOpticalNet; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public final class OpticalNetHandler implements IPipeNetNodeHandler { + + public static final OpticalNetHandler INSTANCE = new OpticalNetHandler(); + + @Override + public @NotNull Collection getOrCreateFromNets(ServerLevel world, BlockPos pos, + IPipeStructure structure) { + if (structure instanceof OpticalStructure) { + return Collections.singletonList(WorldOpticalNet.getWorldNet(world).getOrCreateNode(pos)); + } + return Collections.emptyList(); + } + + @Override + public @NotNull Collection getFromNets(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof OpticalStructure) { + WorldPipeNetNode node = WorldOpticalNet.getWorldNet(world).getNode(pos); + if (node != null) return Collections.singletonList(node); + } + return Collections.emptyList(); + } + + @Override + public void removeFromNets(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof OpticalStructure) { + WorldOpticalNet net = WorldOpticalNet.getWorldNet(world); + WorldPipeNetNode node = net.getNode(pos); + if (node != null) net.removeNode(node); + } + } + + @Override + public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeStructure structure) { + tooltip.add(Component.translatable("block.gtceu.normal_optical_pipe.tooltip")); + + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java index c83c66c836..c0f6c67ddc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java @@ -51,11 +51,11 @@ private ILaserContainer getInnerContainer() { } @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage) { + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { ILaserContainer handler = getInnerContainer(); if (handler == null) return 0; setPipesActive(); - return handler.acceptEnergyFromNetwork(side, voltage, amperage); + return handler.acceptEnergyFromNetwork(side, voltage, amperage, false); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java index 1dc939e15e..c8cbeb8bed 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.laser; import com.gregtechceu.gtceu.api.capability.ILaserContainer; +import com.gregtechceu.gtceu.api.capability.ILaserRelay; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.pipenet.PipeNetWalker; import com.gregtechceu.gtceu.common.blockentity.LaserPipeBlockEntity; @@ -81,7 +82,7 @@ protected void checkNeighbour(LaserPipeBlockEntity pipeNode, BlockPos pipePos, D } if (((LaserNetWalker) root).routePath == null) { - ILaserContainer handler = neighbourTile + ILaserRelay handler = neighbourTile .getCapability(GTCapability.CAPABILITY_LASER, faceToNeighbour.getOpposite()).resolve().orElse(null); if (handler != null) { ((LaserNetWalker) root).routePath = new LaserRoutePath(pipePos.immutable(), faceToNeighbour, diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java new file mode 100644 index 0000000000..a6c3d6ddb2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java @@ -0,0 +1,108 @@ +package com.gregtechceu.gtceu.common.pipelike.net; + +import com.gregtechceu.gtceu.api.graphnet.path.INetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeActivableBlockEntity; +import com.gregtechceu.gtceu.utils.TaskScheduler; +import com.gregtechceu.gtceu.utils.function.Task; +import com.lowdragmc.lowdraglib.Platform; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.WeakHashMap; + +public class SlowActiveWalker implements Task { + + private static final int RECENT_WALKER_CUTOFF = 10; + + private static final Map, Long> RECENT_DISPATCHES = new WeakHashMap<>(); + + /** + * Dispatches a slow walker along a path with default parameters. + * + * @param world the world to schedule the task in. When this world is unloaded, the task will die no matter + * its state, so be careful! + * @param path the path to walk. + * @param delay the ticks between steps of the walker + */ + public static void dispatch(Level world, INetPath path, int delay) { + dispatch(world, path, delay, 1, 1); + } + + /** + * Dispatches a slow walker along a path. + * + * @param world the world to schedule the task in. When this world is unloaded, the task will die no matter + * its state, so be careful! + * @param path the path to walk. + * @param delay the ticks between steps of the walker + * @param stepSize the number of nodes within the path that the walker progresses every step + * @param activeLength the number of tiles that will be left active behind a progressing walker + */ + public static void dispatch(Level world, INetPath path, int delay, + int stepSize, int activeLength) { + long tick = Platform.getMinecraftServer().getTickCount(); + RECENT_DISPATCHES.compute(path, (k, v) -> { + if (v == null || v < tick) { + SlowActiveWalker walker = new SlowActiveWalker(path, delay, stepSize, activeLength); + TaskScheduler.scheduleTask(world, walker); + return tick + RECENT_WALKER_CUTOFF; + } else return v; + }); + } + + private final INetPath path; + private final int lastStep; + private int index = 0; + + private final int delay; + private final int stepSize; + private final int activeLength; + private int counter; + + protected SlowActiveWalker(INetPath path, int delay, int stepSize, + int activeLength) { + this.path = path; + this.delay = delay; + this.stepSize = stepSize; + this.activeLength = activeLength; + this.lastStep = this.path.getOrderedNodes().size() + activeLength - 1; + this.step(getSafe(-stepSize), getSafe(0)); + } + + @Override + public boolean run() { + counter++; + if (counter >= delay) { + counter = 0; + for (int i = 0; i < stepSize; i++) { + index++; + this.step(getSafe(index - activeLength), getSafe(index)); + if (index >= lastStep) { + return false; + } + } + } + return true; + } + + protected @Nullable WorldPipeNetNode getSafe(int index) { + if (index >= path.getOrderedNodes().size()) return null; + else if (index < 0) return null; + else return path.getOrderedNodes().get(index); + } + + protected void step(@Nullable WorldPipeNetNode previous, @Nullable WorldPipeNetNode next) { + if (previous != null) activate(previous, false); + if (next != null) activate(next, true); + } + + protected void activate(@NotNull WorldPipeNetNode node, boolean active) { + if (node.getBlockEntity() instanceof PipeActivableBlockEntity activable) { + activable.setActive(active); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java new file mode 100644 index 0000000000..dde45bdf2c --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java @@ -0,0 +1,197 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.capability.IEnergyContainer; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.AbstractGroupData; +import com.gregtechceu.gtceu.api.graphnet.NetGroup; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import lombok.Setter; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumMap; +import java.util.Iterator; + +public class EnergyCapabilityObject implements IPipeCapabilityObject, IEnergyContainer { + + private final WorldPipeNet net; + @Setter + private @Nullable PipeBlockEntity tile; + + private final EnumMap internalBuffers = new EnumMap<>(Direction.class); + private final WorldPipeNetNode node; + + private boolean transferring = false; + + public EnergyCapabilityObject(@NotNull N net, + WorldPipeNetNode node) { + this.net = net; + this.node = node; + for (Direction facing : GTUtil.DIRECTIONS) { + AbstractNetFlowEdge edge = (AbstractNetFlowEdge) net.getNewEdge(); + edge.setData(NetLogicData.union(node.getData(), (NetLogicData) null)); + internalBuffers.put(facing, edge); + } + } + + private FlowWorldPipeNetPath.Provider getProvider() { + return (FlowWorldPipeNetPath.Provider) net; + } + + private boolean inputDisallowed(Direction side) { + if (side == null) return false; + if (tile == null) return true; + else return tile.isBlocked(side); + } + + @Override + public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { + if (tile == null || this.transferring || inputDisallowed(side)) return 0; + this.transferring = true; + + SimulatorKey simulator = null; + if (simulate) simulator = SimulatorKey.getNewSimulatorInstance(); + long tick = Platform.getMinecraftServer().getTickCount(); + + AbstractNetFlowEdge internalBuffer = this.internalBuffers.get(side); + if (internalBuffer != null) { + long limit = internalBuffer.getFlowLimit(IPredicateTestObject.INSTANCE, net, tick, simulator); + if (limit <= 0) { + this.transferring = false; + return 0; + } else if (amperage > limit) { + amperage = limit; + } + } + long availableAmperage = amperage; + + EnergyTraverseData data = new EnergyTraverseData(net, IPredicateTestObject.INSTANCE, simulator, tick, voltage, + tile.getBlockPos(), side); + availableAmperage -= TraverseHelpers.traverseFlood(data, getPaths(data), availableAmperage); + if (availableAmperage > 0) { + availableAmperage -= TraverseHelpers.traverseDumb(data, getPaths(data), data::handleOverflow, + availableAmperage); + } + long accepted = amperage - availableAmperage; + + if (internalBuffer != null) data.consumeFlowLimit(internalBuffer, node, accepted); + if (!simulate) { + EnergyGroupData group = getEnergyData(); + if (group != null) { + group.addEnergyInPerSec(accepted * voltage, data.getQueryTick()); + } + } + this.transferring = false; + return accepted; + } + + private Iterator getPaths(EnergyTraverseData data) { + assert tile != null; + return getProvider().getPaths(net.getNode(tile.getBlockPos()), data.getTestObject(), data.getSimulatorKey(), + data.getQueryTick()); + } + + @Nullable + private EnergyGroupData getEnergyData() { + if (tile == null) return null; + NetNode node = net.getNode(tile.getBlockPos()); + if (node == null) return null; + NetGroup group = node.getGroupUnsafe(); + if (group == null) return null; + AbstractGroupData data = group.getData(); + if (!(data instanceof EnergyGroupData e)) return null; + return e; + } + + @Override + public long getInputAmperage() { + if (tile == null) return 0; + return tile.getNetLogicData(net.getNetworkID()).getLogicEntryDefaultable(ThroughputLogic.INSTANCE).getValue(); + } + + @Override + public long getInputVoltage() { + if (tile == null) return 0; + return tile.getNetLogicData(net.getNetworkID()).getLogicEntryDefaultable(VoltageLimitLogic.INSTANCE).getValue(); + } + + @Override + public Capability[] getCapabilities() { + return WorldEnergyNet.CAPABILITIES; + } + + @Override + public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { + if (capability == GTCapability.CAPABILITY_ENERGY_CONTAINER) { + return GTCapability.CAPABILITY_ENERGY_CONTAINER + .orEmpty(capability, LazyOptional.of(() -> this)); + } + return null; + } + + @Override + public long getInputPerSec() { + EnergyGroupData data = getEnergyData(); + if (data == null) return 0; + else return data + .getEnergyInPerSec(Platform.getMinecraftServer().getTickCount()); + } + + @Override + public long getOutputPerSec() { + EnergyGroupData data = getEnergyData(); + if (data == null) return 0; + else return data + .getEnergyOutPerSec(Platform.getMinecraftServer().getTickCount()); + } + + @Override + public boolean inputsEnergy(Direction side) { + return !inputDisallowed(side); + } + + @Override + public boolean outputsEnergy(Direction side) { + return true; + } + + @Override + public long changeEnergy(long differenceAmount) { + GTCEu.LOGGER.error("Do not use changeEnergy() for cables! Use acceptEnergyFromNetwork()"); + return acceptEnergyFromNetwork(null, + differenceAmount / getInputAmperage(), + differenceAmount / getInputVoltage(), false) * getInputVoltage(); + } + + @Override + public long getEnergyStored() { + return 0; + } + + @Override + public long getEnergyCapacity() { + return getInputAmperage() * getInputVoltage(); + } + + @Override + public boolean isOneProbeHidden() { + return true; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowData.java new file mode 100644 index 0000000000..01105b2e99 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowData.java @@ -0,0 +1,8 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +public record EnergyFlowData(long amperage, long voltage) { + + public long getEU() { + return amperage * voltage; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java new file mode 100644 index 0000000000..4732b2e532 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java @@ -0,0 +1,76 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.nbt.ByteTag; +import net.minecraft.network.FriendlyByteBuf; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.List; + +public class EnergyFlowLogic extends NetLogicEntry { + + public static final EnergyFlowLogic INSTANCE = new EnergyFlowLogic(); + + private static final int MEMORY_TICKS = 10; + + private final Long2ObjectOpenHashMap> memory = new Long2ObjectOpenHashMap<>(); + + protected EnergyFlowLogic() { + super("EnergyFlow"); + } + + public @NotNull Long2ObjectOpenHashMap> getMemory() { + return memory; + } + + public @NotNull List getFlow(long tick) { + return memory.getOrDefault(tick, Collections.emptyList()); + } + + public void recordFlow(long tick, EnergyFlowData flow) { + updateMemory(tick); + memory.compute(tick, (k, v) -> { + if (v == null) v = new ObjectArrayList<>(); + v.add(flow); + return v; + }); + } + + private void updateMemory(long tick) { + var iter = memory.long2ObjectEntrySet().fastIterator(); + while (iter.hasNext()) { + Long2ObjectMap.Entry> entry = iter.next(); + if (entry.getLongKey() + MEMORY_TICKS < tick) { + iter.remove(); + } + } + } + + @Override + public ByteTag serializeNBT() { + return ByteTag.valueOf((byte) 0); + } + + @Override + public void deserializeNBT(ByteTag nbt) {} + + @Override + public @NotNull EnergyFlowLogic getNew() { + return new EnergyFlowLogic(); + } + + @Override + public boolean shouldEncode() { + return false; + } + + @Override + public void encode(FriendlyByteBuf buf, boolean fullChange) {} + + @Override + public void decode(FriendlyByteBuf buf, boolean fullChange) {} +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java new file mode 100644 index 0000000000..72ab2dbbe9 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java @@ -0,0 +1,60 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.graphnet.AbstractGroupData; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class EnergyGroupData extends AbstractGroupData { + + private long lastEnergyInPerSec; + private long lastEnergyOutPerSec; + private long energyInPerSec; + private long energyOutPerSec; + private long updateTime; + + public long getEnergyInPerSec(long queryTick) { + updateCache(queryTick); + return lastEnergyInPerSec; + } + + public long getEnergyOutPerSec(long queryTick) { + updateCache(queryTick); + return lastEnergyOutPerSec; + } + + public void addEnergyInPerSec(long energy, long queryTick) { + updateCache(queryTick); + energyInPerSec += energy; + } + + public void addEnergyOutPerSec(long energy, long queryTick) { + updateCache(queryTick); + energyOutPerSec += energy; + } + + private void updateCache(long queryTick) { + if (queryTick > updateTime) { + updateTime = updateTime + 20; + clearCache(); + } + } + + public void clearCache() { + lastEnergyInPerSec = energyInPerSec; + lastEnergyOutPerSec = energyOutPerSec; + energyInPerSec = 0; + energyOutPerSec = 0; + } + + @Override + public boolean mergeAllowed(@NotNull AbstractGroupData other) { + return true; + } + + @Override + public @Nullable AbstractGroupData merge(@NotNull AbstractGroupData other) { + if (other instanceof EnergyGroupData) + return new EnergyGroupData(); + else return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java new file mode 100644 index 0000000000..af2adaedbb --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java @@ -0,0 +1,166 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.capability.IEnergyContainer; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossCache; +import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossResult; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.AbstractTraverseData; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; +import com.gregtechceu.gtceu.utils.GTUtil; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; + +import java.util.function.LongSupplier; +import java.util.function.Supplier; + +public class EnergyTraverseData extends AbstractTraverseData { + + private final Object2ObjectOpenHashMap overVoltageInformation; + + private final long startVoltage; + private long pathVoltage; + + private final BlockPos sourcePos; + private final Direction inputFacing; + + public EnergyTraverseData(IGraphNet net, IPredicateTestObject testObject, SimulatorKey simulator, long queryTick, + long startVoltage, BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick); + this.overVoltageInformation = new Object2ObjectOpenHashMap<>(); + this.startVoltage = startVoltage; + this.sourcePos = sourcePos; + this.inputFacing = inputFacing; + } + + @Override + public boolean prepareForPathWalk(@NotNull FlowWorldPipeNetPath path, long flow) { + if (flow <= 0) return true; + this.pathVoltage = startVoltage; + this.overVoltageInformation.clear(); + this.overVoltageInformation.trim(10); + return false; + } + + @Override + public ReversibleLossOperator traverseToNode(@NotNull WorldPipeNetNode node, long flowReachingNode) { + VoltageLimitLogic limitLogic = node.getData().getLogicEntryNullable(VoltageLimitLogic.INSTANCE); + if (limitLogic != null) { + long voltage = limitLogic.getValue(); + if (voltage < pathVoltage) overVoltageInformation.put(node, + new OverVoltageInformation(voltage, flowReachingNode)); + } + TemperatureLogic temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + if (!node.getData().getLogicEntryDefaultable(SuperconductorLogic.INSTANCE) + .canSuperconduct(temperatureLogic == null ? TemperatureLogic.DEFAULT_TEMPERATURE : + temperatureLogic.getTemperature(getQueryTick()))) { + pathVoltage -= node.getData().getLogicEntryDefaultable(VoltageLossLogic.INSTANCE).getValue(); + } + + NodeLossCache.Key key = NodeLossCache.key(node, this); + NodeLossResult result = NodeLossCache.getLossResult(key); + if (result != null) { + return result.getLossFunction(); + } else { + result = temperatureLogic == null ? null : temperatureLogic.getLossResult(getQueryTick()); + if (result == null) { + return ReversibleLossOperator.IDENTITY; + } + if (result.hasPostAction()) NodeLossCache.registerLossResult(key, result); + return result.getLossFunction(); + } + } + + public void handleOverflow(@NotNull WorldPipeNetNode node, long overflow) { + TemperatureLogic logic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + if (logic != null) { + // this occurs after finalization but before path reset. + logic.applyThermalEnergy(calculateHeatA(overflow, pathVoltage), getQueryTick()); + } + } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long flowReachingDestination) { + this.pathVoltage = (long) GTUtil.geometricMean(pathVoltage, + overVoltageInformation.values().stream().filter(o -> o.voltageCap < this.pathVoltage) + .mapToDouble(o -> (double) o.voltageCap).toArray()); + overVoltageInformation.forEach((k, v) -> v.doHeating(k, pathVoltage, getQueryTick())); + long availableFlow = flowReachingDestination; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IEnergyContainer container = capability.getValue() + .getCapability(GTCapability.CAPABILITY_ENERGY_CONTAINER, capability.getKey().getOpposite()).resolve().orElse(null); + if (container != null) { + availableFlow -= IEnergyTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(pathVoltage, availableFlow, container, + capability.getKey(), getSimulatorKey() != null); + } + } + long accepted = flowReachingDestination - availableFlow; + if (getSimulatorKey() == null && destination.getGroupUnsafe() != null && + destination.getGroupSafe().getData() instanceof EnergyGroupData data) { + data.addEnergyOutPerSec(accepted * pathVoltage, getQueryTick()); + } + return accepted; + } + + @Override + public void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNode, + long consumption) { + super.consumeFlowLimit(edge, targetNode, consumption); + if (consumption > 0) recordFlow(targetNode, consumption); + } + + private void recordFlow(@NotNull NetNode node, long amperes) { + EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + if (logic == null) { + logic = EnergyFlowLogic.INSTANCE.getNew(); + node.getData().setLogicEntry(logic); + } + logic.recordFlow(getQueryTick(), new EnergyFlowData(amperes, pathVoltage)); + } + + private static int calculateHeatV(long amperage, long voltage, long maxVoltage) { + return (int) (amperage * (Math.log1p(Math.log((double) voltage / maxVoltage)) * 45 + 36.5)); + } + + private static int calculateHeatA(long amperage, long voltage) { + return (int) (amperage * (Math.log1p(Math.log((double) voltage)) * 45 + 36.5)); + } + + protected static class OverVoltageInformation implements LongSupplier { + + public final long voltageCap; + + private final long amperage; + + public OverVoltageInformation(long voltageCap, long amperage) { + this.voltageCap = voltageCap; + this.amperage = amperage; + } + + @Override + public long getAsLong() { + return voltageCap; + } + + public void doHeating(WorldPipeNetNode node, long finalVoltage, long tick) { + TemperatureLogic logic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + if (logic != null) { + logic.applyThermalEnergy(calculateHeatV(amperage, finalVoltage, voltageCap), tick); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java new file mode 100644 index 0000000000..d02bbe09eb --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java @@ -0,0 +1,45 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.capability.IEnergyContainer; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; +import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface IEnergyTransferController { + + TransferControl CONTROL = new TransferControl<>("Energy") { + + @Override + public @NotNull IEnergyTransferController get(@Nullable Object potentialHolder) { + if (!(potentialHolder instanceof TransferControlProvider holder)) return DEFAULT; + IEnergyTransferController found = holder.getControllerForControl(CONTROL); + return found == null ? DEFAULT : found; + } + + @Override + public @NotNull IEnergyTransferController getNoPassage() { + return NO_PASSAGE; + } + }; + + IEnergyTransferController DEFAULT = new IEnergyTransferController() {}; + + IEnergyTransferController NO_PASSAGE = new IEnergyTransferController() { + + @Override + public long insertToHandler(long voltage, long amperage, @NotNull IEnergyContainer destHandler, + Direction side, boolean simulate) { + return 0; + } + }; + + /** + * @return inserted amperes + */ + default long insertToHandler(long voltage, long amperage, @NotNull IEnergyContainer destHandler, Direction side, + boolean simulate) { + return destHandler.acceptEnergyFromNetwork(side, voltage, amperage, simulate); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java new file mode 100644 index 0000000000..d38ab8aced --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java @@ -0,0 +1,22 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.graphnet.logic.AbstractIntLogicData; +import org.jetbrains.annotations.NotNull; + +public final class SuperconductorLogic extends AbstractIntLogicData { + + public static final SuperconductorLogic INSTANCE = new SuperconductorLogic().setValue(0); + + public SuperconductorLogic() { + super("Superconductor"); + } + + public boolean canSuperconduct(int temp) { + return this.getValue() > temp; + } + + @Override + public @NotNull SuperconductorLogic getNew() { + return new SuperconductorLogic(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java new file mode 100644 index 0000000000..e58300b4b0 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java @@ -0,0 +1,26 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import org.jetbrains.annotations.NotNull; + +public final class VoltageLimitLogic extends AbstractLongLogicData { + + public static final VoltageLimitLogic INSTANCE = new VoltageLimitLogic().setValue(0); + + private VoltageLimitLogic() { + super("VoltageLimit"); + } + + @Override + public @NotNull VoltageLimitLogic getNew() { + return new VoltageLimitLogic().setValue(INSTANCE.getValue()); + } + + @Override + public VoltageLimitLogic union(NetLogicEntry other) { + if (other instanceof VoltageLimitLogic l) { + return this.getValue() < l.getValue() ? this : l; + } else return this; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java new file mode 100644 index 0000000000..5bf1cbd2a2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java @@ -0,0 +1,26 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import org.jetbrains.annotations.NotNull; + +public final class VoltageLossLogic extends AbstractLongLogicData { + + public static final VoltageLossLogic INSTANCE = new VoltageLossLogic().setValue(0); + + private VoltageLossLogic() { + super("VoltageLoss"); + } + + @Override + public @NotNull VoltageLossLogic getNew() { + return new VoltageLossLogic(); + } + + @Override + public VoltageLossLogic union(NetLogicEntry other) { + if (other instanceof VoltageLossLogic l) { + return this.getWith(this.getValue() + l.getValue()); + } else return this; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java new file mode 100644 index 0000000000..bbc0675f57 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java @@ -0,0 +1,73 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.AbstractGroupData; +import com.gregtechceu.gtceu.api.graphnet.alg.DynamicWeightsShortestPathsAlgorithm; +import com.gregtechceu.gtceu.api.graphnet.edge.NetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.common.capabilities.Capability; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public final class WorldEnergyNet extends WorldPipeNet implements FlowWorldPipeNetPath.Provider { + + public static final Capability[] CAPABILITIES = new Capability[] { GTCapability.CAPABILITY_ENERGY_CONTAINER }; + + private static final String DATA_ID = "gtceu_world_energy_net"; + + public static WorldEnergyNet getWorldNet(ServerLevel serverLevel) { + return serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldEnergyNet net = new WorldEnergyNet(); + net.load(tag); + return net; + }, WorldEnergyNet::new, DATA_ID); + } + + public WorldEnergyNet() { + super(false, DynamicWeightsShortestPathsAlgorithm::new); + } + + @Override + public boolean usesDynamicWeights(int algorithmID) { + return true; + } + + @Override + public Capability[] getTargetCapabilities() { + return CAPABILITIES; + } + + @Override + public IPipeCapabilityObject[] getNewCapabilityObjects(WorldPipeNetNode node) { + return new IPipeCapabilityObject[] { new EnergyCapabilityObject(this, node) }; + } + + @Override + public Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + return backer.getPaths(node, 0, FlowWorldPipeNetPath.MAPPER, testObject, simulator, queryTick); + } + + @Override + public @NotNull NetFlowEdge getNewEdge() { + return new NetFlowEdge(1); + } + + @Override + public AbstractGroupData getBlankGroupData() { + return new EnergyGroupData(); + } + + @Override + public int getNetworkID() { + return 0; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java new file mode 100644 index 0000000000..eb142ff3f0 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java @@ -0,0 +1,42 @@ +package com.gregtechceu.gtceu.common.pipelike.net.laser; + +import com.gregtechceu.gtceu.api.capability.ILaserRelay; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface ILaserTransferController { + + TransferControl CONTROL = new TransferControl<>("Laser") { + + @Override + public @NotNull ILaserTransferController get(@Nullable Object potentialHolder) { + if (!(potentialHolder instanceof TransferControlProvider holder)) return DEFAULT; + ILaserTransferController found = holder.getControllerForControl(CONTROL); + return found == null ? DEFAULT : found; + } + + @Override + public @NotNull ILaserTransferController getNoPassage() { + return NO_PASSAGE; + } + }; + + ILaserTransferController DEFAULT = new ILaserTransferController() {}; + + ILaserTransferController NO_PASSAGE = new ILaserTransferController() { + + @Override + public long insertToHandler(long voltage, long amperage, @NotNull ILaserRelay destHandler) { + return 0; + } + }; + + /** + * @return inserted amperes + */ + default long insertToHandler(long voltage, long amperage, @NotNull ILaserRelay destHandler) { + return destHandler.receiveLaser(voltage, amperage); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java new file mode 100644 index 0000000000..f3153683f9 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java @@ -0,0 +1,87 @@ +package com.gregtechceu.gtceu.common.pipelike.net.laser; + +import com.gregtechceu.gtceu.api.capability.ILaserRelay; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.pipenet.BasicWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.common.pipelike.net.SlowActiveWalker; +import com.lowdragmc.lowdraglib.Platform; +import lombok.Setter; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public class LaserCapabilityObject implements IPipeCapabilityObject, ILaserRelay { + + private final WorldPipeNet net; + @Setter + private @Nullable PipeBlockEntity tile; + + private boolean transmitting; + + public LaserCapabilityObject(@NotNull N net) { + this.net = net; + } + + private BasicWorldPipeNetPath.Provider getProvider() { + return (BasicWorldPipeNetPath.Provider) net; + } + + private Iterator getPaths() { + assert tile != null; + long tick = Platform.getMinecraftServer().getTickCount(); + return getProvider().getPaths(net.getNode(tile.getBlockPos()), IPredicateTestObject.INSTANCE, null, tick); + } + + @Override + public long receiveLaser(long laserVoltage, long laserAmperage) { + if (tile == null || this.transmitting) return 0; + this.transmitting = true; + + long available = laserAmperage; + for (Iterator it = getPaths(); it.hasNext();) { + BasicWorldPipeNetPath path = it.next(); + WorldPipeNetNode destination = path.getTargetNode(); + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + ILaserRelay laser = capability.getValue() + .getCapability(GTCapability.CAPABILITY_LASER, capability.getKey().getOpposite()).resolve().orElse(null); + if (laser != null) { + long transmitted = ILaserTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(laserVoltage, laserAmperage, laser); + if (transmitted > 0) { + SlowActiveWalker.dispatch(tile.getLevel(), path, 1, 2, 2); + available -= transmitted; + if (available <= 0) { + this.transmitting = false; + return laserAmperage; + } + } + } + } + } + this.transmitting = false; + + return laserAmperage - available; + } + + @Override + public Capability[] getCapabilities() { + return WorldLaserNet.CAPABILITIES; + } + + @Override + public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { + if (capability == GTCapability.CAPABILITY_LASER) { + return GTCapability.CAPABILITY_LASER.orEmpty(capability, LazyOptional.of(() -> this)); + } + return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java new file mode 100644 index 0000000000..5fa7623337 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java @@ -0,0 +1,55 @@ +package com.gregtechceu.gtceu.common.pipelike.net.laser; + +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.alg.SinglePathAlgorithm; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.BasicWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.common.capabilities.Capability; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public class WorldLaserNet extends WorldPipeNet implements BasicWorldPipeNetPath.Provider { + + public static final Capability[] CAPABILITIES = new Capability[] { GTCapability.CAPABILITY_LASER }; + + private static final String DATA_ID = "gtceu_world_laser_net"; + + public static WorldLaserNet getWorldNet(ServerLevel serverLevel) { + return serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldLaserNet net = new WorldLaserNet(); + net.load(tag); + return net; + }, WorldLaserNet::new, DATA_ID); + } + + public WorldLaserNet() { + super(false, SinglePathAlgorithm::new); + } + + @Override + public Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + return backer.getPaths(node, 0, BasicWorldPipeNetPath.MAPPER, testObject, simulator, queryTick); + } + + @Override + public Capability[] getTargetCapabilities() { + return CAPABILITIES; + } + + @Override + public IPipeCapabilityObject[] getNewCapabilityObjects(WorldPipeNetNode node) { + return new IPipeCapabilityObject[] { new LaserCapabilityObject(this) }; + } + + @Override + public int getNetworkID() { + return 3; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java new file mode 100644 index 0000000000..507812f2c3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java @@ -0,0 +1,96 @@ +package com.gregtechceu.gtceu.common.pipelike.net.optical; + +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; +import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; +import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.pipenet.BasicWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.common.pipelike.block.optical.IOpticalTransferController; +import com.gregtechceu.gtceu.common.pipelike.net.SlowActiveWalker; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import lombok.Setter; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; +import java.util.Set; + +public class DataCapabilityObject implements IPipeCapabilityObject, IDataAccess { + + private final WorldPipeNet net; + + @Setter + private @Nullable PipeBlockEntity tile; + + private final Set recentQueries = GTUtil.createWeakHashSet(); + + public DataCapabilityObject(@NotNull N net) { + this.net = net; + } + + private BasicWorldPipeNetPath.Provider getProvider() { + return (BasicWorldPipeNetPath.Provider) net; + } + + @Override + public boolean accessData(@NotNull DataQueryObject queryObject) { + if (tile == null) return false; + // if the add call fails (because the object already exists in the set) then do not recurse + if (!recentQueries.add(queryObject)) return false; + + for (Iterator it = getPaths(); it.hasNext();) { + BasicWorldPipeNetPath path = it.next(); + WorldPipeNetNode destination = path.getTargetNode(); + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + IDataAccess access = capability.getValue() + .getCapability(GTCapability.CAPABILITY_DATA_ACCESS, + capability.getKey().getOpposite()).resolve().orElse(null); + if (access != null) { + queryObject.setShouldTriggerWalker(false); + boolean cancelled = IOpticalTransferController.CONTROL + .get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())) + .queryHandler(queryObject, access); + if (queryObject.shouldTriggerWalker()) { + SlowActiveWalker.dispatch(tile.getLevel(), path, 1); + } + if (cancelled) return true; + } + } + } + return false; + } + + @Override + public @NotNull DataAccessFormat getFormat() { + return DataAccessFormat.UNIVERSAL; + } + + private Iterator getPaths() { + assert tile != null; + long tick = Platform.getMinecraftServer().getTickCount(); + return getProvider().getPaths(net.getNode(tile.getBlockPos()), IPredicateTestObject.INSTANCE, null, tick); + } + + @Override + public Capability[] getCapabilities() { + return WorldOpticalNet.CAPABILITIES; + } + + @Override + public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { + if (capability == GTCapability.CAPABILITY_DATA_ACCESS) { + return GTCapability.CAPABILITY_DATA_ACCESS.orEmpty(capability, LazyOptional.of(() -> this)); + } + return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java new file mode 100644 index 0000000000..b1fe7c0e83 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java @@ -0,0 +1,55 @@ +package com.gregtechceu.gtceu.common.pipelike.net.optical; + +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.alg.SinglePathAlgorithm; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.BasicWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.common.capabilities.Capability; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public class WorldOpticalNet extends WorldPipeNet implements BasicWorldPipeNetPath.Provider { + + public static final Capability[] CAPABILITIES = new Capability[] { GTCapability.CAPABILITY_DATA_ACCESS }; + + private static final String DATA_ID = "gtceu_world_optical_net"; + + public static WorldOpticalNet getWorldNet(ServerLevel serverLevel) { + return serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldOpticalNet net = new WorldOpticalNet(); + net.load(tag); + return net; + }, WorldOpticalNet::new, DATA_ID); + } + + public WorldOpticalNet() { + super(false, SinglePathAlgorithm::new); + } + + @Override + public Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + return backer.getPaths(node, 0, BasicWorldPipeNetPath.MAPPER, testObject, simulator, queryTick); + } + + @Override + public Capability[] getTargetCapabilities() { + return CAPABILITIES; + } + + @Override + public IPipeCapabilityObject[] getNewCapabilityObjects(WorldPipeNetNode node) { + return new IPipeCapabilityObject[] { new DataCapabilityObject(this) }; + } + + @Override + public int getNetworkID() { + return 4; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java index d2595fab50..d5f2538c62 100644 --- a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java @@ -619,6 +619,11 @@ public static class ClientConfigs { @Configurable.Comment({ "Duration of UI animations in ms", "Default: 300" }) @Configurable.Range(min = 1) public int animationTime = 300; + + @Configurable + @Configurable.Comment({ "Prevent optical and laser cables from animating when active.", "Default: false" }) + public boolean preventAnimatedCables = false; + @Configurable public ArmorHud armorHud = new ArmorHud(); diff --git a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java index 2072bda138..24e12d07d6 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java @@ -30,6 +30,7 @@ import net.minecraft.tags.TagEntry; import net.minecraft.tags.TagKey; import net.minecraft.tags.TagLoader; +import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantments; @@ -53,6 +54,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.function.Consumer; import java.util.function.Supplier; public class MixinHelpers { @@ -290,4 +292,10 @@ public static void addFluidTexture(Material material, FluidStorage.FluidEntry va } } } + + public static void loadBakedModelTextures(ResourceLocation atlas, Consumer consumer) { + if (atlas.equals(InventoryMenu.BLOCK_ATLAS)) { + + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java new file mode 100644 index 0000000000..2380df0c14 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java @@ -0,0 +1,35 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.core.MixinHelpers; +import com.lowdragmc.lowdraglib.client.renderer.IRenderer; +import net.minecraft.client.renderer.texture.atlas.SpriteResourceLoader; +import net.minecraft.client.renderer.texture.atlas.SpriteSource; +import net.minecraft.client.renderer.texture.atlas.sources.SingleFile; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.asm.mixin.injection.callback.LocalCapture; + +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +@Mixin(SpriteResourceLoader.class) +public class SpriteResourceLoaderMixin { + + // try to load all renderer textures + @Inject(method = "load", at = @At(value = "RETURN"), + locals = LocalCapture.CAPTURE_FAILHARD) + private static void injectLoad(ResourceManager resourceManager, ResourceLocation location, CallbackInfoReturnable cir, ResourceLocation resourceLocation, List list) { + ResourceLocation atlas = new ResourceLocation(location.getNamespace(), "textures/atlas/%s.png".formatted(location.getPath())); + Set sprites = new HashSet<>(); + MixinHelpers.loadBakedModelTextures(atlas, sprites::add); + for (ResourceLocation sprite : sprites) { + list.add(new SingleFile(sprite, Optional.empty())); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java index 478065c3b2..a88889f821 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java @@ -400,6 +400,13 @@ public static DyeColor determineDyeColor(int rgbColor) { return distances.get(min); } + public static double geometricMean(double first, double... numbers) { + for (double number : numbers) { + first *= number; + } + return Math.pow(first, 1D / (1 + numbers.length)); + } + public static long binarySearch(long minValue, long maxValue, LongPredicate test, boolean ascending) { while (maxValue - minValue > 1) { long middle = (minValue + maxValue) / 2; diff --git a/src/main/resources/gtceu.mixins.json b/src/main/resources/gtceu.mixins.json index ec71dfef3b..dcc6c476cc 100644 --- a/src/main/resources/gtceu.mixins.json +++ b/src/main/resources/gtceu.mixins.json @@ -16,6 +16,7 @@ "LevelRendererMixin", "ModelManagerMixin", "MultiPlayerGameModeMixin", + "SpriteResourceLoaderMixin", "rei.FluidEntryRendererMixin" ], "mixins": [ From 841d51974a625e15604112c62a9b8f1d087c3125 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 22 Aug 2024 16:46:36 +0300 Subject: [PATCH 05/70] stuff --- .../api/blockentity/PipeBlockEntity.java | 10 +- .../gtceu/api/cover/filter/Filter.java | 44 +++ .../gtceu/api/cover/filter/FluidFilter.java | 5 + .../gtceu/api/cover/filter/ItemFilter.java | 5 + .../api/cover/filter/SimpleFluidFilter.java | 11 + .../api/cover/filter/SimpleItemFilter.java | 11 + .../gtceu/api/cover/filter/TagFilter.java | 5 + .../api/cover/filter/TagFluidFilter.java | 7 + .../gtceu/api/cover/filter/TagItemFilter.java | 7 + .../physical/tile/PipeCoverHolder.java | 19 +- .../pipenet/predicate/FilterPredicate.java | 32 +- .../traverse/SimpleTileRoundRobinData.java | 2 +- .../predicate/NetPredicateRegistry.java | 2 +- .../gtceu/api/item/OpticalPipeBlockItem.java | 29 -- .../trait/NotifiableComputationContainer.java | 7 +- .../gtceu/api/pipenet/PipeCoverContainer.java | 226 ----------- .../renderer/cover/ICoverableRenderer.java | 2 +- .../gtceu/common/block/CableBlock.java | 146 ------- .../gtceu/common/block/OpticalPipeBlock.java | 117 ------ .../common/blockentity/CableBlockEntity.java | 365 ------------------ .../blockentity/OpticalPipeBlockEntity.java | 223 ----------- .../gtceu/common/data/GTBlockEntities.java | 17 +- .../gtceu/common/data/GTBlocks.java | 120 +++--- .../gtceu/common/data/GTCreativeModeTabs.java | 3 +- .../cable/AveragingPerTickCounter.java | 87 ----- .../common/pipelike/cable/CableData.java | 61 --- .../common/pipelike/cable/EnergyNet.java | 94 ----- .../pipelike/cable/EnergyNetHandler.java | 164 -------- .../pipelike/cable/EnergyNetWalker.java | 84 ---- .../pipelike/cable/EnergyRoutePath.java | 44 --- .../common/pipelike/cable/Insulation.java | 103 ----- .../common/pipelike/cable/LevelEnergyNet.java | 28 -- .../pipelike/cable/PerTickLongCounter.java | 58 --- .../common/pipelike/laser/LaserPipeNet.java | 3 +- .../common/pipelike/laser/LaserRoutePath.java | 5 +- .../pipelike/optical/LevelOpticalPipeNet.java | 29 -- .../pipelike/optical/OpticalNetHandler.java | 126 ------ .../pipelike/optical/OpticalNetWalker.java | 73 ---- .../pipelike/optical/OpticalPipeNet.java | 64 --- .../optical/OpticalPipeProperties.java | 6 - .../pipelike/optical/OpticalPipeType.java | 41 -- .../pipelike/optical/OpticalRoutePath.java | 57 --- .../data/recipe/misc/ComputerRecipes.java | 22 +- .../jade/provider/CableBlockProvider.java | 9 +- .../top/provider/CableInfoProvider.java | 10 +- 45 files changed, 198 insertions(+), 2385 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/item/OpticalPipeBlockItem.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeCoverContainer.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/block/OpticalPipeBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/blockentity/CableBlockEntity.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/AveragingPerTickCounter.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/CableData.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetWalker.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyRoutePath.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/Insulation.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/LevelEnergyNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/PerTickLongCounter.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/LevelOpticalPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetHandler.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetWalker.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeProperties.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalRoutePath.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java index b02b8c1add..09acd7473a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java @@ -71,11 +71,6 @@ public abstract class PipeBlockEntity & IPipeTyp private final FieldManagedStorage syncStorage = new FieldManagedStorage(this); private final long offset = GTValues.RNG.nextInt(20); - @Getter - @DescSynced - @Persisted(key = "cover") - protected final PipeCoverContainer coverContainer; - @Getter @Setter @DescSynced @@ -108,7 +103,6 @@ public abstract class PipeBlockEntity & IPipeTyp public PipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); - this.coverContainer = new PipeCoverContainer(this); this.serverTicks = new ArrayList<>(); this.waitingToAdd = new ArrayList<>(); } @@ -146,13 +140,11 @@ public long getOffsetTimer() { @Override public void setRemoved() { super.setRemoved(); - coverContainer.onUnload(); } @Override public void clearRemoved() { super.clearRemoved(); - coverContainer.onLoad(); } @Override @@ -373,7 +365,7 @@ public Pair onToolClick(Set toolTypes var hitResult = new BlockHitResult(context.getClickLocation(), context.getClickedFace(), context.getClickedPos(), false); Direction gridSide = ICoverable.determineGridSideHit(hitResult); - CoverBehavior coverBehavior = gridSide == null ? null : coverContainer.getCoverAtSide(gridSide); + CoverBehavior coverBehavior = null; if (gridSide == null) gridSide = hitResult.getDirection(); // Prioritize covers where they apply (Screwdriver, Soft Mallet) diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java index f0e84e5c62..358c46f7da 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java @@ -2,10 +2,13 @@ import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; +import lombok.RequiredArgsConstructor; import net.minecraft.nbt.CompoundTag; +import net.minecraft.util.StringRepresentable; import java.util.function.Consumer; import java.util.function.Predicate; +import java.util.function.Supplier; /** * @author KilaBash @@ -16,6 +19,8 @@ public interface Filter> extends Predicate { WidgetGroup openConfigurator(int x, int y); + void loadFilter(CompoundTag tag); + CompoundTag saveFilter(); void setOnUpdated(Consumer onUpdated); @@ -25,4 +30,43 @@ default boolean isBlackList() { } default void setBlackList(boolean blackList) {} + + default boolean testGeneric(Object test) { + return this.test((T) test); + } + + @RequiredArgsConstructor + enum FilterType implements StringRepresentable { + ITEM("item", SimpleItemFilter::new), + ITEM_TAG("item_tag", TagItemFilter::new), + FLUID("fluid", SimpleFluidFilter::new), + FLUID_TAG("fluid_tag", TagFluidFilter::new) + ; + + private final String name; + private final Supplier> constructor; + + @Override + public String getSerializedName() { + return name; + } + + public static FilterType getByName(String name) { + return switch (name) { + case "item" -> FilterType.ITEM; + case "item_tag" -> FilterType.ITEM_TAG; + case "fluid" -> FilterType.FLUID; + case "fluid_tag" -> FilterType.FLUID_TAG; + default -> throw new IllegalStateException("Unexpected value: " + name); + }; + } + + public static Filter makeNew(FilterType filterType) { + return filterType.constructor.get(); + } + + public static Filter makeNew(String filterType) { + return getByName(filterType).constructor.get(); + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java index 852533a1ad..041fa8ee04 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java @@ -63,6 +63,11 @@ public WidgetGroup openConfigurator(int x, int y) { throw new NotImplementedException("Not available for empty fluid filter"); } + @Override + public void loadFilter(CompoundTag tag) { + throw new NotImplementedException("Not available for empty fluid filter"); + } + @Override public CompoundTag saveFilter() { throw new NotImplementedException("Not available for empty fluid filter"); diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java index a1fcd32b17..7c8d5181d0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java @@ -66,6 +66,11 @@ public WidgetGroup openConfigurator(int x, int y) { throw new NotImplementedException("Not available for empty item filter"); } + @Override + public void loadFilter(CompoundTag tag) { + throw new NotImplementedException("Not available for empty item filter"); + } + @Override public CompoundTag saveFilter() { throw new NotImplementedException("Not available for empty item filter"); diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java index 80cc6ce02a..41cc7f78ca 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java @@ -73,8 +73,19 @@ public void setOnUpdated(Consumer onUpdated) { }; } + @Override + public void loadFilter(CompoundTag tag) { + this.isBlackList = tag.getBoolean("isBlackList"); + this.ignoreNbt = tag.getBoolean("matchNbt"); + var list = tag.getList("matches", Tag.TAG_COMPOUND); + for (int i = 0; i < list.size(); i++) { + this.matches[i] = FluidStack.loadFromTag((CompoundTag) list.get(i)); + } + } + public CompoundTag saveFilter() { var tag = new CompoundTag(); + tag.putString("type", FilterType.FLUID.getSerializedName()); tag.putBoolean("isBlackList", isBlackList); tag.putBoolean("matchNbt", ignoreNbt); var list = new ListTag(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java index 16be254469..d7d4995901 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java @@ -72,8 +72,19 @@ public void setOnUpdated(Consumer onUpdated) { }; } + @Override + public void loadFilter(CompoundTag tag) { + this.isBlackList = tag.getBoolean("isBlackList"); + this.ignoreNbt = tag.getBoolean("matchNbt"); + var list = tag.getList("matches", Tag.TAG_COMPOUND); + for (int i = 0; i < list.size(); i++) { + this.matches[i] = ItemStack.of((CompoundTag) list.get(i)); + } + } + public CompoundTag saveFilter() { var tag = new CompoundTag(); + tag.putString("type", FilterType.ITEM.getSerializedName()); tag.putBoolean("isBlackList", isBlackList); tag.putBoolean("matchNbt", ignoreNbt); var list = new ListTag(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFilter.java index 5fa5e1537f..47a914dc7b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFilter.java @@ -42,6 +42,11 @@ public abstract class TagFilter> implements Filter return handler; } + @Override + public CompoundTag saveFilter() { + CompoundTag tag = super.saveFilter(); + tag.putString("type", FilterType.FLUID_TAG.getSerializedName()); + return tag; + } + public void setOreDict(String oreDict) { cache.clear(); super.setOreDict(oreDict); diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java index aa7f34c080..ecc5f91bb5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java @@ -36,6 +36,13 @@ private static TagItemFilter loadFilter(CompoundTag tag, Consumer it return handler; } + @Override + public CompoundTag saveFilter() { + CompoundTag tag = super.saveFilter(); + tag.putString("type", FilterType.FLUID_TAG.getSerializedName()); + return tag; + } + public void setOreDict(String oreDict) { cache.clear(); super.setOreDict(oreDict); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java index 9ff59262de..2186a16f39 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -8,16 +8,15 @@ import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.utils.GTUtil; - import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; -import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; +import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; - +import lombok.Getter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.entity.player.Player; @@ -27,7 +26,6 @@ import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; - import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,6 +33,10 @@ public class PipeCoverHolder implements ICoverable, IEnhancedManaged { + public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(PipeCoverHolder.class); + @Getter + private final FieldManagedStorage syncStorage = new FieldManagedStorage(this); + private final PipeBlockEntity holder; @Persisted @DescSynced @@ -270,14 +272,11 @@ public void unsubscribe(@Nullable TickableSubscription current) { @Override public ManagedFieldHolder getFieldHolder() { - return null; + return MANAGED_FIELD_HOLDER; } @Override - public IManagedStorage getSyncStorage() { - return null; + public void onChanged() { + holder.onChanged(); } - - @Override - public void onChanged() {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java index 5ba7df0c6b..0ef29aae6a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java @@ -1,9 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.predicate; +import com.gregtechceu.gtceu.api.cover.filter.Filter; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.gregtechceu.gtceu.common.cover.filter.BaseFilterContainer; +import lombok.Setter; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; @@ -16,38 +18,32 @@ public final class FilterPredicate extends EdgePredicate sourceFilter; + @Setter + private @Nullable Filter targetFilter; private FilterPredicate() { super("FluidFilter"); } - public void setSourceFilter(@Nullable BaseFilterContainer sourceFilter) { - this.sourceFilter = sourceFilter; - } - - public void setTargetFilter(@Nullable BaseFilterContainer targetFilter) { - this.targetFilter = targetFilter; - } - @Override public CompoundTag serializeNBT() { CompoundTag tag = new CompoundTag(); - if (sourceFilter != null) tag.put("Source", sourceFilter.serializeNBT()); - if (targetFilter != null) tag.put("Target", targetFilter.serializeNBT()); + if (sourceFilter != null) tag.put("Source", sourceFilter.saveFilter()); + if (targetFilter != null) tag.put("Target", targetFilter.saveFilter()); return tag; } @Override public void deserializeNBT(CompoundTag nbt) { if (nbt.contains("Source")) { - sourceFilter = new GenericFilterContainer(); - sourceFilter.deserializeNBT(nbt.getCompound("Source")); + sourceFilter = Filter.FilterType.makeNew(nbt.getCompound("Source").getString("type")); + sourceFilter.loadFilter(nbt.getCompound("Source")); } else sourceFilter = null; if (nbt.contains("Target")) { - targetFilter = new GenericFilterContainer(); - targetFilter.deserializeNBT(nbt.getCompound("Target")); + targetFilter = Filter.FilterType.makeNew(nbt.getCompound("Target").getString("type")); + targetFilter.loadFilter(nbt.getCompound("Target")); } else targetFilter = null; } @@ -64,8 +60,8 @@ public boolean andy() { @Override public boolean test(IPredicateTestObject object) { Object test = object.recombine(); - if (sourceFilter != null && !sourceFilter.test(test)) return false; - return targetFilter == null || targetFilter.test(test); + if (sourceFilter != null && !sourceFilter.testGeneric(test)) return false; + return targetFilter == null || targetFilter.testGeneric(test); } private static class GenericFilterContainer extends BaseFilterContainer { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java index 665c00be32..ab13268b3d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/SimpleTileRoundRobinData.java @@ -36,6 +36,6 @@ public void progressToNextInternalDestination(WorldPipeNetNode node, @Nullable S } public @Nullable T getAtPointer(WorldPipeNetNode node, @Nullable SimulatorKey simulator) { - return getCapabilityAtPointer(cap, node, simulator); + return getCapabilityAtPointer(cap, node, simulator).resolve().orElse(null); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java index 7c74e704f3..ccf99b289a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java @@ -12,7 +12,7 @@ public final class NetPredicateRegistry { private static final Map>> REGISTRY = new Object2ObjectOpenHashMap<>(); static void register(@NotNull EdgePredicate predicate) { - REGISTRY.putIfAbsent(predicate.getName(), predicate::getNew); + REGISTRY.putIfAbsent(predicate.getSerializedName(), predicate::getNew); } public static @Nullable Supplier<@NotNull EdgePredicate> getSupplierNullable(String name) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/OpticalPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/OpticalPipeBlockItem.java deleted file mode 100644 index ed59e05ded..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/item/OpticalPipeBlockItem.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.gregtechceu.gtceu.api.item; - -import com.gregtechceu.gtceu.common.block.OpticalPipeBlock; - -import com.lowdragmc.lowdraglib.client.renderer.IItemRendererProvider; -import com.lowdragmc.lowdraglib.client.renderer.IRenderer; - -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.Nullable; - -import javax.annotation.ParametersAreNonnullByDefault; - -@ParametersAreNonnullByDefault -public class OpticalPipeBlockItem extends PipeBlockItem implements IItemRendererProvider { - - public OpticalPipeBlockItem(OpticalPipeBlock block, Properties properties) { - super(block, properties); - } - - @Nullable - @Override - @OnlyIn(Dist.CLIENT) - public IRenderer getRenderer(ItemStack stack) { - return getBlock().getRenderer(getBlock().defaultBlockState()); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java index adc57c3006..029451a8c8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java @@ -14,7 +14,6 @@ import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiController; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiPart; import com.gregtechceu.gtceu.api.recipe.GTRecipe; -import com.gregtechceu.gtceu.common.blockentity.OpticalPipeBlockEntity; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.core.Direction; @@ -276,10 +275,8 @@ public IOpticalComputationProvider getComputationProvider() { private IOpticalComputationProvider getOpticalNetProvider() { for (Direction direction : GTUtil.DIRECTIONS) { BlockEntity blockEntity = machine.getLevel().getBlockEntity(machine.getPos().relative(direction)); - if (blockEntity instanceof OpticalPipeBlockEntity) { - return blockEntity.getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, direction.getOpposite()) - .orElse(null); - } + return blockEntity.getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, direction.getOpposite()) + .resolve().orElse(null); } return null; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeCoverContainer.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeCoverContainer.java deleted file mode 100644 index 95ceb763f7..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeCoverContainer.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.cover.CoverDefinition; -import com.gregtechceu.gtceu.api.machine.TickableSubscription; -import com.gregtechceu.gtceu.api.registry.GTRegistries; -import com.gregtechceu.gtceu.common.blockentity.FluidPipeBlockEntity; -import com.gregtechceu.gtceu.common.blockentity.ItemPipeBlockEntity; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; -import com.lowdragmc.lowdraglib.side.item.IItemTransfer; -import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; -import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; -import com.lowdragmc.lowdraglib.syncdata.annotation.ReadOnlyManaged; -import com.lowdragmc.lowdraglib.syncdata.annotation.UpdateListener; -import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; -import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.Level; - -import lombok.Getter; -import org.jetbrains.annotations.Nullable; - -/** - * @author KilaBash - * @date 2023/2/18 - * @implNote PipeCoverContainer - */ - -public class PipeCoverContainer implements ICoverable, IEnhancedManaged { - - public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(PipeCoverContainer.class); - @Getter - private final FieldManagedStorage syncStorage = new FieldManagedStorage(this); - private final IPipeNode pipeTile; - - @DescSynced - @Persisted - @UpdateListener(methodName = "onCoverSet") - @ReadOnlyManaged(onDirtyMethod = "onCoverDirty", - serializeMethod = "serializeCoverUid", - deserializeMethod = "deserializeCoverUid") - private CoverBehavior up, down, north, south, west, east; - - public PipeCoverContainer(IPipeNode pipeTile) { - this.pipeTile = pipeTile; - } - - @SuppressWarnings("unused") - private void onCoverSet(CoverBehavior newValue, CoverBehavior oldValue) { - if (newValue != oldValue && (newValue == null || oldValue == null)) { - scheduleRenderUpdate(); - } - } - - @Override - public ManagedFieldHolder getFieldHolder() { - return MANAGED_FIELD_HOLDER; - } - - @Override - public void onChanged() { - var level = getLevel(); - if (level != null && !level.isClientSide && level.getServer() != null) { - level.getServer().execute(this::markDirty); - } - } - - @Override - public Level getLevel() { - return pipeTile.getPipeLevel(); - } - - @Override - public BlockPos getPos() { - return pipeTile.getPipePos(); - } - - @Override - public long getOffsetTimer() { - return pipeTile.getOffsetTimer(); - } - - @Override - public void markDirty() { - pipeTile.markAsDirty(); - } - - @Override - public void notifyBlockUpdate() { - pipeTile.notifyBlockUpdate(); - } - - @Override - public void scheduleRenderUpdate() { - pipeTile.scheduleRenderUpdate(); - } - - @Override - public void scheduleNeighborShapeUpdate() { - pipeTile.scheduleNeighborShapeUpdate(); - } - - @Override - public boolean isInValid() { - return pipeTile.isInValid(); - } - - @Override - public boolean canPlaceCoverOnSide(CoverDefinition definition, Direction side) { - return getCoverAtSide(side) == null; - } - - @Override - public double getCoverPlateThickness() { - float thickness = pipeTile.getPipeType().getThickness(); - // no cover plate for pipes >= 1 block thick - if (thickness >= 1) return 0; - - // If the available space for the cover is less than the regular cover plate thickness, use that - - // need to divide by 2 because thickness is centered on the block, so the space is half on each side of the pipe - return Math.min(1.0 / 16.0, (1.0 - thickness) / 2); - } - - @Override - public Direction getFrontFacing() { - return Direction.NORTH; - } - - @Override - public boolean shouldRenderBackSide() { - return true; - } - - @Nullable - @Override - public TickableSubscription subscribeServerTick(Runnable runnable) { - return pipeTile.subscribeServerTick(runnable); - } - - @Override - public void unsubscribe(@Nullable TickableSubscription current) { - pipeTile.unsubscribe(current); - } - - @Override - public IItemTransfer getItemTransferCap(@Nullable Direction side, boolean useCoverCapability) { - if (pipeTile instanceof ItemPipeBlockEntity itemPipe) { - return getLevel() instanceof ServerLevel ? itemPipe.getHandler(side, useCoverCapability) : - IItemTransfer.EMPTY; - } else { - return null; - } - } - - @Override - public IFluidTransfer getFluidTransferCap(@Nullable Direction side, boolean useCoverCapability) { - if (pipeTile instanceof FluidPipeBlockEntity fluidPipe) { - return fluidPipe.getTankList(side); - } else { - return null; - } - } - - @Override - public CoverBehavior getCoverAtSide(Direction side) { - return switch (side) { - case UP -> up; - case SOUTH -> south; - case WEST -> west; - case DOWN -> down; - case EAST -> east; - case NORTH -> north; - }; - } - - public void setCoverAtSide(@Nullable CoverBehavior coverBehavior, Direction side) { - switch (side) { - case UP -> up = coverBehavior; - case SOUTH -> south = coverBehavior; - case WEST -> west = coverBehavior; - case DOWN -> down = coverBehavior; - case EAST -> east = coverBehavior; - case NORTH -> north = coverBehavior; - } - if (coverBehavior != null) { - coverBehavior.getSyncStorage().markAllDirty(); - } - } - - @SuppressWarnings("unused") - private boolean onCoverDirty(CoverBehavior coverBehavior) { - return coverBehavior != null && (coverBehavior.getSyncStorage().hasDirtySyncFields() || - coverBehavior.getSyncStorage().hasDirtyPersistedFields()); - } - - @SuppressWarnings("unused") - private CompoundTag serializeCoverUid(CoverBehavior coverBehavior) { - var uid = new CompoundTag(); - uid.putString("id", GTRegistries.COVERS.getKey(coverBehavior.coverDefinition).toString()); - uid.putInt("side", coverBehavior.attachedSide.ordinal()); - return uid; - } - - @SuppressWarnings("unused") - private CoverBehavior deserializeCoverUid(CompoundTag uid) { - var definitionId = new ResourceLocation(uid.getString("id")); - var side = GTUtil.DIRECTIONS[uid.getInt("side")]; - var definition = GTRegistries.COVERS.get(definitionId); - if (definition != null) { - return definition.createCoverBehavior(this, side); - } - GTCEu.LOGGER.error("couldn't find cover definition {}", definitionId); - throw new RuntimeException(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java index f2986b5d81..31f7e26145 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java @@ -82,7 +82,7 @@ default void renderCovers(List quads, @Nullable Direction side, Rando .cube(cube).cubeUV().tintIndex(-1).bake()); } } - cover.getCoverRenderer().renderCover(quads, side, rand, cover, modelFacing, pos, level, modelState); + //cover.getCoverRenderer().renderCover(quads, side, rand, cover, modelFacing, pos, level, modelState); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java deleted file mode 100644 index 22b20bc8b5..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/block/CableBlock.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.gregtechceu.gtceu.common.block; - -import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.block.MaterialPipeBlock; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.client.model.PipeModel; -import com.gregtechceu.gtceu.common.blockentity.CableBlockEntity; -import com.gregtechceu.gtceu.common.data.GTBlockEntities; -import com.gregtechceu.gtceu.common.data.GTBlocks; -import com.gregtechceu.gtceu.common.data.GTDamageTypes; -import com.gregtechceu.gtceu.common.pipelike.cable.Insulation; -import com.gregtechceu.gtceu.common.pipelike.cable.LevelEnergyNet; -import com.gregtechceu.gtceu.utils.GTUtil; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; - -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * @author KilaBash - * @date 2023/3/1 - * @implNote CableBlock - */ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public class CableBlock extends MaterialPipeBlock { - - public CableBlock(Properties properties, Insulation insulation, Material material) { - super(properties, insulation, material); - } - - @Override - public int tinted(BlockState blockState, @Nullable BlockAndTintGetter blockAndTintGetter, - @Nullable BlockPos blockPos, int index) { - if (pipeType.isCable && index == 0) { - return 0x404040; - } - return index == 0 || index == 1 ? material.getMaterialRGB() : -1; - } - - @Override - protected WireProperties createProperties(Insulation insulation, Material material) { - return insulation.modifyProperties(material.getProperty(PropertyKey.WIRE)); - } - - @Override - protected WireProperties createMaterialData() { - return material.getProperty(PropertyKey.WIRE); - } - - @Override - public LevelEnergyNet getWorldPipeNet(ServerLevel level) { - return LevelEnergyNet.getOrCreate(level); - } - - @Override - public BlockEntityType> getBlockEntityType() { - return GTBlockEntities.CABLE.get(); - } - - @Override - public boolean canPipesConnect(IPipeNode selfTile, Direction side, - IPipeNode sideTile) { - return selfTile instanceof CableBlockEntity && sideTile instanceof CableBlockEntity; - } - - @Override - public boolean canPipeConnectToBlock(IPipeNode selfTile, Direction side, - @Nullable BlockEntity tile) { - return tile != null && - tile.getCapability(GTCapability.CAPABILITY_ENERGY_CONTAINER, side.getOpposite()).isPresent(); - } - - @Override - protected PipeModel createPipeModel() { - return pipeType.createPipeModel(material); - } - - @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, - TooltipFlag flag) { - super.appendHoverText(stack, level, tooltip, flag); - WireProperties wireProperties = createProperties(defaultBlockState(), stack); - int tier = GTUtil.getTierByVoltage(wireProperties.getVoltage()); - if (wireProperties.isSuperconductor()) - tooltip.add(Component.translatable("gtceu.cable.superconductor", GTValues.VN[tier])); - tooltip.add(Component.translatable("gtceu.cable.voltage", wireProperties.getVoltage(), GTValues.VNF[tier])); - tooltip.add(Component.translatable("gtceu.cable.amperage", wireProperties.getAmperage())); - tooltip.add(Component.translatable("gtceu.cable.loss_per_block", wireProperties.getLossPerBlock())); - } - - @Override - public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { - // dont apply damage if there is a frame box - var pipeNode = getPipeTile(level, pos); - if (pipeNode.getFrameMaterial() != null) { - BlockState frameState = GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, pipeNode.getFrameMaterial()) - .getDefaultState(); - frameState.getBlock().entityInside(frameState, level, pos, entity); - return; - } - if (level.isClientSide) return; - - Insulation insulation = getPipeTile(level, pos).getPipeType(); - if (insulation.insulationLevel == -1 && entity instanceof LivingEntity entityLiving) { - CableBlockEntity cable = (CableBlockEntity) getPipeTile(level, pos); - if (cable != null && cable.getFrameMaterial() == null && cable.getNodeData().getLossPerBlock() > 0) { - long voltage = cable.getCurrentMaxVoltage(); - double amperage = cable.getAverageAmperage(); - if (voltage > 0L && amperage > 0L) { - float damageAmount = (float) ((GTUtil.getTierByVoltage(voltage) + 1) * amperage * 4); - entityLiving.hurt(GTDamageTypes.ELECTRIC.source(level), damageAmount); - if (entityLiving instanceof ServerPlayer) { - // TODO advancments - // AdvancementTriggers.ELECTROCUTION_DEATH.trigger((PlayerMP) entityLiving); - } - } - } - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/OpticalPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/OpticalPipeBlock.java deleted file mode 100644 index 015d2b002d..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/block/OpticalPipeBlock.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.gregtechceu.gtceu.common.block; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.block.PipeBlock; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.client.model.PipeModel; -import com.gregtechceu.gtceu.client.renderer.block.PipeBlockRenderer; -import com.gregtechceu.gtceu.common.blockentity.OpticalPipeBlockEntity; -import com.gregtechceu.gtceu.common.data.GTBlockEntities; -import com.gregtechceu.gtceu.common.pipelike.optical.LevelOpticalPipeNet; -import com.gregtechceu.gtceu.common.pipelike.optical.OpticalPipeProperties; -import com.gregtechceu.gtceu.common.pipelike.optical.OpticalPipeType; - -import net.minecraft.client.color.block.BlockColor; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.annotation.ParametersAreNonnullByDefault; - -@ParametersAreNonnullByDefault -public class OpticalPipeBlock extends PipeBlock { - - public final PipeBlockRenderer renderer; - @Getter - public final PipeModel pipeModel; - - private final OpticalPipeType pipeType; - private final OpticalPipeProperties properties; - - public OpticalPipeBlock(BlockBehaviour.Properties properties, @NotNull OpticalPipeType pipeType) { - super(properties, pipeType); - this.pipeType = pipeType; - this.properties = OpticalPipeProperties.INSTANCE; - this.pipeModel = new PipeModel(pipeType.getThickness(), () -> GTCEu.id("block/pipe/pipe_optical_side"), - () -> GTCEu.id("block/pipe/pipe_optical_in"), null, null); - this.renderer = new PipeBlockRenderer(this.pipeModel); - } - - @Override - public LevelOpticalPipeNet getWorldPipeNet(ServerLevel level) { - return LevelOpticalPipeNet.getOrCreate(level); - } - - @Override - public BlockEntityType> getBlockEntityType() { - return GTBlockEntities.OPTICAL_PIPE.get(); - } - - @Override - public OpticalPipeProperties createRawData(BlockState pState, @Nullable ItemStack pStack) { - return null; - } - - @Override - public OpticalPipeProperties createProperties(@NotNull IPipeNode pipeTile) { - OpticalPipeType pipeType = pipeTile.getPipeType(); - if (pipeType == null) return getFallbackType(); - return this.pipeType.modifyProperties(properties); - } - - @Override - public OpticalPipeProperties getFallbackType() { - return OpticalPipeProperties.INSTANCE; - } - - @Override - public @Nullable PipeBlockRenderer getRenderer(BlockState state) { - return renderer; - } - - @OnlyIn(Dist.CLIENT) - public static BlockColor tintedColor() { - return (blockState, level, blockPos, index) -> { - if (blockPos != null && level != null && - level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { - if (pipe.getFrameMaterial() != null) { - if (index == 3) { - return pipe.getFrameMaterial().getMaterialRGB(); - } else if (index == 4) { - return pipe.getFrameMaterial().getMaterialSecondaryRGB(); - } - } - if (pipe.isPainted()) { - return pipe.getRealColor(); - } - } - return -1; - }; - } - - @Override - public boolean canPipesConnect(IPipeNode selfTile, Direction side, - IPipeNode sideTile) { - return selfTile instanceof OpticalPipeBlockEntity && sideTile instanceof OpticalPipeBlockEntity; - } - - @Override - public boolean canPipeConnectToBlock(IPipeNode selfTile, Direction side, - @Nullable BlockEntity tile) { - if (tile == null) return false; - if (tile.getCapability(GTCapability.CAPABILITY_DATA_ACCESS, side.getOpposite()).isPresent()) return true; - return tile.getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, side.getOpposite()).isPresent(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/CableBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/CableBlockEntity.java deleted file mode 100644 index ca8e848311..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/CableBlockEntity.java +++ /dev/null @@ -1,365 +0,0 @@ -package com.gregtechceu.gtceu.common.blockentity; - -import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.IEnergyContainer; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; -import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.api.item.tool.GTToolType; -import com.gregtechceu.gtceu.api.machine.TickableSubscription; -import com.gregtechceu.gtceu.api.machine.feature.IDataInfoProvider; -import com.gregtechceu.gtceu.common.block.CableBlock; -import com.gregtechceu.gtceu.common.data.GTBlocks; -import com.gregtechceu.gtceu.common.item.PortableScannerBehavior; -import com.gregtechceu.gtceu.common.pipelike.cable.*; -import com.gregtechceu.gtceu.utils.FormattingUtil; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; -import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; -import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; - -import net.minecraft.ChatFormatting; -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * @author KilaBash - * @date 2023/3/1 - * @implNote CableBlockEntity - */ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public class CableBlockEntity extends PipeBlockEntity implements IDataInfoProvider { - - public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(CableBlockEntity.class, - PipeBlockEntity.MANAGED_FIELD_HOLDER); - - protected WeakReference currentEnergyNet = new WeakReference<>(null); - - private static final int meltTemp = 3000; - - private final EnumMap handlers = new EnumMap<>(Direction.class); - private final PerTickLongCounter maxVoltageCounter = new PerTickLongCounter(); - private final AveragingPerTickCounter averageVoltageCounter = new AveragingPerTickCounter(); - private final AveragingPerTickCounter averageAmperageCounter = new AveragingPerTickCounter(); - private EnergyNetHandler defaultHandler; - private int heatQueue; - @Getter - @Persisted - @DescSynced - private int temperature = getDefaultTemp(); - private TickableSubscription heatSubs; - - public CableBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - } - - public static CableBlockEntity create(BlockEntityType type, BlockPos pos, BlockState blockState) { - return new CableBlockEntity(type, pos, blockState); - } - - @Override - public @NotNull LazyOptional getCapability(@NotNull Capability cap, @Nullable Direction side) { - if (cap == GTCapability.CAPABILITY_ENERGY_CONTAINER) { - var container = getEnergyContainer(side); - if (container != null) { - return GTCapability.CAPABILITY_ENERGY_CONTAINER.orEmpty(cap, LazyOptional.of(() -> container)); - } - } else if (cap == GTCapability.CAPABILITY_COVERABLE) { - return GTCapability.CAPABILITY_COVERABLE.orEmpty(cap, LazyOptional.of(this::getCoverContainer)); - } else if (cap == GTCapability.CAPABILITY_TOOLABLE) { - return GTCapability.CAPABILITY_TOOLABLE.orEmpty(cap, LazyOptional.of(() -> this)); - } - return super.getCapability(cap, side); - } - - @Override - public boolean canAttachTo(Direction side) { - if (level != null) { - if (level.getBlockEntity(getBlockPos().relative(side)) instanceof CableBlockEntity) { - return false; - } - return GTCapabilityHelper.getEnergyContainer(level, getBlockPos().relative(side), side.getOpposite()) != - null; - } - return false; - } - - @Nullable - private EnergyNet getEnergyNet() { - if (!(level instanceof ServerLevel serverLevel)) - return null; - EnergyNet currentEnergyNet = this.currentEnergyNet.get(); - if (currentEnergyNet != null && currentEnergyNet.isValid() && - currentEnergyNet.containsNode(getBlockPos())) - return currentEnergyNet; // return current net if it is still valid - LevelEnergyNet worldENet = LevelEnergyNet.getOrCreate(serverLevel); - currentEnergyNet = worldENet.getNetFromPos(getBlockPos()); - if (currentEnergyNet != null) { - this.currentEnergyNet = new WeakReference<>(currentEnergyNet); - } - return currentEnergyNet; - } - - public void checkNetwork() { - if (defaultHandler != null) { - EnergyNet current = getEnergyNet(); - if (defaultHandler.getNet() != current) { - defaultHandler.updateNetwork(current); - for (EnergyNetHandler handler : handlers.values()) { - handler.updateNetwork(current); - } - } - } - } - - @Nullable - public IEnergyContainer getEnergyContainer(@Nullable Direction side) { - if (side != null && !isConnected(side)) return null; - // the EnergyNetHandler can only be created on the server, so we have an empty placeholder for the client - if (isRemote()) return IEnergyContainer.DEFAULT; - if (handlers.isEmpty()) - initHandlers(); - checkNetwork(); - return handlers.getOrDefault(side, defaultHandler); - } - - @Override - public boolean canHaveBlockedFaces() { - return false; - } - - private void initHandlers() { - EnergyNet net = getEnergyNet(); - if (net == null) { - return; - } - for (Direction facing : GTUtil.DIRECTIONS) { - handlers.put(facing, new EnergyNetHandler(net, this, facing)); - } - defaultHandler = new EnergyNetHandler(net, this, null); - } - - @Override - public void onLoad() { - super.onLoad(); - if (!level.isClientSide) { - setTemperature(temperature); - if (temperature > getDefaultTemp()) { - subscribeHeat(); - } - } - } - - private void subscribeHeat() { - if (this.heatSubs == null) { - this.heatSubs = subscribeServerTick(this::update); - } - } - - private void unsubscribeHeat() { - if (this.heatSubs != null) { - this.unsubscribe(this.heatSubs); - this.heatSubs = null; - } - } - - public CableBlock getPipeBlock() { - return (CableBlock) super.getPipeBlock(); - } - - public double getAverageAmperage() { - return averageAmperageCounter.getAverage(getLevel()); - } - - public long getCurrentMaxVoltage() { - return maxVoltageCounter.get(getLevel()); - } - - public double getAverageVoltage() { - return averageVoltageCounter.getAverage(getLevel()); - } - - public long getMaxAmperage() { - return getNodeData().getAmperage(); - } - - public long getMaxVoltage() { - return getNodeData().getVoltage(); - } - - public int getDefaultTemp() { - return 293; - } - - public static int getMeltTemp() { - return meltTemp; - } - - /** - * Should only be called internally - * - * @return if the cable should be destroyed - */ - public boolean incrementAmperage(long amps, long voltage) { - if (voltage > maxVoltageCounter.get(getLevel())) { - maxVoltageCounter.set(getLevel(), voltage); - } - averageVoltageCounter.increment(getLevel(), voltage * amps); - averageAmperageCounter.increment(getLevel(), amps); - - int dif = (int) (averageAmperageCounter.getLast(getLevel()) - getMaxAmperage()); - if (dif > 0) { - applyHeat(dif * 40); - return true; - } - - return false; - } - - public void applyHeat(int amount) { - heatQueue += amount; - if (!level.isClientSide && heatSubs == null && temperature + heatQueue > getDefaultTemp()) { - subscribeHeat(); - } - } - - private boolean update() { - if (heatQueue > 0) { - // if received heat from overvolting or overamping, add heat - setTemperature(temperature + heatQueue); - } - - if (temperature >= meltTemp) { - // cable melted - level.setBlockAndUpdate(worldPosition, Blocks.FIRE.defaultBlockState()); - return false; - } - - if (temperature <= getDefaultTemp()) { - unsubscribeHeat(); - return false; - } - - if (getPipeType().insulationLevel >= 0 && temperature >= 1500 && GTValues.RNG.nextFloat() < 0.1) { - // insulation melted - uninsulate(); - return false; - } - - if (heatQueue == 0) { - // otherwise cool down - setTemperature((int) (temperature - Math.pow(temperature - getDefaultTemp(), 0.35))); - } else { - heatQueue = 0; - } - return true; - } - - private void uninsulate() { - int temp = temperature; - setTemperature(getDefaultTemp()); - int index = getPipeType().insulationLevel; - CableBlock newBlock = GTBlocks.CABLE_BLOCKS.get(Insulation.values()[index].tagPrefix, getPipeBlock().material) - .get(); - level.setBlockAndUpdate(getBlockPos(), newBlock.defaultBlockState()); - CableBlockEntity newCable = (CableBlockEntity) level.getBlockEntity(getBlockPos()); - if (newCable != null) { // should never be null - newCable.setTemperature(temp); - newCable.subscribeHeat(); - for (Direction facing : GTUtil.DIRECTIONS) { - if (isConnected(facing)) { - newCable.setConnection(facing, true, true); - } - } - newCable.setChanged(); - // force a block rerender - newCable.scheduleRenderUpdate(); - } - } - - public void setTemperature(int temperature) { - this.temperature = temperature; - level.getLightEngine().checkBlock(worldPosition); - if (!level.isClientSide) { - var facing = Direction.UP; - float xPos = facing.getStepX() * 0.76F + worldPosition.getX() + 0.25F; - float yPos = facing.getStepY() * 0.76F + worldPosition.getY() + 0.25F; - float zPos = facing.getStepZ() * 0.76F + worldPosition.getZ() + 0.25F; - - float ySpd = facing.getStepY() * 0.1F + 0.2F + 0.1F * GTValues.RNG.nextFloat(); - float temp = GTValues.RNG.nextFloat() * 2 * (float) Math.PI; - float xSpd = (float) Math.sin(temp) * 0.1F; - float zSpd = (float) Math.cos(temp) * 0.1F; - - ((ServerLevel) level).sendParticles(ParticleTypes.SMOKE, - xPos + GTValues.RNG.nextFloat() * 0.5F, - yPos + GTValues.RNG.nextFloat() * 0.5F, - zPos + GTValues.RNG.nextFloat() * 0.5F, - 0, - xSpd, ySpd, zSpd, 1); - } - } - - public static void onBlockEntityRegister(BlockEntityType cableBlockEntityBlockEntityType) {} - - ////////////////////////////////////// - // ******* Interaction *******// - ////////////////////////////////////// - - @Override - public ResourceTexture getPipeTexture(boolean isBlock) { - return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; - } - - @Override - public GTToolType getPipeTuneTool() { - return GTToolType.WIRE_CUTTER; - } - - @Override - public ManagedFieldHolder getFieldHolder() { - return MANAGED_FIELD_HOLDER; - } - - @Override - public @NotNull List getDataInfo(PortableScannerBehavior.DisplayMode mode) { - List list = new ArrayList<>(); - - if (mode == PortableScannerBehavior.DisplayMode.SHOW_ALL || - mode == PortableScannerBehavior.DisplayMode.SHOW_ELECTRICAL_INFO) { - list.add(Component.translatable("behavior.portable_scanner.eu_per_sec", - Component.translatable(FormattingUtil.formatNumbers(getAverageVoltage())) - .withStyle(ChatFormatting.RED))); - list.add(Component.translatable("behavior.portable_scanner.amp_per_sec", - Component.translatable(FormattingUtil.formatNumbers(getAverageAmperage())) - .withStyle(ChatFormatting.RED))); - } - - return list; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java deleted file mode 100644 index a874ae5ff0..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/OpticalPipeBlockEntity.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.gregtechceu.gtceu.common.blockentity; - -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.IDataAccessHatch; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; -import com.gregtechceu.gtceu.api.capability.data.IDataAccess; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.item.tool.GTToolType; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.api.recipe.GTRecipe; -import com.gregtechceu.gtceu.common.pipelike.optical.*; -import com.gregtechceu.gtceu.utils.GTUtil; -import com.gregtechceu.gtceu.utils.TaskHandler; - -import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; -import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; -import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -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.Capability; -import net.minecraftforge.common.util.LazyOptional; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.lang.ref.WeakReference; -import java.util.Collection; -import java.util.EnumMap; - -public class OpticalPipeBlockEntity extends PipeBlockEntity { - - public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(OpticalPipeBlockEntity.class, - PipeBlockEntity.MANAGED_FIELD_HOLDER); - - private final EnumMap handlers = new EnumMap<>(Direction.class); - // the OpticalNetHandler can only be created on the server, so we have an empty placeholder for the client - private final IDataAccess clientDataHandler = new DefaultDataHandler(); - private final IOpticalComputationProvider clientComputationHandler = new DefaultComputationHandler(); - private WeakReference currentPipeNet = new WeakReference<>(null); - private OpticalNetHandler defaultHandler; - - @Getter - @Persisted - @DescSynced - @RequireRerender - private boolean isActive; - - public OpticalPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - } - - @Override - public boolean canHaveBlockedFaces() { - return false; - } - - private void initHandlers() { - OpticalPipeNet net = getOpticalPipeNet(); - if (net == null) return; - for (Direction facing : GTUtil.DIRECTIONS) { - handlers.put(facing, new OpticalNetHandler(net, this, facing)); - } - defaultHandler = new OpticalNetHandler(net, this, null); - } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == GTCapability.CAPABILITY_DATA_ACCESS) { - if (level.isClientSide) { - return GTCapability.CAPABILITY_DATA_ACCESS.orEmpty(capability, - LazyOptional.of(() -> clientDataHandler)); - } - - if (handlers.isEmpty()) initHandlers(); - - checkNetwork(); - return GTCapability.CAPABILITY_DATA_ACCESS.orEmpty(capability, - LazyOptional.of(() -> handlers.getOrDefault(facing, defaultHandler))); - } - - if (capability == GTCapability.CAPABILITY_COMPUTATION_PROVIDER) { - if (level.isClientSide) { - return GTCapability.CAPABILITY_COMPUTATION_PROVIDER.orEmpty(capability, - LazyOptional.of(() -> clientComputationHandler)); - } - - if (handlers.isEmpty()) initHandlers(); - - checkNetwork(); - return GTCapability.CAPABILITY_COMPUTATION_PROVIDER.orEmpty(capability, - LazyOptional.of(() -> handlers.getOrDefault(facing, defaultHandler))); - } - - if (capability == GTCapability.CAPABILITY_COVERABLE) { - return GTCapability.CAPABILITY_COVERABLE.orEmpty(capability, LazyOptional.of(this::getCoverContainer)); - } - - return super.getCapability(capability, facing); - } - - public void checkNetwork() { - if (defaultHandler != null) { - OpticalPipeNet current = getOpticalPipeNet(); - if (defaultHandler.getNet() != current) { - defaultHandler.updateNetwork(current); - for (OpticalNetHandler handler : handlers.values()) { - handler.updateNetwork(current); - } - } - } - } - - public OpticalPipeNet getOpticalPipeNet() { - if (level == null || level.isClientSide) - return null; - OpticalPipeNet currentPipeNet = this.currentPipeNet.get(); - if (currentPipeNet != null && currentPipeNet.isValid() && currentPipeNet.containsNode(getPipePos())) - return currentPipeNet; // if current net is valid and does contain position, return it - LevelOpticalPipeNet worldNet = (LevelOpticalPipeNet) getPipeBlock() - .getWorldPipeNet((ServerLevel) getPipeLevel()); - currentPipeNet = worldNet.getNetFromPos(getPipePos()); - if (currentPipeNet != null) { - this.currentPipeNet = new WeakReference<>(currentPipeNet); - } - return currentPipeNet; - } - - @Override - public boolean canAttachTo(Direction side) { - return false; - } - - @Override - public void setConnection(Direction side, boolean connected, boolean fromNeighbor) { - if (!getLevel().isClientSide && connected && !fromNeighbor) { - // never allow more than two connections total - if (getNumConnections() >= 2) return; - - // also check the other pipe - BlockEntity tile = getLevel().getBlockEntity(getPipePos().relative(side)); - if (tile instanceof IPipeNode pipeTile && - pipeTile.getPipeType().getClass() == this.getPipeType().getClass()) { - if (pipeTile.getNumConnections() >= 2) return; - } - } - super.setConnection(side, connected, fromNeighbor); - } - - /** - * @param active if the pipe should become active - * @param duration how long the pipe should be active for - */ - public void setActive(boolean active, int duration) { - boolean stateChanged = false; - if (this.isActive && !active) { - this.isActive = false; - stateChanged = true; - } else if (!this.isActive && active) { - this.isActive = true; - stateChanged = true; - TaskHandler.enqueueServerTask((ServerLevel) getLevel(), () -> setActive(false, -1), duration); - } - - if (stateChanged) { - notifyBlockUpdate(); - setChanged(); - } - } - - @Override - public void onChunkUnloaded() { - super.onChunkUnloaded(); - this.handlers.clear(); - } - - @Override - public GTToolType getPipeTuneTool() { - return GTToolType.WIRE_CUTTER; - } - - @Override - public ManagedFieldHolder getFieldHolder() { - return MANAGED_FIELD_HOLDER; - } - - private static class DefaultDataHandler implements IDataAccessHatch { - - @Override - public boolean isRecipeAvailable(@NotNull GTRecipe recipe, @NotNull Collection seen) { - return false; - } - - @Override - public boolean isCreative() { - return false; - } - } - - private static class DefaultComputationHandler implements IOpticalComputationProvider { - - @Override - public int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { - return 0; - } - - @Override - public int getMaxCWUt(@NotNull Collection seen) { - return 0; - } - - @Override - public boolean canBridge(@NotNull Collection seen) { - return false; - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index 00f2a86152..c9b3c77d5a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -25,20 +25,14 @@ public class GTBlockEntities { public static final BlockEntityEntry NEW_PIPE = REGISTRATE .blockEntity("pipe", PipeBlockEntity::new) .validBlocks(Stream.concat(Arrays.stream(GTBlocks.DUCT_PIPES), - Stream.concat(Arrays.stream(GTBlocks.OPTICAL_PIPES), - Stream.concat(Arrays.stream(GTBlocks.LASER_PIPES), + Stream.concat(Stream.of(GTBlocks.OPTICAL_PIPE), + Stream.concat(Stream.of(GTBlocks.LASER_PIPE), Stream.concat(GTBlocks.ITEM_PIPE_BLOCKS.values().stream(), Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), GTBlocks.FLUID_PIPE_BLOCKS.values().stream()))))) .toArray(NonNullSupplier[]::new)) .register(); - public static final BlockEntityEntry CABLE = REGISTRATE - .blockEntity("cable", CableBlockEntity::create) - .onRegister(CableBlockEntity::onBlockEntityRegister) - .validBlocks(GTBlocks.CABLE_BLOCKS.values().toArray(BlockEntry[]::new)) - .register(); - public static final BlockEntityEntry FLUID_PIPE = REGISTRATE .blockEntity("fluid_pipe", FluidPipeBlockEntity::new) .onRegister(FluidPipeBlockEntity::onBlockEntityRegister) @@ -54,12 +48,7 @@ public class GTBlockEntities { public static final BlockEntityEntry LASER_PIPE = REGISTRATE .blockEntity("laser_pipe", LaserPipeBlockEntity::create) .onRegister(LaserPipeBlockEntity::onBlockEntityRegister) - .validBlocks(GTBlocks.LASER_PIPES) - .register(); - - public static final BlockEntityEntry OPTICAL_PIPE = REGISTRATE - .blockEntity("optical_pipe", OpticalPipeBlockEntity::new) - .validBlocks(GTBlocks.OPTICAL_PIPES) + .validBlocks(GTBlocks.LASER_PIPE) .register(); public static final BlockEntityEntry DUCT_PIPE = REGISTRATE diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index c123384a66..a17cd3f372 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -21,16 +21,20 @@ import com.gregtechceu.gtceu.api.registry.registrate.CompassSection; import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; import com.gregtechceu.gtceu.common.block.*; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; +import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserPipeBlock; +import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserStructure; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalPipeBlock; import com.gregtechceu.gtceu.common.block.explosive.IndustrialTNTBlock; import com.gregtechceu.gtceu.common.block.explosive.PowderbarrelBlock; -import com.gregtechceu.gtceu.common.pipelike.cable.Insulation; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.duct.DuctPipeType; import com.gregtechceu.gtceu.common.pipelike.fluidpipe.FluidPipeType; import com.gregtechceu.gtceu.common.pipelike.fluidpipe.longdistance.LDFluidPipeType; import com.gregtechceu.gtceu.common.pipelike.item.ItemPipeType; import com.gregtechceu.gtceu.common.pipelike.item.longdistance.LDItemPipeType; import com.gregtechceu.gtceu.common.pipelike.laser.LaserPipeType; -import com.gregtechceu.gtceu.common.pipelike.optical.OpticalPipeType; import com.gregtechceu.gtceu.core.mixins.BlockPropertiesAccessor; import com.gregtechceu.gtceu.data.recipe.CustomTags; import com.gregtechceu.gtceu.utils.FormattingUtil; @@ -128,9 +132,33 @@ public class GTBlocks { public static Table> CABLE_BLOCKS; public static Table> FLUID_PIPE_BLOCKS; public static Table> ITEM_PIPE_BLOCKS; - public static final BlockEntry[] LASER_PIPES = new BlockEntry[LaserPipeType.values().length]; - public static final BlockEntry[] OPTICAL_PIPES = new BlockEntry[OpticalPipeType.values().length]; public static final BlockEntry[] DUCT_PIPES = new BlockEntry[DuctPipeType.VALUES.length]; + public static final BlockEntry LASER_PIPE = REGISTRATE + .block("normal_laser_pipe", (p) -> new LaserPipeBlock(p, LaserStructure.NORMAL)) + .initialProperties(() -> Blocks.IRON_BLOCK) + .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) + .blockstate(NonNullBiConsumer.noop()) + .defaultLoot() + .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) + .addLayer(() -> RenderType::cutoutMipped) + .item(com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem::new) + .model(NonNullBiConsumer.noop()) + .color(() -> LaserPipeBlockItem::tintColor) + .build() + .register(); + public static final BlockEntry OPTICAL_PIPE = REGISTRATE + .block("normal_optical_pipe", (p) -> new OpticalPipeBlock(p, OpticalStructure.INSTANCE)) + .lang("Optical Fiber Cable") + .initialProperties(() -> Blocks.IRON_BLOCK) + .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) + .blockstate(NonNullBiConsumer.noop()) + .defaultLoot() + .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) + .addLayer(() -> RenderType::cutoutMipped) + .item(com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem::new) + .model(NonNullBiConsumer.noop()) + .build() + .register(); ////////////////////////////////////// // ***** Procedural Blocks *****// @@ -266,44 +294,44 @@ private static void registerOreIndicator(Material material, GTRegistrate registr // Cable/Wire Blocks private static void generateCableBlocks() { GTCEu.LOGGER.debug("Generating GTCEu Cable/Wire Blocks..."); - for (Insulation insulation : Insulation.values()) { + CableStructure.registerDefaultStructures(structure -> { for (MaterialRegistry registry : GTCEuAPI.materialManager.getRegistries()) { GTRegistrate registrate = registry.getRegistrate(); for (Material material : registry.getAllMaterials()) { - if (allowCableBlock(material, insulation)) { - registerCableBlock(material, insulation, registrate); + if (allowCableBlock(material, structure)) { + registerCableBlock(material, structure, registrate); } } } - } + }); CABLE_BLOCKS = CABLE_BLOCKS_BUILDER.build(); GTCEu.LOGGER.debug("Generating GTCEu Cable/Wire Blocks... Complete!"); } - private static boolean allowCableBlock(Material material, Insulation insulation) { - return material.hasProperty(PropertyKey.WIRE) && !insulation.tagPrefix.isIgnored(material) && - !(insulation.isCable && material.getProperty(PropertyKey.WIRE).isSuperconductor()); + private static boolean allowCableBlock(Material material, CableStructure insulation) { + return material.hasProperty(PropertyKey.WIRE) && !insulation.prefix().isIgnored(material) && + !(insulation.isInsulated() && material.getProperty(PropertyKey.WIRE).isSuperconductor()); } - private static void registerCableBlock(Material material, Insulation insulation, GTRegistrate registrate) { + private static void registerCableBlock(Material material, CableStructure insulation, GTRegistrate registrate) { var entry = registrate - .block("%s_%s".formatted(material.getName(), insulation.name), - p -> new CableBlock(p, insulation, material)) + .block("%s_%s".formatted(material.getName(), insulation.name()), + p -> new com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock(p, insulation, material)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> p.dynamicShape().noOcclusion().noLootTable().forceSolidOn()) - .transform(unificationBlock(insulation.tagPrefix, material)) + .transform(unificationBlock(insulation.prefix(), material)) .blockstate(NonNullBiConsumer.noop()) .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) .color(() -> MaterialPipeBlock::tintedColor) - .item(MaterialPipeBlockItem::new) + .item(com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem::new) .model(NonNullBiConsumer.noop()) .color(() -> MaterialPipeBlockItem::tintColor) .onRegister(compassNodeExist(GTCompassSections.MATERIALS, "wire_and_cable")) .build() .register(); - CABLE_BLOCKS_BUILDER.put(insulation.tagPrefix, material, entry); + CABLE_BLOCKS_BUILDER.put(insulation.prefix(), material, entry); } // Fluid Pipe Blocks @@ -399,62 +427,6 @@ private static void registerItemPipeBlock(Material material, ItemPipeType itemPi ITEM_PIPE_BLOCKS_BUILDER.put(itemPipeType.getTagPrefix(), material, entry); } - // Laser Pipe Blocks - private static void generateLaserPipeBlocks() { - GTCEu.LOGGER.debug("Generating GTCEu Laser Pipe Blocks..."); - for (int i = 0; i < LaserPipeType.values().length; ++i) { - registerLaserPipeBlock(i); - } - GTCEu.LOGGER.debug("Generating GTCEu Laser Pipe Blocks... Complete!"); - } - - private static void registerLaserPipeBlock(int index) { - var type = LaserPipeType.values()[index]; - var entry = REGISTRATE - .block("%s_laser_pipe".formatted(type.getSerializedName()), (p) -> new LaserPipeBlock(p, type)) - .initialProperties(() -> Blocks.IRON_BLOCK) - .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) - .blockstate(NonNullBiConsumer.noop()) - .defaultLoot() - .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) - .addLayer(() -> RenderType::cutoutMipped) - .color(() -> LaserPipeBlock::tintedColor) - .item(LaserPipeBlockItem::new) - .model(NonNullBiConsumer.noop()) - .color(() -> LaserPipeBlockItem::tintColor) - .build() - .register(); - LASER_PIPES[index] = entry; - } - - // Optical Pipe Blocks - private static void generateOpticalPipeBlocks() { - GTCEu.LOGGER.debug("Generating GTCEu Optical Pipe Blocks..."); - for (int i = 0; i < OpticalPipeType.values().length; ++i) { - registerOpticalPipeBlock(i); - } - GTCEu.LOGGER.debug("Generating GTCEu Optical Pipe Blocks... Complete!"); - } - - private static void registerOpticalPipeBlock(int index) { - var type = OpticalPipeType.values()[index]; - var entry = REGISTRATE - .block("%s_optical_pipe".formatted(type.getSerializedName()), (p) -> new OpticalPipeBlock(p, type)) - .lang("Optical Fiber Cable") - .initialProperties(() -> Blocks.IRON_BLOCK) - .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) - .blockstate(NonNullBiConsumer.noop()) - .defaultLoot() - .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) - .addLayer(() -> RenderType::cutoutMipped) - .color(() -> OpticalPipeBlock::tintedColor) - .item(OpticalPipeBlockItem::new) - .model(NonNullBiConsumer.noop()) - .build() - .register(); - OPTICAL_PIPES[index] = entry; - } - // Optical Pipe Blocks private static void generateDuctPipeBlocks() { GTCEu.LOGGER.debug("Generating GTCEu Duct Pipe Blocks..."); @@ -1708,8 +1680,6 @@ public static void init() { generateCableBlocks(); // Cable & Wire Blocks generateFluidPipeBlocks(); // Fluid Pipe Blocks generateItemPipeBlocks(); // Item Pipe Blocks - generateLaserPipeBlocks(); // Laser Pipe Blocks - generateOpticalPipeBlocks(); // Optical Pipe Blocks generateDuctPipeBlocks(); // Duct Pipe Blocks // Remove Builder Tables diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTCreativeModeTabs.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTCreativeModeTabs.java index 11935bc1e3..351f07d9ca 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTCreativeModeTabs.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTCreativeModeTabs.java @@ -10,7 +10,6 @@ import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; -import com.gregtechceu.gtceu.common.pipelike.cable.Insulation; import net.minecraft.core.NonNullList; import net.minecraft.core.registries.Registries; @@ -50,7 +49,7 @@ public class GTCreativeModeTabs { .register(); public static RegistryEntry MATERIAL_PIPE = REGISTRATE.defaultCreativeTab("material_pipe", builder -> builder.displayItems(new RegistrateDisplayItemsGenerator("material_pipe", REGISTRATE)) - .icon(() -> ChemicalHelper.get(Insulation.WIRE_DOUBLE.getTagPrefix(), GTMaterials.Copper)) + .icon(() -> ChemicalHelper.get(TagPrefix.wireGtDouble, GTMaterials.Copper)) .title(REGISTRATE.addLang("itemGroup", GTCEu.id("material_pipe"), GTCEu.NAME + " Material Pipes")) .build()) .register(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/AveragingPerTickCounter.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/AveragingPerTickCounter.java deleted file mode 100644 index 41fac33087..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/AveragingPerTickCounter.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import net.minecraft.world.level.Level; - -import java.util.Arrays; - -public class AveragingPerTickCounter { - - private final long defaultValue; - private final long[] values; - private long lastUpdatedWorldTime = 0; - private int currentIndex = 0; - private boolean dirty = true; - private double lastAverage = 0; - - public AveragingPerTickCounter() { - this(0, 20); - } - - /** - * Averages a value over a certain amount of ticks - * - * @param defaultValue self-explanatory - * @param length amount of ticks to average (20 for 1 second) - */ - public AveragingPerTickCounter(long defaultValue, int length) { - this.defaultValue = defaultValue; - this.values = new long[length]; - Arrays.fill(values, defaultValue); - } - - private void checkValueState(Level world) { - if (world == null) return; - long currentWorldTime = world.getGameTime(); - if (currentWorldTime != lastUpdatedWorldTime) { - long dif = currentWorldTime - lastUpdatedWorldTime; - if (dif >= values.length || dif < 0) { - Arrays.fill(values, defaultValue); - currentIndex = 0; - } else { - for (int i = currentIndex + 1; i <= currentIndex + dif; i++) { - values[i % values.length] = defaultValue; - } - currentIndex += dif; - if (currentIndex >= values.length) - currentIndex = currentIndex % values.length; - } - this.lastUpdatedWorldTime = currentWorldTime; - dirty = true; - } - } - - /** - * @return the value from the current tick - */ - public long getLast(Level world) { - checkValueState(world); - return values[currentIndex]; - } - - /** - * @return the average of all values - */ - public double getAverage(Level world) { - checkValueState(world); - if (!dirty) - return lastAverage; - dirty = false; - return lastAverage = Arrays.stream(values).sum() / (double) (values.length); - } - - /** - * @param value the value to increment the current value by - */ - public void increment(Level world, long value) { - checkValueState(world); - values[currentIndex] += value; - } - - /** - * @param value the value to set current value to - */ - public void set(Level world, long value) { - checkValueState(world); - values[currentIndex] = value; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/CableData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/CableData.java deleted file mode 100644 index e45ef0c9b7..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/CableData.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; -import com.gregtechceu.gtceu.api.pipenet.IAttachData; - -import net.minecraft.core.Direction; - -import lombok.Getter; -import lombok.experimental.Accessors; - -import java.util.Objects; - -/** - * @author KilaBash - * @date 2023/3/1 - * @implNote CableData - */ -@Accessors(fluent = true) -public class CableData implements IAttachData { - - @Getter - WireProperties properties; - @Getter - byte connections; - - public CableData(WireProperties properties, byte connections) { - this.properties = properties; - this.connections = connections; - } - - @Override - public boolean canAttachTo(Direction side) { - return (connections & (1 << side.ordinal())) != 0; - } - - @Override - public boolean setAttached(Direction side, boolean attach) { - var result = canAttachTo(side); - if (result != attach) { - if (attach) { - connections |= (1 << side.ordinal()); - } else { - connections &= ~(1 << side.ordinal()); - } - } - return result != attach; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof CableData cableData) { - return cableData.properties.equals(properties) && connections == cableData.connections; - } - return super.equals(obj); - } - - @Override - public int hashCode() { - return Objects.hash(properties, connections); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNet.java deleted file mode 100644 index 98852c3e1c..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNet.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; -import com.gregtechceu.gtceu.api.pipenet.Node; -import com.gregtechceu.gtceu.api.pipenet.PipeNet; - -import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.level.Level; - -import java.util.*; - -public class EnergyNet extends PipeNet { - - private final Map> NET_DATA = new HashMap<>(); - - private long lastEnergyFluxPerSec; - private long energyFluxPerSec; - private long lastTime; - - protected EnergyNet(LevelPipeNet world) { - super(world); - } - - public List getNetData(BlockPos pipePos) { - List data = NET_DATA.get(pipePos); - if (data == null) { - data = EnergyNetWalker.createNetData(this, pipePos); - if (data == null) { - // walker failed, don't cache so it tries again on next insertion - return Collections.emptyList(); - } - data.sort(Comparator.comparingInt(EnergyRoutePath::getDistance)); - NET_DATA.put(pipePos, data); - } - return data; - } - - @Override - public void onNeighbourUpdate(BlockPos fromPos) { - NET_DATA.clear(); - } - - @Override - public void onPipeConnectionsUpdate() { - NET_DATA.clear(); - } - - @Override - protected void transferNodeData(Map> transferredNodes, - PipeNet parentNet) { - super.transferNodeData(transferredNodes, parentNet); - NET_DATA.clear(); - ((EnergyNet) parentNet).NET_DATA.clear(); - } - - @Override - protected void writeNodeData(WireProperties nodeData, CompoundTag tagCompound) { - tagCompound.putInt("voltage", nodeData.getVoltage()); - tagCompound.putInt("amperage", nodeData.getAmperage()); - tagCompound.putInt("loss", nodeData.getLossPerBlock()); - } - - @Override - protected WireProperties readNodeData(CompoundTag tagCompound) { - int voltage = tagCompound.getInt("voltage"); - int amperage = tagCompound.getInt("amperage"); - int lossPerBlock = tagCompound.getInt("loss"); - return new WireProperties(voltage, amperage, lossPerBlock); - } - - ////////////////////////////////////// - // ******* Pipe Status *******// - ////////////////////////////////////// - - public long getEnergyFluxPerSec() { - Level world = getLevel(); - if (world != null && !world.isClientSide && (world.getGameTime() - lastTime) >= 20) { - lastTime = world.getGameTime(); - clearCache(); - } - return lastEnergyFluxPerSec; - } - - public void addEnergyFluxPerSec(long energy) { - energyFluxPerSec += energy; - } - - public void clearCache() { - lastEnergyFluxPerSec = energyFluxPerSec; - energyFluxPerSec = 0; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java deleted file mode 100644 index 649f4845b3..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetHandler.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.IEnergyContainer; -import com.gregtechceu.gtceu.common.blockentity.CableBlockEntity; -import com.gregtechceu.gtceu.utils.GTUtil; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.block.Blocks; - -import java.util.Objects; - -public class EnergyNetHandler implements IEnergyContainer { - - private EnergyNet net; - private boolean transfer; - private final CableBlockEntity cable; - private final Direction facing; - - public EnergyNetHandler(EnergyNet net, CableBlockEntity cable, Direction facing) { - this.net = Objects.requireNonNull(net); - this.cable = Objects.requireNonNull(cable); - this.facing = facing; - } - - public EnergyNet getNet() { - return net; - } - - public void updateNetwork(EnergyNet net) { - this.net = net; - } - - @Override - public long getEnergyCanBeInserted() { - return getEnergyCapacity(); - } - - @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { - if (transfer) return 0; - if (side == null) { - if (facing == null) return 0; - side = facing; - } - - long amperesUsed = 0L; - for (EnergyRoutePath path : net.getNetData(cable.getPipePos())) { - if (path.getMaxLoss() >= voltage) { - // Will lose all the energy with this path, so don't use it - continue; - } - - if (cable.getPipePos().equals(path.getTargetPipePos()) && side == path.getTargetFacing()) { - // Do not insert into source handler - continue; - } - - IEnergyContainer dest = path.getHandler(getNet().getLevel()); - if (dest == null) continue; - - Direction facing = path.getTargetFacing().getOpposite(); - if (!dest.inputsEnergy(facing) || dest.getEnergyCanBeInserted() <= 0) continue; - - long pathVoltage = voltage - path.getMaxLoss(); - boolean cableBroken = false; - for (CableBlockEntity cable : path.getPath()) { - if (cable.getMaxVoltage() < voltage) { - int heat = (int) (Math.log( - GTUtil.getTierByVoltage(voltage) - GTUtil.getTierByVoltage(cable.getMaxVoltage())) * - 45 + 36.5); - cable.applyHeat(heat); - - cableBroken = cable.isInValid(); - if (cableBroken) { - // a cable burned away (or insulation melted) - break; - } - - // limit transfer to cables max and void rest - pathVoltage = Math.min(cable.getMaxVoltage(), pathVoltage); - } - } - - if (cableBroken) continue; - - transfer = true; - long amps = dest.acceptEnergyFromNetwork(facing, pathVoltage, amperage - amperesUsed, false); - transfer = false; - if (amps == 0) continue; - - amperesUsed += amps; - long voltageTraveled = voltage; - for (CableBlockEntity cable : path.getPath()) { - voltageTraveled -= cable.getNodeData().getLossPerBlock(); - if (voltageTraveled <= 0) break; - - if (!cable.isInValid()) { - cable.incrementAmperage(amps, voltageTraveled); - } - } - - if (amperage == amperesUsed) break; - } - - net.addEnergyFluxPerSec(amperesUsed * voltage); - return amperesUsed; - } - - private void burnCable(ServerLevel serverLevel, BlockPos pos) { - serverLevel.setBlockAndUpdate(pos, Blocks.FIRE.defaultBlockState()); - if (!getNet().getLevel().isClientSide) { - getNet().getLevel().sendParticles(ParticleTypes.LARGE_SMOKE, - pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, - 5 + getNet().getLevel().random.nextInt(3), 0.0, 0.0, 0.0, 0.1); - } - } - - @Override - public long getInputAmperage() { - return cable.getNodeData().getAmperage(); - } - - @Override - public long getInputVoltage() { - return cable.getNodeData().getVoltage(); - } - - @Override - public long getEnergyCapacity() { - return getInputVoltage() * getInputAmperage(); - } - - @Override - public long changeEnergy(long energyToAdd) { - GTCEu.LOGGER.warn("Do not use changeEnergy() for cables! Use acceptEnergyFromNetwork()"); - return acceptEnergyFromNetwork(null, - energyToAdd / getInputAmperage(), - energyToAdd / getInputVoltage(), false) * getInputVoltage(); - } - - @Override - public boolean outputsEnergy(Direction side) { - return true; - } - - @Override - public boolean inputsEnergy(Direction side) { - return true; - } - - @Override - public long getEnergyStored() { - return 0; - } - - @Override - public boolean isOneProbeHidden() { - return true; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetWalker.java deleted file mode 100644 index a81994d1f2..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyNetWalker.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import com.gregtechceu.gtceu.api.capability.IEnergyContainer; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; -import com.gregtechceu.gtceu.api.pipenet.PipeNetWalker; -import com.gregtechceu.gtceu.common.blockentity.CableBlockEntity; - -import com.lowdragmc.lowdraglib.LDLib; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.entity.BlockEntity; - -import org.apache.commons.lang3.ArrayUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; - -public class EnergyNetWalker extends PipeNetWalker { - - @Nullable - public static List createNetData(EnergyNet pipeNet, BlockPos sourcePipe) { - try { - EnergyNetWalker walker = new EnergyNetWalker(pipeNet, sourcePipe, 1, new ArrayList<>()); - walker.traversePipeNet(); - return walker.routes; - } catch (Exception e) { - LDLib.LOGGER.error("error while create net data for energynet", e); - } - return null; - } - - private final List routes; - private CableBlockEntity[] pipes = {}; - private int loss; - - public EnergyNetWalker(EnergyNet pipeNet, BlockPos sourcePipe, int walkedBlocks, List routes) { - super(pipeNet, sourcePipe, walkedBlocks); - this.routes = routes; - } - - @NotNull - @Override - protected PipeNetWalker createSubWalker(EnergyNet pipeNet, - Direction facingToNextPos, - BlockPos nextPos, - int walkedBlocks) { - EnergyNetWalker walker = new EnergyNetWalker(pipeNet, nextPos, walkedBlocks, routes); - walker.loss = loss; - walker.pipes = pipes; - return walker; - } - - @Override - protected void checkPipe(CableBlockEntity pipeTile, BlockPos pos) { - pipes = ArrayUtils.add(pipes, pipeTile); - loss += pipeTile.getNodeData().getLossPerBlock(); - } - - @Override - protected void checkNeighbour(CableBlockEntity pipeTile, BlockPos pipePos, Direction faceToNeighbour, - @Nullable BlockEntity neighbourTile) { - // assert that the last added pipe is the current pipe - if (pipeTile != pipes[pipes.length - 1]) - throw new IllegalStateException( - "The current pipe is not the last added pipe. Something went seriously wrong!"); - if (neighbourTile != null) { - IEnergyContainer container = neighbourTile - .getCapability(GTCapability.CAPABILITY_ENERGY_CONTAINER, faceToNeighbour.getOpposite()).resolve() - .orElse(null); - if (container != null) { - routes.add(new EnergyRoutePath(pipePos.immutable(), faceToNeighbour, pipes, getWalkedBlocks(), loss)); - } - } - } - - @Override - protected Class getBasePipeClass() { - return CableBlockEntity.class; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyRoutePath.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyRoutePath.java deleted file mode 100644 index c74b197643..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/EnergyRoutePath.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.IEnergyContainer; -import com.gregtechceu.gtceu.api.pipenet.IRoutePath; -import com.gregtechceu.gtceu.common.blockentity.CableBlockEntity; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; - -import lombok.Getter; -import org.jetbrains.annotations.Nullable; - -public class EnergyRoutePath implements IRoutePath { - - private final CableBlockEntity targetPipe; - @Getter - private final BlockPos targetPipePos; - @Getter - private final Direction targetFacing; - @Getter - private final int distance; - @Getter - private final CableBlockEntity[] path; - @Getter - private final long maxLoss; - - public EnergyRoutePath(BlockPos targetPipePos, Direction targetFacing, CableBlockEntity[] path, int distance, - long maxLoss) { - this.targetPipe = path[path.length - 1]; - this.targetPipePos = targetPipePos; - this.targetFacing = targetFacing; - this.path = path; - this.distance = distance; - this.maxLoss = maxLoss; - } - - @Nullable - public IEnergyContainer getHandler(Level world) { - return GTCapabilityHelper.getEnergyContainer(world, getTargetPipePos().relative(targetFacing), - targetFacing.getOpposite()); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/Insulation.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/Insulation.java deleted file mode 100644 index 56ecba27f8..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/Insulation.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.pipenet.IMaterialPipeType; -import com.gregtechceu.gtceu.client.model.PipeModel; - -import net.minecraft.resources.ResourceLocation; - -import lombok.Getter; -import org.jetbrains.annotations.Nullable; - -import java.util.function.Supplier; - -import static com.gregtechceu.gtceu.api.data.tag.TagPrefix.*; - -public enum Insulation implements IMaterialPipeType { - - WIRE_SINGLE("single_wire", 0.125f, 1, 2, wireGtSingle, -1, false), - WIRE_DOUBLE("double_wire", 0.25f, 2, 2, wireGtDouble, -1, false), - WIRE_QUADRUPLE("quadruple_wire", 0.375f, 4, 3, wireGtQuadruple, -1, false), - WIRE_OCTAL("octal_wire", 0.5f, 8, 3, wireGtOctal, -1, false), - WIRE_HEX("hex_wire", 0.75f, 16, 3, wireGtHex, -1, false), - - CABLE_SINGLE("single_cable", 0.25f, 1, 1, cableGtSingle, 0, true), - CABLE_DOUBLE("double_cable", 0.375f, 2, 1, cableGtDouble, 1, true), - CABLE_QUADRUPLE("quadruple_cable", 0.5f, 4, 1, cableGtQuadruple, 2, true), - CABLE_OCTAL("octal_cable", 0.75f, 8, 1, cableGtOctal, 3, true), - CABLE_HEX("hex_cable", 1.0f, 16, 1, cableGtHex, 4, true); - - public static final ResourceLocation TYPE_ID = GTCEu.id("insulation"); - - public final String name; - public final float thickness; - public final int amperage; - public final int lossMultiplier; - @Getter - public final TagPrefix tagPrefix; - public final int insulationLevel; - public final boolean isCable; - - Insulation(String name, float thickness, int amperage, int lossMultiplier, TagPrefix TagPrefix, int insulated, - boolean isCable) { - this.name = name; - this.thickness = thickness; - this.amperage = amperage; - this.tagPrefix = TagPrefix; - this.insulationLevel = insulated; - this.lossMultiplier = lossMultiplier; - this.isCable = isCable; - } - - @Override - public float getThickness() { - return thickness; - } - - @Override - public WireProperties modifyProperties(WireProperties baseProperties) { - int lossPerBlock; - if (!baseProperties.isSuperconductor() && baseProperties.getLossPerBlock() == 0) - lossPerBlock = (int) (0.75 * lossMultiplier); - else lossPerBlock = baseProperties.getLossPerBlock() * lossMultiplier; - - return new WireProperties(baseProperties.getVoltage(), baseProperties.getAmperage() * amperage, lossPerBlock, - baseProperties.isSuperconductor()); - } - - public boolean isCable() { - return ordinal() > 4; - } - - @Override - public boolean isPaintable() { - return true; - } - - @Override - public ResourceLocation type() { - return TYPE_ID; - } - - public PipeModel createPipeModel(Material material) { - Supplier wireSideTexturePath = () -> MaterialIconType.wire - .getBlockTexturePath(material.getMaterialIconSet(), true).withSuffix("_side"); - Supplier wireEndTexturePath = () -> MaterialIconType.wire - .getBlockTexturePath(material.getMaterialIconSet(), true).withSuffix("_end"); - Supplier<@Nullable ResourceLocation> wireSideOverlayTexturePath = () -> MaterialIconType.wire - .getBlockTexturePath(material.getMaterialIconSet(), "side_overlay", true); - Supplier<@Nullable ResourceLocation> wireEndOverlayTexturePath = () -> MaterialIconType.wire - .getBlockTexturePath(material.getMaterialIconSet(), "end_overlay", true); - PipeModel model = new PipeModel(thickness, - isCable ? () -> GTCEu.id("block/cable/insulation_5") : wireSideTexturePath, wireEndTexturePath, - wireSideOverlayTexturePath, wireEndOverlayTexturePath); - if (isCable) { - model.setEndOverlayTexture(GTCEu.id("block/cable/insulation_%s".formatted(insulationLevel))); - } - return model; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/LevelEnergyNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/LevelEnergyNet.java deleted file mode 100644 index 799e65281b..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/LevelEnergyNet.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; - -public class LevelEnergyNet extends LevelPipeNet { - - public static LevelEnergyNet getOrCreate(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> new LevelEnergyNet(serverLevel, tag), - () -> new LevelEnergyNet(serverLevel), "gtcue_energy_net"); - } - - public LevelEnergyNet(ServerLevel serverLevel) { - super(serverLevel); - } - - public LevelEnergyNet(ServerLevel serverLevel, CompoundTag tag) { - super(serverLevel, tag); - } - - @Override - protected EnergyNet createNetInstance() { - return new EnergyNet(this); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/PerTickLongCounter.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/PerTickLongCounter.java deleted file mode 100644 index 72f0d8bdb5..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/cable/PerTickLongCounter.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.cable; - -import net.minecraft.world.level.Level; - -public class PerTickLongCounter { - - private final long defaultValue; - private long lastUpdatedWorldTime; - private long lastValue; - private long currentValue; - - public PerTickLongCounter() { - this(0); - } - - public PerTickLongCounter(long defaultValue) { - this.defaultValue = defaultValue; - this.currentValue = defaultValue; - this.lastValue = defaultValue; - } - - private void checkValueState(Level world) { - if (world == null) return; - long currentWorldTime = world.getGameTime(); - if (currentWorldTime != lastUpdatedWorldTime) { - if (currentWorldTime == lastUpdatedWorldTime + 1) { - // last updated time is 1 tick ago, so we can move current value to last - // before resetting it to default value - this.lastValue = currentValue; - } else { - // otherwise, set last value as default value - this.lastValue = defaultValue; - } - this.lastUpdatedWorldTime = currentWorldTime; - this.currentValue = defaultValue; - } - } - - public long get(Level world) { - checkValueState(world); - return currentValue; - } - - public long getLast(Level world) { - checkValueState(world); - return lastValue; - } - - public void increment(Level world, long value) { - checkValueState(world); - this.currentValue += value; - } - - public void set(Level world, long value) { - checkValueState(world); - this.currentValue = value; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java index 65c0358977..de5e6d58f9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ILaserContainer; +import com.gregtechceu.gtceu.api.capability.ILaserRelay; import com.gregtechceu.gtceu.api.pipenet.IAttachData; import com.gregtechceu.gtceu.api.pipenet.PipeNet; @@ -118,7 +119,7 @@ public BlockPos getHandlerPos() { * @return the handler */ @Nullable - public ILaserContainer getHandler(@NotNull Level world) { + public ILaserRelay getHandler(@NotNull Level world) { return GTCapabilityHelper.getLaser(world, getHandlerPos(), faceToHandler.getOpposite()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java index 8b2f095df3..523e24d4a5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ILaserContainer; +import com.gregtechceu.gtceu.api.capability.ILaserRelay; import com.gregtechceu.gtceu.api.pipenet.IAttachData; import com.gregtechceu.gtceu.api.pipenet.IRoutePath; @@ -13,7 +14,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class LaserRoutePath implements IRoutePath, IAttachData { +public class LaserRoutePath implements IRoutePath, IAttachData { @Getter private final BlockPos targetPipePos; @@ -43,7 +44,7 @@ public LaserRoutePath(BlockPos targetPipePos, Direction targetFacing, int distan * @return the handler */ @Nullable - public ILaserContainer getHandler(Level level) { + public ILaserRelay getHandler(Level level) { return GTCapabilityHelper.getLaser(level, getTargetPipePos().relative(targetFacing), targetFacing.getOpposite()); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/LevelOpticalPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/LevelOpticalPipeNet.java deleted file mode 100644 index b3f35e4a7f..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/LevelOpticalPipeNet.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.optical; - -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; - -public class LevelOpticalPipeNet extends LevelPipeNet { - - private static final String DATA_ID = "gtceu_optical_pipe_net"; - - public static LevelOpticalPipeNet getOrCreate(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> new LevelOpticalPipeNet(serverLevel, tag), - () -> new LevelOpticalPipeNet(serverLevel), DATA_ID); - } - - public LevelOpticalPipeNet(ServerLevel level) { - super(level); - } - - public LevelOpticalPipeNet(ServerLevel serverLevel, CompoundTag tag) { - super(serverLevel, tag); - } - - @Override - protected OpticalPipeNet createNetInstance() { - return new OpticalPipeNet(this); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetHandler.java deleted file mode 100644 index 9ea4e426f2..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetHandler.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.optical; - -import com.gregtechceu.gtceu.api.capability.IDataAccessHatch; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; -import com.gregtechceu.gtceu.api.capability.IOpticalDataAccessHatch; -import com.gregtechceu.gtceu.api.recipe.GTRecipe; -import com.gregtechceu.gtceu.common.blockentity.OpticalPipeBlockEntity; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; - -public class OpticalNetHandler implements IDataAccessHatch, IOpticalComputationProvider { - - private final OpticalPipeBlockEntity pipe; - private final Level world; - private final Direction facing; - - private OpticalPipeNet net; - - public OpticalNetHandler(OpticalPipeNet net, @NotNull OpticalPipeBlockEntity pipe, @Nullable Direction facing) { - this.net = net; - this.pipe = pipe; - this.facing = facing; - this.world = pipe.getLevel(); - } - - public void updateNetwork(OpticalPipeNet net) { - this.net = net; - } - - public OpticalPipeNet getNet() { - return net; - } - - @Override - public boolean isRecipeAvailable(@NotNull GTRecipe recipe, @NotNull Collection seen) { - boolean isAvailable = traverseRecipeAvailable(recipe, seen); - if (isAvailable) setPipesActive(); - return isAvailable; - } - - @Override - public boolean isCreative() { - return false; - } - - @Override - public int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { - int provided = traverseRequestCWUt(cwut, simulate, seen); - if (provided > 0) setPipesActive(); - return provided; - } - - @Override - public int getMaxCWUt(@NotNull Collection seen) { - return traverseMaxCWUt(seen); - } - - @Override - public boolean canBridge(@NotNull Collection seen) { - return traverseCanBridge(seen); - } - - private void setPipesActive() { - for (BlockPos pos : net.getAllNodes().keySet()) { - if (world.getBlockEntity(pos) instanceof OpticalPipeBlockEntity opticalPipe) { - opticalPipe.setActive(true, 100); - } - } - } - - private boolean isNetInvalidForTraversal() { - return net == null || pipe == null || pipe.isInValid(); - } - - private boolean traverseRecipeAvailable(@NotNull GTRecipe recipe, @NotNull Collection seen) { - if (isNetInvalidForTraversal()) return false; - - OpticalRoutePath inv = net.getNetData(pipe.getPipePos(), facing); - if (inv == null) return false; - - IOpticalDataAccessHatch hatch = inv.getDataHatch(); - if (hatch == null || seen.contains(hatch)) return false; - - if (hatch.isTransmitter()) { - return hatch.isRecipeAvailable(recipe, seen); - } - return false; - } - - private int traverseRequestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { - IOpticalComputationProvider provider = getComputationProvider(seen); - if (provider == null) return 0; - return provider.requestCWUt(cwut, simulate, seen); - } - - private int traverseMaxCWUt(@NotNull Collection seen) { - IOpticalComputationProvider provider = getComputationProvider(seen); - if (provider == null) return 0; - return provider.getMaxCWUt(seen); - } - - private boolean traverseCanBridge(@NotNull Collection seen) { - IOpticalComputationProvider provider = getComputationProvider(seen); - if (provider == null) return true; // nothing found, so don't report a problem, just pass quietly - return provider.canBridge(seen); - } - - @Nullable - private IOpticalComputationProvider getComputationProvider(@NotNull Collection seen) { - if (isNetInvalidForTraversal()) return null; - - OpticalRoutePath inv = net.getNetData(pipe.getPipePos(), facing); - if (inv == null) return null; - - IOpticalComputationProvider hatch = inv.getComputationHatch(); - if (hatch == null || seen.contains(hatch)) return null; - return hatch; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetWalker.java deleted file mode 100644 index 16711b1e8a..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalNetWalker.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.optical; - -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.pipenet.PipeNetWalker; -import com.gregtechceu.gtceu.common.blockentity.OpticalPipeBlockEntity; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.entity.BlockEntity; - -import org.jetbrains.annotations.Nullable; - -public class OpticalNetWalker extends PipeNetWalker { - - public static final OpticalRoutePath FAILED_MARKER = new OpticalRoutePath(null, null, 0); - - @Nullable - public static OpticalRoutePath createNetData(OpticalPipeNet world, BlockPos sourcePipe, - Direction faceToSourceHandler) { - OpticalNetWalker walker = new OpticalNetWalker(world, sourcePipe, 1); - walker.sourcePipe = sourcePipe; - walker.facingToHandler = faceToSourceHandler; - walker.traversePipeNet(); - return walker.isFailed() ? FAILED_MARKER : walker.routePath; - } - - private OpticalRoutePath routePath; - private BlockPos sourcePipe; - private Direction facingToHandler; - - protected OpticalNetWalker(OpticalPipeNet world, BlockPos sourcePipe, int distance) { - super(world, sourcePipe, distance); - } - - @Override - protected PipeNetWalker createSubWalker(OpticalPipeNet world, - Direction facingToNextPos, - BlockPos nextPos, - int walkedBlocks) { - OpticalNetWalker walker = new OpticalNetWalker(world, nextPos, walkedBlocks); - walker.facingToHandler = facingToHandler; - walker.sourcePipe = sourcePipe; - return walker; - } - - @Override - protected void checkPipe(OpticalPipeBlockEntity pipeTile, BlockPos pos) {} - - @Override - protected void checkNeighbour(OpticalPipeBlockEntity pipeTile, BlockPos pipePos, Direction faceToNeighbour, - @Nullable BlockEntity neighbourTile) { - if (neighbourTile == null || - (pipePos.equals(sourcePipe) && faceToNeighbour == facingToHandler)) { - return; - } - - if (((OpticalNetWalker) root).routePath == null) { - if (neighbourTile.getCapability(GTCapability.CAPABILITY_DATA_ACCESS, - faceToNeighbour.getOpposite()).isPresent() || - neighbourTile.getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, - faceToNeighbour.getOpposite()).isPresent()) { - ((OpticalNetWalker) root).routePath = new OpticalRoutePath(pipeTile, faceToNeighbour, - getWalkedBlocks()); - stop(); - } - } - } - - @Override - protected Class getBasePipeClass() { - return OpticalPipeBlockEntity.class; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeNet.java deleted file mode 100644 index f4b52a2a06..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeNet.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.optical; - -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; -import com.gregtechceu.gtceu.api.pipenet.Node; -import com.gregtechceu.gtceu.api.pipenet.PipeNet; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; - -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import org.jetbrains.annotations.Nullable; - -import java.util.Map; - -public class OpticalPipeNet extends PipeNet { - - private final Map NET_DATA = new Object2ObjectOpenHashMap<>(); - - public OpticalPipeNet(LevelPipeNet> world) { - super(world); - } - - @Nullable - public OpticalRoutePath getNetData(BlockPos pipePos, Direction facing) { - if (NET_DATA.containsKey(pipePos)) { - return NET_DATA.get(pipePos); - } - OpticalRoutePath data = OpticalNetWalker.createNetData(this, pipePos, facing); - if (data == OpticalNetWalker.FAILED_MARKER) { - // walker failed, don't cache, so it tries again on next insertion - return null; - } - - NET_DATA.put(pipePos, data); - return data; - } - - @Override - public void onNeighbourUpdate(BlockPos fromPos) { - NET_DATA.clear(); - } - - @Override - public void onPipeConnectionsUpdate() { - NET_DATA.clear(); - } - - @Override - protected void transferNodeData(Map> transferredNodes, - PipeNet parentNet) { - super.transferNodeData(transferredNodes, parentNet); - NET_DATA.clear(); - ((OpticalPipeNet) parentNet).NET_DATA.clear(); - } - - @Override - protected void writeNodeData(OpticalPipeProperties nodeData, CompoundTag tagCompound) {} - - @Override - protected OpticalPipeProperties readNodeData(CompoundTag tagCompound) { - return OpticalPipeProperties.INSTANCE; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeProperties.java deleted file mode 100644 index 8bdd971470..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeProperties.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.optical; - -public class OpticalPipeProperties { - - public static final OpticalPipeProperties INSTANCE = new OpticalPipeProperties(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeType.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeType.java deleted file mode 100644 index bb64d6a98e..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalPipeType.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.optical; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.pipenet.IPipeType; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.StringRepresentable; - -import java.util.Locale; - -public enum OpticalPipeType implements IPipeType, StringRepresentable { - - NORMAL; - - public static final ResourceLocation TYPE = GTCEu.id("optical"); - - @Override - public float getThickness() { - return 0.375F; - } - - @Override - public OpticalPipeProperties modifyProperties(OpticalPipeProperties baseProperties) { - return baseProperties; - } - - @Override - public boolean isPaintable() { - return true; - } - - @Override - public ResourceLocation type() { - return TYPE; - } - - @Override - public String getSerializedName() { - return name().toLowerCase(Locale.ROOT); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalRoutePath.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalRoutePath.java deleted file mode 100644 index 07ccff2fe6..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/optical/OpticalRoutePath.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.optical; - -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.IDataAccessHatch; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; -import com.gregtechceu.gtceu.api.capability.IOpticalDataAccessHatch; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.pipenet.IRoutePath; -import com.gregtechceu.gtceu.common.blockentity.OpticalPipeBlockEntity; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class OpticalRoutePath implements IRoutePath { - - @Getter - private final OpticalPipeBlockEntity targetPipe; - @Getter - private final Direction targetFacing; - @Getter - private final int distance; - - public OpticalRoutePath(OpticalPipeBlockEntity targetPipe, Direction targetFacing, int distance) { - this.targetPipe = targetPipe; - this.targetFacing = targetFacing; - this.distance = distance; - } - - @Nullable - public IOpticalDataAccessHatch getDataHatch() { - IDataAccessHatch dataAccessHatch = getTargetCapability(GTCapability.CAPABILITY_DATA_ACCESS, - targetPipe.getPipeLevel()); - return dataAccessHatch instanceof IOpticalDataAccessHatch opticalHatch ? opticalHatch : null; - } - - @Nullable - public IOpticalComputationProvider getComputationHatch() { - return getTargetCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, targetPipe.getPipeLevel()); - } - - @Override - public @NotNull BlockPos getTargetPipePos() { - return targetPipe.getPipePos(); - } - - @Nullable - @Override - public IOpticalComputationProvider getHandler(Level world) { - return GTCapabilityHelper.getOpticalComputationProvider(world, getTargetPipePos().relative(targetFacing), - targetFacing.getOpposite()); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java index bbef2f22a2..f23fbf431d 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java @@ -87,7 +87,7 @@ public static void init(Consumer provider) { .inputItems(foil, Silver, 8) .inputFluids(Polytetrafluoroethylene.getFluid(L)) .cleanroom(CleanroomType.CLEANROOM) - .outputItems(OPTICAL_PIPES[0]) + .outputItems(OPTICAL_PIPE[0]) .duration(100).EUt(VA[IV]).save(provider); ASSEMBLY_LINE_RECIPES.recipeBuilder("data_bank") @@ -96,7 +96,7 @@ public static void init(Consumer provider) { .inputItems(TOOL_DATA_ORB) .inputItems(wireFine, Cobalt, 64) .inputItems(wireFine, Copper, 64) - .inputItems(OPTICAL_PIPES[0].asStack(4)) + .inputItems(OPTICAL_PIPE[0].asStack(4)) .inputItems(wireGtDouble, IndiumTinBariumTitaniumCuprate, 16) .inputFluids(SolderingAlloy.getFluid(L * 2)) .inputFluids(Lubricant.getFluid(500)) @@ -115,7 +115,7 @@ public static void init(Consumer provider) { .inputItems(ELECTRIC_MOTOR_ZPM, 2) .inputItems(wireGtDouble, UraniumRhodiumDinaquadide, 32) .inputItems(foil, Trinium, 32) - .inputItems(OPTICAL_PIPES[0].asStack(16)) + .inputItems(OPTICAL_PIPE[0].asStack(16)) .inputFluids(SolderingAlloy.getFluid(L * 8)) .inputFluids(VanadiumGallium.getFluid(L * 8)) .outputItems(RESEARCH_STATION) @@ -132,7 +132,7 @@ public static void init(Consumer provider) { .inputItems(ROBOT_ARM_ZPM, 2) .inputItems(ELECTRIC_MOTOR_ZPM, 2) .inputItems(wireGtDouble, UraniumRhodiumDinaquadide, 16) - .inputItems(OPTICAL_PIPES[0].asStack(2)) + .inputItems(OPTICAL_PIPE[0].asStack(2)) .inputFluids(SolderingAlloy.getFluid(L * 4)) .inputFluids(Polybenzimidazole.getFluid(L * 2)) .outputItems(OBJECT_HOLDER) @@ -150,12 +150,12 @@ public static void init(Consumer provider) { .inputItems(wireGtDouble, EnrichedNaquadahTriniumEuropiumDuranide, 32) .inputItems(foil, Tritanium, 64) .inputItems(foil, Tritanium, 64) - .inputItems(OPTICAL_PIPES[0].asStack(8)) + .inputItems(OPTICAL_PIPE[0].asStack(8)) .inputFluids(SolderingAlloy.getFluid(L * 4)) .inputFluids(Polybenzimidazole.getFluid(L * 4)) .outputItems(NETWORK_SWITCH) .stationResearch(b -> b - .researchStack(new ItemStack(OPTICAL_PIPES[0])) + .researchStack(new ItemStack(OPTICAL_PIPE[0])) .CWUt(32) .EUt(VA[ZPM])) .duration(1200).EUt(100000).save(provider); @@ -167,7 +167,7 @@ public static void init(Consumer provider) { .inputItems(TOOL_DATA_ORB) .inputItems(COVER_SCREEN) .inputItems(wireGtDouble, UraniumRhodiumDinaquadide, 64) - .inputItems(OPTICAL_PIPES[0].asStack(16)) + .inputItems(OPTICAL_PIPE[0].asStack(16)) .inputFluids(SolderingAlloy.getFluid(L * 8)) .inputFluids(VanadiumGallium.getFluid(L * 8)) .inputFluids(PCBCoolant.getFluid(4000)) @@ -210,7 +210,7 @@ public static void init(Consumer provider) { .inputItems(ADVANCED_COMPUTER_CASING.asStack()) .inputItems(CustomTags.UV_CIRCUITS) .inputItems(EMITTER_ZPM) - .inputItems(OPTICAL_PIPES[0].asStack(2)) + .inputItems(OPTICAL_PIPE[0].asStack(2)) .outputItems(HPCA_BRIDGE_COMPONENT) .inputFluids(PCBCoolant.getFluid(1000)) .cleanroom(CleanroomType.CLEANROOM) @@ -239,7 +239,7 @@ public static void init(Consumer provider) { .inputItems(ITEM_IMPORT_BUS[LuV]) .inputItems(CustomTags.LuV_CIRCUITS) .inputItems(SENSOR_IV) - .inputItems(OPTICAL_PIPES[0].asStack(2)) + .inputItems(OPTICAL_PIPE[0].asStack(2)) .inputFluids(Polybenzimidazole.getFluid(L * 2)) .outputItems(DATA_HATCH_RECEIVER) .cleanroom(CleanroomType.CLEANROOM) @@ -250,7 +250,7 @@ public static void init(Consumer provider) { .inputItems(ITEM_EXPORT_BUS[LuV]) .inputItems(CustomTags.LuV_CIRCUITS) .inputItems(EMITTER_IV) - .inputItems(OPTICAL_PIPES[0].asStack(2)) + .inputItems(OPTICAL_PIPE[0].asStack(2)) .inputFluids(Polybenzimidazole.getFluid(L * 2)) .outputItems(DATA_HATCH_TRANSMITTER) .cleanroom(CleanroomType.CLEANROOM) @@ -287,7 +287,7 @@ public static void init(Consumer provider) { .inputItems(CASING_LAMINATED_GLASS.asStack(1)) .inputItems(foil, Osmiridium, 2) .inputFluids(Polytetrafluoroethylene.getFluid(L)) - .outputItems(LASER_PIPES[0]) + .outputItems(LASER_PIPE[0]) .cleanroom(CleanroomType.CLEANROOM) .duration(100).EUt(VA[IV]).save(provider); } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java index b91c909ee9..487b45591f 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java @@ -2,8 +2,8 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.common.block.CableBlock; -import com.gregtechceu.gtceu.common.blockentity.CableBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeMaterialBlockEntity; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.nbt.CompoundTag; @@ -51,14 +51,17 @@ public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPlugi public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccessor) { CompoundTag data = compoundTag.getCompound(getUid().toString()); if (blockAccessor.getBlock() instanceof CableBlock cableBlock) { - CableBlockEntity cable = (CableBlockEntity) cableBlock.getPipeTile(blockAccessor.getLevel(), + PipeMaterialBlockEntity cable = cableBlock.getBlockEntity(blockAccessor.getLevel(), blockAccessor.getPosition()); if (cable != null) { var cableData = new CompoundTag(); + // TODO fix + /* cableData.putLong("maxVoltage", cable.getMaxVoltage()); cableData.putLong("currentVoltage", cable.getCurrentMaxVoltage()); cableData.putDouble("maxAmperage", cable.getMaxAmperage()); cableData.putDouble("currentAmperage", cable.getAverageAmperage()); + */ data.put("cableData", cableData); } } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java index f819034570..b5aacd2a13 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java @@ -1,12 +1,7 @@ package com.gregtechceu.gtceu.integration.top.provider; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.common.block.CableBlock; -import com.gregtechceu.gtceu.common.blockentity.CableBlockEntity; -import com.gregtechceu.gtceu.utils.GTUtil; -import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; @@ -14,8 +9,6 @@ import mcjty.theoneprobe.api.*; -import static com.gregtechceu.gtceu.utils.FormattingUtil.DECIMAL_FORMAT_1F; - public class CableInfoProvider implements IProbeInfoProvider { @Override @@ -26,6 +19,8 @@ public ResourceLocation getID() { @Override public void addProbeInfo(ProbeMode probeMode, IProbeInfo iProbeInfo, Player player, Level level, BlockState blockState, IProbeHitData iProbeHitData) { + // TODO fix + /* if (blockState.getBlock() instanceof CableBlock cableBlock) { CableBlockEntity cable = (CableBlockEntity) cableBlock.getPipeTile(level, iProbeHitData.getPos()); if (cable != null) { @@ -48,5 +43,6 @@ public void addProbeInfo(ProbeMode probeMode, IProbeInfo iProbeInfo, Player play horizontalPane.text(DECIMAL_FORMAT_1F.format(cable.getMaxAmperage()) + "A"); } } + */ } } From e8215adc4d96e5f675c0fef266a9d4a40e449e64 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 22 Aug 2024 18:03:30 +0300 Subject: [PATCH 06/70] holy errors, batman! --- .../gtceu/api/block/MaterialBlock.java | 1 - .../gtceu/api/block/MaterialPipeBlock.java | 120 ---- .../gtceu/api/block/PipeBlock.java | 472 ------------- .../blockentity/MetaMachineBlockEntity.java | 4 +- .../api/blockentity/PipeBlockEntity.java | 1 - .../gtceu/api/cover/CoverBehavior.java | 2 +- .../gtceu/api/data/tag/TagPrefix.java | 101 +-- .../gtceu/api/fluids/FluidState.java | 6 + .../physical/tile/PipeCoverHolder.java | 2 +- .../predicate/test/FluidTestObject.java | 6 +- .../gtceu/api/item/LaserPipeBlockItem.java | 47 -- .../gtceu/api/item/MaterialPipeBlockItem.java | 65 -- .../gtceu/api/item/MetaMachineItem.java | 1 - .../gtceu/api/item/PipeBlockItem.java | 102 --- .../gtceu/api/misc/LaserContainerList.java | 16 + .../gtceu/api/pipenet/IPipeNode.java | 1 - .../longdistance/LongDistancePipeType.java | 4 +- .../renderer/BlockHighLightRenderer.java | 1 - .../gtceu/client/renderer/pipe/PipeModel.java | 151 ++++ .../renderer/pipe/cache/BlockableSQC.java | 77 ++ .../renderer/pipe/cache/RestrictiveSQC.java | 82 +++ .../pipe/util/PipeSpriteWoodClarifier.java | 12 + .../renderer/pipe/util/WoodCacheKey.java | 53 ++ .../gtceu/common/block/DuctPipeBlock.java | 4 +- .../gtceu/common/block/FluidPipeBlock.java | 172 ----- .../gtceu/common/block/ItemPipeBlock.java | 94 --- .../gtceu/common/block/LaserPipeBlock.java | 115 --- .../blockentity/FluidPipeBlockEntity.java | 572 --------------- .../blockentity/ItemPipeBlockEntity.java | 193 ----- .../blockentity/LaserPipeBlockEntity.java | 234 ------- .../gtceu/common/cover/ConveyorCover.java | 661 ++++++++++++------ .../gtceu/common/cover/PumpCover.java | 1 + .../gtceu/common/cover/RobotArmCover.java | 1 - .../common/cover/filter/MatchResult.java | 45 ++ .../common/cover/filter/MergabilityInfo.java | 60 ++ .../gtceu/common/data/GTBlockEntities.java | 4 +- .../gtceu/common/data/GTBlocks.java | 112 +-- .../gtceu/common/data/GTMachines.java | 4 +- .../gtceu/common/data/GTMaterials.java | 16 +- .../common/item/PortableScannerBehavior.java | 1 - .../block/pipe/MaterialPipeBlock.java | 14 + .../block/pipe/MaterialPipeStructure.java | 121 ++++ .../pipelike/fluidpipe/FluidPipeData.java | 61 -- .../pipelike/fluidpipe/FluidPipeNet.java | 47 -- .../pipelike/fluidpipe/FluidPipeType.java | 88 --- .../fluidpipe/FluidTransferHandler.java | 161 ----- .../pipelike/fluidpipe/LevelFluidPipeNet.java | 28 - .../pipelike/fluidpipe/PipeNetRoutePath.java | 49 -- .../pipelike/fluidpipe/PipeTankList.java | 178 ----- .../common/pipelike/item/ItemNetHandler.java | 505 ------------- .../common/pipelike/item/ItemNetWalker.java | 140 ---- .../common/pipelike/item/ItemPipeData.java | 53 -- .../common/pipelike/item/ItemPipeNet.java | 64 -- .../common/pipelike/item/ItemPipeType.java | 97 --- .../common/pipelike/item/ItemRoutePath.java | 68 -- .../pipelike/item/LevelItemPipeNet.java | 28 - .../pipelike/laser/LaserNetHandler.java | 115 --- .../common/pipelike/laser/LaserNetWalker.java | 94 --- .../common/pipelike/laser/LaserPipeNet.java | 126 ---- .../pipelike/laser/LaserPipeProperties.java | 9 - .../common/pipelike/laser/LaserPipeType.java | 41 -- .../common/pipelike/laser/LaserRoutePath.java | 69 -- .../pipelike/laser/LevelLaserPipeNet.java | 29 - .../fluid}/LDFluidEndpointMachine.java | 2 +- .../fluid}/LDFluidPipeType.java | 2 +- .../item}/LDItemEndpointMachine.java | 2 +- .../item}/LDItemPipeType.java | 2 +- .../net/fluid/ContainmentFailure.java | 151 ++++ .../net/fluid/FluidCapabilityObject.java | 303 ++++++++ .../net/fluid/FluidContainmentLogic.java | 149 ++++ .../net/fluid/FluidEQTraverseData.java | 64 ++ .../net/fluid/FluidRRTraverseData.java | 63 ++ .../pipelike/net/fluid/FluidTraverseData.java | 177 +++++ .../net/fluid/IFluidTransferController.java | 72 ++ .../fluid/IFluidTraverseGuideProvider.java | 22 + .../pipelike/net/fluid/WorldFluidNet.java | 116 +++ .../net/item/IItemTransferController.java | 78 +++ .../net/item/IItemTraverseGuideProvider.java | 22 + .../net/item/ItemCapabilityObject.java | 251 +++++++ .../pipelike/net/item/ItemEQTraverseData.java | 66 ++ .../pipelike/net/item/ItemRRTraverseData.java | 64 ++ .../pipelike/net/item/ItemTraverseData.java | 64 ++ .../pipelike/net/item/WorldItemNet.java | 118 ++++ .../gregtechceu/gtceu/core/MixinHelpers.java | 4 +- .../gtceu/data/recipe/CraftingComponent.java | 66 +- .../recipe/configurable/RecipeAddition.java | 4 +- .../recipe/generated/PipeRecipeHandler.java | 18 +- .../recipe/misc/AssemblerRecipeLoader.java | 16 +- .../data/recipe/misc/CircuitRecipes.java | 2 +- .../data/recipe/misc/ComponentRecipes.java | 30 +- .../data/recipe/misc/ComputerRecipes.java | 26 +- .../recipe/misc/CraftingRecipeLoader.java | 16 +- .../gtceu/data/recipe/misc/GCyMRecipes.java | 10 +- .../data/recipe/misc/MachineRecipeLoader.java | 2 +- .../recipe/misc/MetaTileEntityLoader.java | 96 +-- .../MetaTileEntityMachineRecipeLoader.java | 4 +- .../gtceu/integration/jade/GTJadePlugin.java | 1 - .../provider/FluidPipeStorageProvider.java | 1 - .../gtceu/utils/DummyMachineBlockEntity.java | 24 + 99 files changed, 3137 insertions(+), 4772 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/block/MaterialPipeBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/block/PipeBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/item/LaserPipeBlockItem.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/item/MaterialPipeBlockItem.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/item/PipeBlockItem.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/PipeSpriteWoodClarifier.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/block/FluidPipeBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/block/ItemPipeBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/block/LaserPipeBlock.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/blockentity/FluidPipeBlockEntity.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeData.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidTransferHandler.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/LevelFluidPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeNetRoutePath.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeTankList.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetHandler.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetWalker.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeData.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemRoutePath.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/item/LevelItemPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeProperties.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LevelLaserPipeNet.java rename src/main/java/com/gregtechceu/gtceu/common/pipelike/{fluidpipe/longdistance => longdistance/fluid}/LDFluidEndpointMachine.java (97%) rename src/main/java/com/gregtechceu/gtceu/common/pipelike/{fluidpipe/longdistance => longdistance/fluid}/LDFluidPipeType.java (86%) rename src/main/java/com/gregtechceu/gtceu/common/pipelike/{item/longdistance => longdistance/item}/LDItemEndpointMachine.java (96%) rename src/main/java/com/gregtechceu/gtceu/common/pipelike/{item/longdistance => longdistance/item}/LDItemPipeType.java (87%) create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java index 7aa8bfc7e9..a27c8a3688 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java @@ -3,7 +3,6 @@ import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.item.PipeBlockItem; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; import com.gregtechceu.gtceu.client.renderer.block.MaterialBlockRenderer; diff --git a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/block/MaterialPipeBlock.java deleted file mode 100644 index 034cf09bbe..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialPipeBlock.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.gregtechceu.gtceu.api.block; - -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.pipenet.*; -import com.gregtechceu.gtceu.client.model.PipeModel; -import com.gregtechceu.gtceu.client.renderer.block.PipeBlockRenderer; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.client.color.block.BlockColor; -import net.minecraft.core.BlockPos; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.Nullable; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * @author KilaBash - * @date 2023/2/28 - * @implNote MaterialPipeBlock - */ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public abstract class MaterialPipeBlock< - PipeType extends Enum & IPipeType & IMaterialPipeType, NodeDataType, - WorldPipeNetType extends LevelPipeNet>> - extends PipeBlock { - - public final Material material; - public final PipeBlockRenderer renderer; - public final PipeModel model; - - public MaterialPipeBlock(Properties properties, PipeType pipeType, Material material) { - super(properties, pipeType); - this.material = material; - this.model = createPipeModel(); - this.renderer = new PipeBlockRenderer(this.model); - } - - @OnlyIn(Dist.CLIENT) - public static BlockColor tintedColor() { - return (blockState, level, blockPos, index) -> { - if (blockState.getBlock() instanceof MaterialPipeBlock block) { - if (blockPos != null && level != null && - level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { - if (pipe.getFrameMaterial() != null) { - if (index == 3) { - return pipe.getFrameMaterial().getMaterialRGB(); - } else if (index == 4) { - return pipe.getFrameMaterial().getMaterialSecondaryRGB(); - } - } - if (pipe.isPainted()) { - return pipe.getRealColor(); - } - } - return block.tinted(blockState, level, blockPos, index); - } - return -1; - }; - } - - public int tinted(BlockState blockState, @Nullable BlockAndTintGetter blockAndTintGetter, - @Nullable BlockPos blockPos, int index) { - return index == 0 || index == 1 ? material.getMaterialRGB() : -1; - } - - @Override - protected PipeModel getPipeModel() { - return model; - } - - @Override - public final NodeDataType createRawData(BlockState pState, @Nullable ItemStack pStack) { - return createMaterialData(); - } - - @Override - public NodeDataType createProperties(IPipeNode pipeTile) { - PipeType pipeType = pipeTile.getPipeType(); - Material material = ((MaterialPipeBlock) pipeTile - .getPipeBlock()).material; - if (pipeType == null || material == null) { - return getFallbackType(); - } - return createProperties(pipeType, material); - } - - protected abstract NodeDataType createProperties(PipeType pipeType, Material material); - - @Override - public @Nullable PipeBlockRenderer getRenderer(BlockState state) { - return renderer; - } - - @Override - public final NodeDataType getFallbackType() { - return createMaterialData(); - } - - protected abstract NodeDataType createMaterialData(); - - protected abstract PipeModel createPipeModel(); - - @Override - public String getDescriptionId() { - return pipeType.getTagPrefix().getUnlocalizedName(material); - } - - @Override - public MutableComponent getName() { - return pipeType.getTagPrefix().getLocalizedName(material); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/block/PipeBlock.java deleted file mode 100644 index b129ce3c9d..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/block/PipeBlock.java +++ /dev/null @@ -1,472 +0,0 @@ -package com.gregtechceu.gtceu.api.block; - -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.item.PipeBlockItem; -import com.gregtechceu.gtceu.api.item.component.IInteractionItem; -import com.gregtechceu.gtceu.api.item.tool.GTToolType; -import com.gregtechceu.gtceu.api.item.tool.ToolHelper; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.api.pipenet.IPipeType; -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; -import com.gregtechceu.gtceu.api.pipenet.PipeNet; -import com.gregtechceu.gtceu.client.model.PipeModel; -import com.gregtechceu.gtceu.client.renderer.block.PipeBlockRenderer; -import com.gregtechceu.gtceu.common.data.GTBlocks; -import com.gregtechceu.gtceu.common.data.GTItems; -import com.gregtechceu.gtceu.common.item.CoverPlaceBehavior; -import com.gregtechceu.gtceu.config.ConfigHolder; -import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.client.renderer.IBlockRendererProvider; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.sounds.SoundSource; -import net.minecraft.util.RandomSource; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.DyeColor; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.context.UseOnContext; -import net.minecraft.world.level.*; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityTicker; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.level.storage.loot.LootParams; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -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.EntityCollisionContext; -import net.minecraft.world.phys.shapes.Shapes; -import net.minecraft.world.phys.shapes.VoxelShape; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * @author KilaBash - * @date 2023/2/28 - * @implNote PipeBlock - */ -@SuppressWarnings("deprecation") -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public abstract class PipeBlock & IPipeType, NodeDataType, - WorldPipeNetType extends LevelPipeNet>> extends AppearanceBlock - implements EntityBlock, IBlockRendererProvider, SimpleWaterloggedBlock { - - public final PipeType pipeType; - - public PipeBlock(Properties properties, PipeType pipeType) { - super(properties); - this.pipeType = pipeType; - registerDefaultState(defaultBlockState().setValue(BlockProperties.SERVER_TICK, false) - .setValue(BlockStateProperties.WATERLOGGED, false)); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - super.createBlockStateDefinition(builder.add(BlockProperties.SERVER_TICK, BlockStateProperties.WATERLOGGED)); - } - - @Override - public FluidState getFluidState(BlockState state) { - return state.getValue(BlockStateProperties.WATERLOGGED) ? Fluids.WATER.getSource(false) : - super.getFluidState(state); - } - - @Override - public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor level, - BlockPos pos, BlockPos neighborPos) { - if (state.getValue(BlockStateProperties.WATERLOGGED)) { - level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); - } - return super.updateShape(state, direction, neighborState, level, pos, neighborPos); - } - - @Override - public final PipeBlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return getBlockEntityType().create(pos, state); - } - - public abstract WorldPipeNetType getWorldPipeNet(ServerLevel level); - - public abstract BlockEntityType> getBlockEntityType(); - - /** - * Add data via placement. - */ - public abstract NodeDataType createRawData(BlockState pState, @Nullable ItemStack pStack); - - public NodeDataType createProperties(BlockState state, @Nullable ItemStack stack) { - return pipeType.modifyProperties(createRawData(state, stack)); - } - - public abstract NodeDataType createProperties(IPipeNode pipeTile); - - /** - * Sometimes some people - */ - public abstract NodeDataType getFallbackType(); - - @Nullable - @Override - public abstract PipeBlockRenderer getRenderer(BlockState state); - - protected abstract PipeModel getPipeModel(); - - public void updateActiveNodeStatus(@NotNull Level worldIn, BlockPos pos, - IPipeNode pipeTile) { - if (worldIn.isClientSide) return; - - PipeNet pipeNet = getWorldPipeNet((ServerLevel) worldIn).getNetFromPos(pos); - if (pipeNet != null && pipeTile != null) { - int activeConnections = pipeTile.getConnections(); // remove blocked connections - boolean isActiveNodeNow = activeConnections != 0; - boolean modeChanged = pipeNet.markNodeAsActive(pos, isActiveNodeNow); - if (modeChanged) { - onActiveModeChange(worldIn, pos, isActiveNodeNow, false); - } - } - } - - @Override - public void onNeighborChange(BlockState state, LevelReader level, BlockPos pos, BlockPos neighbor) { - if (level.isClientSide()) return; - IPipeNode pipeTile = getPipeTile(level, pos); - - if (pipeTile != null) { - Direction facing = GTUtil.getFacingToNeighbor(pos, neighbor); - if (facing == null) return; - if (!ConfigHolder.INSTANCE.machines.gt6StylePipesCables) { - boolean open = pipeTile.isConnected(facing); - boolean canConnect = pipeTile.getCoverContainer().getCoverAtSide(facing) != null || - canConnect(pipeTile, facing); - if (!open && canConnect) - pipeTile.setConnection(facing, true, false); - if (open && !canConnect) - pipeTile.setConnection(facing, false, false); - updateActiveNodeStatus(pipeTile.getPipeLevel(), pos, pipeTile); - } - PipeNet net = pipeTile.getPipeNet(); - if (net != null) { - pipeTile.getPipeNet().onNeighbourUpdate(neighbor); - } - } - } - - /** - * Get pipe nodes with the same pipe type. - */ - @Nullable - @SuppressWarnings("unchecked") - public IPipeNode getPipeTile(BlockGetter level, BlockPos pos) { - if (level.getBlockEntity(pos) instanceof IPipeNode pipeTile && - pipeTile.getPipeType().type().equals(pipeType.type())) { - return (IPipeNode) pipeTile; - } - return null; - } - - /** - * Can be used to update tile entity to tickable when node becomes active - * usable for fluid pipes, as example - */ - protected void onActiveModeChange(Level world, BlockPos pos, boolean isActiveNow, boolean isInitialChange) {} - - public boolean canConnect(IPipeNode selfTile, Direction facing) { - if (selfTile.getPipeLevel().getBlockState(selfTile.getPipePos().relative(facing)).getBlock() == Blocks.AIR) - return false; - CoverBehavior cover = selfTile.getCoverContainer().getCoverAtSide(facing); - if (cover != null && !cover.canPipePassThrough()) { - return false; - } - BlockEntity other = selfTile.getNeighbor(facing); - if (other instanceof IPipeNode node) { - cover = node.getCoverContainer().getCoverAtSide(facing.getOpposite()); - if (cover != null && !cover.canPipePassThrough()) - return false; - return canPipesConnect(selfTile, facing, (IPipeNode) other); - } - return canPipeConnectToBlock(selfTile, facing, other); - } - - public abstract boolean canPipesConnect(IPipeNode selfTile, Direction side, - IPipeNode sideTile); - - public abstract boolean canPipeConnectToBlock(IPipeNode selfTile, Direction side, - @Nullable BlockEntity tile); - - @Override - public void setPlacedBy(Level level, BlockPos pos, BlockState state, @Nullable LivingEntity placer, - ItemStack stack) { - super.setPlacedBy(level, pos, state, placer, stack); - IPipeNode pipeTile = getPipeTile(level, pos); - if (pipeTile != null) { - // Color pipes/cables on place if holding spray can in off-hand - if (placer instanceof Player player) { - ItemStack offhand = placer.getOffhandItem(); - for (int i = 0; i < DyeColor.values().length; i++) { - if (offhand.is(GTItems.SPRAY_CAN_DYES[i].get())) { - ((IInteractionItem) GTItems.SPRAY_CAN_DYES[i].get().getComponents().get(0)) - .useOn(new UseOnContext(player, InteractionHand.OFF_HAND, - new BlockHitResult(Vec3.ZERO, player.getDirection(), pos, false))); - break; - } - } - } - } - } - - @Override - public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) { - level.scheduleTick(pos, this, 1); - } - - @Override - public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, - boolean isMoving) { - if (level.isClientSide) return; - IPipeNode pipeTile = getPipeTile(level, pos); - if (pipeTile != null) { - Direction facing = GTUtil.getFacingToNeighbor(pos, fromPos); - if (facing == null) return; - if (!ConfigHolder.INSTANCE.machines.gt6StylePipesCables) { - boolean open = pipeTile.isConnected(facing); - boolean canConnect = pipeTile.getCoverContainer().getCoverAtSide(facing) != null || - this.canConnect(pipeTile, facing); - if (!open && canConnect && state.getBlock() != block) - pipeTile.setConnection(facing, true, false); - if (open && !canConnect) - pipeTile.setConnection(facing, false, false); - updateActiveNodeStatus(level, pos, pipeTile); - } - } - } - - @Override - public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) { - if (pState.hasBlockEntity() && !pState.is(pNewState.getBlock())) { - pLevel.removeBlockEntity(pPos); - if (pLevel instanceof ServerLevel serverLevel) { - getWorldPipeNet(serverLevel).removeNode(pPos); - } - } - } - - @Override - public void destroy(LevelAccessor level, BlockPos pos, BlockState state) { - IPipeNode pipeTile = getPipeTile(level, pos); - if (pipeTile != null) { - pipeTile.getCoverContainer().dropAllCovers(); - } - super.destroy(level, pos, state); - if (level instanceof ServerLevel serverLevel) { - getWorldPipeNet(serverLevel).removeNode(pos); - } - } - - @Override - public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - IPipeNode pipeTile = getPipeTile(level, pos); - if (pipeTile != null) { - int activeConnections = pipeTile.getConnections(); - boolean isActiveNode = activeConnections != 0; - getWorldPipeNet(level).addNode(pos, createRawData(state, null), 0, activeConnections, isActiveNode); - onActiveModeChange(level, pos, isActiveNode, true); - } - } - - @Override - public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult hit) { - ItemStack itemStack = player.getItemInHand(hand); - BlockEntity entity = level.getBlockEntity(pos); - - PipeBlockEntity pipeBlockEntity = null; - if (entity instanceof PipeBlockEntity pbe) { - pipeBlockEntity = pbe; - } - if (pipeBlockEntity == null) { - return InteractionResult.FAIL; - } - - if (pipeBlockEntity.getFrameMaterial() == null && pipeType.getThickness() < 1) { - var frameBlock = MaterialBlock.getFrameboxFromItem(itemStack); - if (frameBlock != null) { - pipeBlockEntity.setFrameMaterial(frameBlock.material); - if (!player.isCreative()) itemStack.shrink(1); - SoundType type = VanillaRecipeHelper.isMaterialWood(frameBlock.material) ? SoundType.WOOD : - SoundType.METAL; - level.playSound(player, pos, - type.getPlaceSound(), SoundSource.BLOCKS, - (type.getVolume() + 1.0F) / 2.0F, type.getPitch() * 0.8F); - player.swing(hand); - return InteractionResult.SUCCESS; - } - } - - if (itemStack.getItem() instanceof PipeBlockItem itemPipe) { - BlockPos offsetPos = pos.offset(hit.getDirection().getNormal()); - BlockState stateAtSide = level.getBlockState(offsetPos); - if (stateAtSide.getBlock() instanceof MaterialBlock matBlock && matBlock.tagPrefix == TagPrefix.frameGt) { - if (itemPipe.getBlock().pipeType == pipeType) { - boolean wasPlaced = matBlock.replaceWithFramedPipe(level, offsetPos, stateAtSide, player, itemStack, - hit); - if (wasPlaced) { - pipeBlockEntity.setConnection(hit.getDirection(), true, false); - } - return wasPlaced ? InteractionResult.CONSUME : InteractionResult.FAIL; - } - } - } - - Set types = ToolHelper.getToolTypes(itemStack); - if (!types.isEmpty() && ToolHelper.canUse(itemStack)) { - var result = pipeBlockEntity.onToolClick(types, itemStack, new UseOnContext(player, hand, hit)); - if (result.getSecond() == InteractionResult.CONSUME && player instanceof ServerPlayer serverPlayer) { - ToolHelper.playToolSound(result.getFirst(), serverPlayer); - - if (!serverPlayer.isCreative()) { - ToolHelper.damageItem(itemStack, serverPlayer, 1); - } - } - return result.getSecond(); - } - return InteractionResult.PASS; - } - - @Override - public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { - var pipeNode = getPipeTile(level, pos); - if (pipeNode.getFrameMaterial() != null) { - BlockState frameState = GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, pipeNode.getFrameMaterial()) - .getDefaultState(); - frameState.getBlock().entityInside(frameState, level, pos, entity); - } - super.entityInside(state, level, pos, entity); - } - - @Override - public boolean isCollisionShapeFullBlock(BlockState state, BlockGetter level, BlockPos pos) { - var pipeNode = getPipeTile(level, pos); - if (pipeNode != null && pipeNode.getFrameMaterial() != null) { - return false; - } - return false; - } - - @Override - public VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - var pipeNode = getPipeTile(level, pos); - if (pipeNode != null && pipeNode.getFrameMaterial() != null) { - return MaterialBlock.FRAME_COLLISION_BOX; - } - return super.getCollisionShape(state, level, pos, context); - } - - @Override - public VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext context) { - var pipeNode = getPipeTile(pLevel, pPos); - var connections = 0; - if (pipeNode != null) { - if (pipeNode.getFrameMaterial() != null) { - return Shapes.block(); - } - connections = pipeNode.getVisualConnections(); - VoxelShape shape = getPipeModel().getShapes(connections); - shape = Shapes.or(shape, pipeNode.getCoverContainer().addCoverCollisionBoundingBox()); - - if (context instanceof EntityCollisionContext entityCtx && entityCtx.getEntity() instanceof Player player) { - var coverable = pipeNode.getCoverContainer(); - var held = player.getMainHandItem(); - Set types = Set.of(GTToolType.WIRE_CUTTER, GTToolType.WRENCH); - BlockEntity tile = pLevel.getBlockEntity(pPos); - if (tile instanceof PipeBlockEntity pipeTile) { - types = Set.of(pipeTile.getPipeTuneTool()); - } - - if (types.stream().anyMatch(type -> type.itemTags.stream().anyMatch(held::is)) || - CoverPlaceBehavior.isCoverBehaviorItem(held, coverable::hasAnyCover, - coverDef -> ICoverable.canPlaceCover(coverDef, coverable)) || - (held.getItem() instanceof BlockItem blockItem && - blockItem.getBlock() instanceof PipeBlock pipeBlock && - pipeBlock.pipeType.type().equals(pipeType.type()))) { - return Shapes.block(); - } - } - return shape; - } - return getPipeModel().getShapes(connections); - } - - @Nullable - @Override - public BlockEntityTicker getTicker(Level level, BlockState state, - BlockEntityType blockEntityType) { - if (blockEntityType == getBlockEntityType()) { - if (!level.isClientSide && state.getValue(BlockProperties.SERVER_TICK)) { - return (pLevel, pPos, pState, pTile) -> { - if (pTile instanceof IPipeNode pipeNode) { - pipeNode.serverTick(); - } - }; - } - } - return null; - } - - @Override - public BlockState getBlockAppearance(BlockState state, BlockAndTintGetter level, BlockPos pos, Direction side, - BlockState sourceState, BlockPos sourcePos) { - var pipe = getPipeTile(level, pos); - if (pipe != null) { - var appearance = pipe.getCoverContainer().getBlockAppearance(state, level, pos, side, sourceState, - sourcePos); - if (appearance != null) return appearance; - } - return super.getBlockAppearance(state, level, pos, side, sourceState, sourcePos); - } - - @Override - public List getDrops(BlockState state, LootParams.Builder builder) { - var context = builder.withParameter(LootContextParams.BLOCK_STATE, state).create(LootContextParamSets.BLOCK); - BlockEntity tileEntity = context.getParamOrNull(LootContextParams.BLOCK_ENTITY); - List drops = new ArrayList<>(super.getDrops(state, builder)); - if (tileEntity instanceof IPipeNode pipeTile) { - if (pipeTile.getFrameMaterial() != null) { - drops.addAll(GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, pipeTile.getFrameMaterial()) - .getDefaultState().getDrops(builder)); - } - for (Direction direction : GTUtil.DIRECTIONS) { - pipeTile.getCoverContainer().removeCover(direction, null); - } - } - return drops; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java index 301c3eb272..c915a4a2fb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java @@ -17,8 +17,8 @@ import com.gregtechceu.gtceu.api.pipenet.longdistance.ILDEndpoint; import com.gregtechceu.gtceu.client.renderer.GTRendererProvider; import com.gregtechceu.gtceu.common.machine.owner.IMachineOwner; -import com.gregtechceu.gtceu.common.pipelike.fluidpipe.longdistance.LDFluidEndpointMachine; -import com.gregtechceu.gtceu.common.pipelike.item.longdistance.LDItemEndpointMachine; +import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidEndpointMachine; +import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemEndpointMachine; import com.lowdragmc.lowdraglib.client.renderer.IRenderer; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java index 09acd7473a..23c4f238d3 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.block.BlockProperties; -import com.gregtechceu.gtceu.api.block.MaterialPipeBlock; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.IToolable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java index 6978977aaa..67350b78ed 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java @@ -196,7 +196,7 @@ public boolean forcePipeRenderConnection() { return true; } - public CoverRenderer getCoverRenderer() { + public CoverRenderer getRenderer() { return coverDefinition.getCoverRenderer(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java index 14704d4512..c531987318 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java @@ -729,65 +729,78 @@ public static TagPrefix get(String name) { material.hasFlag(MaterialFlags.GENERATE_FRAME)); // Pipes - public static final TagPrefix pipeTinyFluid = new TagPrefix("pipeTinyFluid") - .itemTable(() -> GTBlocks.FLUID_PIPE_BLOCKS).langValue("Tiny %s Fluid Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M / 2) - .unificationEnabled(true); - public static final TagPrefix pipeSmallFluid = new TagPrefix("pipeSmallFluid") - .itemTable(() -> GTBlocks.FLUID_PIPE_BLOCKS).langValue("Small %s Fluid Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M).unificationEnabled(true); - public static final TagPrefix pipeNormalFluid = new TagPrefix("pipeNormalFluid") - .itemTable(() -> GTBlocks.FLUID_PIPE_BLOCKS).langValue("Normal %s Fluid Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 3) + public static final TagPrefix pipeTiny = new TagPrefix("pipeTiny") + .langValue("Tiny %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M / 2) .unificationEnabled(true); - public static final TagPrefix pipeLargeFluid = new TagPrefix("pipeLargeFluid") - .itemTable(() -> GTBlocks.FLUID_PIPE_BLOCKS).langValue("Large %s Fluid Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 6) + public static final TagPrefix pipeSmall = new TagPrefix("pipeSmall") + .langValue("Small %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M) .unificationEnabled(true); - public static final TagPrefix pipeHugeFluid = new TagPrefix("pipeHugeFluid") - .itemTable(() -> GTBlocks.FLUID_PIPE_BLOCKS).langValue("Huge %s Fluid Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 12) + public static final TagPrefix pipeNormal = new TagPrefix("pipeNormal") + .langValue("Normal %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 3) .unificationEnabled(true); - - public static final TagPrefix pipeQuadrupleFluid = new TagPrefix("pipeQuadrupleFluid") - .itemTable(() -> GTBlocks.FLUID_PIPE_BLOCKS).langValue("Quadruple %s Fluid Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 4) + public static final TagPrefix pipeLarge = new TagPrefix("pipeLarge") + .langValue("Large %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 6) .unificationEnabled(true); - public static final TagPrefix pipeNonupleFluid = new TagPrefix("pipeNonupleFluid") - .itemTable(() -> GTBlocks.FLUID_PIPE_BLOCKS).langValue("Nonuple %s Fluid Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 9) + public static final TagPrefix pipeHuge = new TagPrefix("pipeHuge") + .langValue("Huge %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 12) .unificationEnabled(true); - public static final TagPrefix pipeSmallItem = new TagPrefix("pipeSmallItem") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Small %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M).unificationEnabled(true); - public static final TagPrefix pipeNormalItem = new TagPrefix("pipeNormalItem") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Normal %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 3) - .unificationEnabled(true); - public static final TagPrefix pipeLargeItem = new TagPrefix("pipeLargeItem") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Large %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 6) + public static final TagPrefix pipeQuadruple = new TagPrefix("pipeQuadruple") + .langValue("Quadruple %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 4) .unificationEnabled(true); - public static final TagPrefix pipeHugeItem = new TagPrefix("pipeHugeItem") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Huge %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 12) + public static final TagPrefix pipeNonuple = new TagPrefix("pipeNonuple") + .langValue("Nonuple %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 9) .unificationEnabled(true); + public static final TagPrefix pipeTinyRestrictive = new TagPrefix("pipeTinyRestrictive") + .langValue("Tiny Restrictive %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M) + .unificationEnabled(true); public static final TagPrefix pipeSmallRestrictive = new TagPrefix("pipeSmallRestrictive") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Small Restrictive %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M).unificationEnabled(true); + .langValue("Small Restrictive %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M) + .unificationEnabled(true); public static final TagPrefix pipeNormalRestrictive = new TagPrefix("pipeNormalRestrictive") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Normal Restrictive %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 3) + .langValue("Normal Restrictive %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 3) .unificationEnabled(true); public static final TagPrefix pipeLargeRestrictive = new TagPrefix("pipeLargeRestrictive") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Large Restrictive %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 6) + .langValue("Large Restrictive %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 6) .unificationEnabled(true); public static final TagPrefix pipeHugeRestrictive = new TagPrefix("pipeHugeRestrictive") - .itemTable(() -> GTBlocks.ITEM_PIPE_BLOCKS).langValue("Huge Restrictive %s Item Pipe") - .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)).materialAmount(GTValues.M * 12) + .langValue("Huge Restrictive %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 12) + .unificationEnabled(true); + + public static final TagPrefix pipeQuadrupleRestrictive = new TagPrefix("pipeQuadrupleRestrictive") + .langValue("Quadruple Restrictive %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 4) + .unificationEnabled(true); + public static final TagPrefix pipeNonupleRestrictive = new TagPrefix("pipeNonupleRestrictive") + .langValue("Nonuple Restrictive %s Pipe") + .miningToolTag(GTToolType.WRENCH.harvestTags.get(0)) + .materialAmount(GTValues.M * 9) .unificationEnabled(true); // Wires and cables diff --git a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java index cde8d46441..28dc19201f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java +++ b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.fluids; import lombok.Getter; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import org.jetbrains.annotations.NotNull; public enum FluidState { @@ -16,4 +17,9 @@ public enum FluidState { FluidState(@NotNull String translationKey) { this.translationKey = translationKey; } + + public static FluidState inferState(FluidStack stack) { + if (stack.getFluid() instanceof GTFluid fluid) return fluid.getState(); + else return stack.getFluid().getFluidType().isLighterThanAir() ? GAS : LIQUID; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java index 2186a16f39..50c5c12b71 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -255,7 +255,7 @@ public CoverRendererPackage createPackage() { if (covers.isEmpty()) return CoverRendererPackage.EMPTY; CoverRendererPackage rendererPackage = new CoverRendererPackage(shouldRenderCoverBackSides()); for (var cover : covers.entrySet()) { - rendererPackage.addRenderer(cover.getValue().getCoverRenderer(), cover.getKey()); + rendererPackage.addRenderer(cover.getValue().getRenderer(), cover.getKey()); } return rendererPackage; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java index 9aa50c65e6..6bb88fa58b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java @@ -2,7 +2,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -27,12 +27,12 @@ public FluidTestObject(@NotNull FluidStack stack) { @Override @Contract(" -> new") public @NotNull FluidStack recombine() { - return new FluidStack(fluid, 1, tag); + return FluidStack.create(fluid, 1, tag); } @Contract("_ -> new") public @NotNull FluidStack recombine(int amount) { - return new FluidStack(fluid, amount, tag); + return FluidStack.create(fluid, amount, tag); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/LaserPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/LaserPipeBlockItem.java deleted file mode 100644 index dfaef338c1..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/item/LaserPipeBlockItem.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gregtechceu.gtceu.api.item; - -import com.gregtechceu.gtceu.api.block.PipeBlock; -import com.gregtechceu.gtceu.common.block.LaserPipeBlock; - -import com.lowdragmc.lowdraglib.client.renderer.IItemRendererProvider; -import com.lowdragmc.lowdraglib.client.renderer.IRenderer; - -import net.minecraft.client.color.item.ItemColor; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.Nullable; - -import javax.annotation.ParametersAreNonnullByDefault; - -@ParametersAreNonnullByDefault -public class LaserPipeBlockItem extends PipeBlockItem implements IItemRendererProvider { - - public LaserPipeBlockItem(PipeBlock block, Properties properties) { - super(block, properties); - } - - @Override - public LaserPipeBlock getBlock() { - return (LaserPipeBlock) super.getBlock(); - } - - @OnlyIn(Dist.CLIENT) - public static ItemColor tintColor() { - return (itemStack, index) -> { - if (itemStack.getItem() instanceof LaserPipeBlockItem materialBlockItem) { - return LaserPipeBlock.tintedColor().getColor(materialBlockItem.getBlock().defaultBlockState(), null, - null, index); - } - return -1; - }; - } - - @Nullable - @Override - @OnlyIn(Dist.CLIENT) - public IRenderer getRenderer(ItemStack stack) { - return getBlock().getRenderer(getBlock().defaultBlockState()); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/MaterialPipeBlockItem.java deleted file mode 100644 index 52ca3f5ecb..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/item/MaterialPipeBlockItem.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.gregtechceu.gtceu.api.item; - -import com.gregtechceu.gtceu.api.block.MaterialPipeBlock; - -import com.lowdragmc.lowdraglib.client.renderer.IItemRendererProvider; -import com.lowdragmc.lowdraglib.client.renderer.IRenderer; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.client.color.item.ItemColor; -import net.minecraft.network.chat.Component; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * @author KilaBash - * @implNote MaterialBlockItem - */ -@MethodsReturnNonnullByDefault -@ParametersAreNonnullByDefault -public class MaterialPipeBlockItem extends PipeBlockItem implements IItemRendererProvider { - - public MaterialPipeBlockItem(MaterialPipeBlock block, Properties properties) { - super(block, properties); - } - - @Override - @NotNull - public MaterialPipeBlock getBlock() { - return (MaterialPipeBlock) super.getBlock(); - } - - @OnlyIn(Dist.CLIENT) - public static ItemColor tintColor() { - return (itemStack, index) -> { - if (itemStack.getItem() instanceof MaterialPipeBlockItem materialBlockItem) { - return materialBlockItem.getBlock().tinted(materialBlockItem.getBlock().defaultBlockState(), null, null, - index); - } - return -1; - }; - } - - @Nullable - @Override - @OnlyIn(Dist.CLIENT) - public IRenderer getRenderer(ItemStack stack) { - return getBlock().getRenderer(getBlock().defaultBlockState()); - } - - @Override - public Component getDescription() { - return this.getBlock().getName(); - } - - @Override - public Component getName(ItemStack stack) { - return getDescription(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java index 6e83030b51..db78d1ce56 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.api.item; import com.gregtechceu.gtceu.api.block.IMachineBlock; -import com.gregtechceu.gtceu.api.block.PipeBlock; import com.gregtechceu.gtceu.api.machine.MachineDefinition; import com.gregtechceu.gtceu.api.pipenet.IPipeNode; diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/PipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/PipeBlockItem.java deleted file mode 100644 index c03cfb6a6a..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/item/PipeBlockItem.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.gregtechceu.gtceu.api.item; - -import com.gregtechceu.gtceu.api.block.PipeBlock; -import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.config.ConfigHolder; -import com.gregtechceu.gtceu.utils.GTUtil; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.network.chat.Component; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; - -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * @author KilaBash - * @date 2023/6/23 - * @implNote PipeBlockItem - */ -@MethodsReturnNonnullByDefault -@ParametersAreNonnullByDefault -public class PipeBlockItem extends BlockItem { - - public PipeBlockItem(PipeBlock block, Properties properties) { - super(block, properties); - } - - @Override - public PipeBlock getBlock() { - return (PipeBlock) super.getBlock(); - } - - @Override - public void appendHoverText(ItemStack stack, @Nullable Level level, List tooltip, - TooltipFlag isAdvanced) { - super.appendHoverText(stack, level, tooltip, isAdvanced); - if (GTUtil.isShiftDown()) { - tooltip.add(Component.translatable("gtceu.tool_action.wire_cutter.connect")); - } else { - tooltip.add(Component.translatable("gtceu.tool_action.show_tooltips")); - } - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public boolean placeBlock(BlockPlaceContext context, BlockState state) { - Level level = context.getLevel(); - BlockPos pos = context.getClickedPos(); - Direction side = context.getClickedFace(); - - var realPos = pos.relative(side.getOpposite()); - var baseNode = getBlock().getPipeTile(level, realPos); - if (baseNode != null) { - var sideAttach = ICoverable - .traceCoverSide(new BlockHitResult(context.getClickLocation(), side, realPos, false)); - if (sideAttach != null && context.getLevel().isEmptyBlock(realPos.relative(sideAttach))) { - pos = realPos.relative(sideAttach); - side = sideAttach; - context = new BlockPlaceContext(level, context.getPlayer(), context.getHand(), context.getItemInHand(), - new BlockHitResult(context.getClickLocation(), sideAttach, realPos, false)); - } - } - - boolean superVal = super.placeBlock(context, state); - if (superVal && !level.isClientSide) { - IPipeNode selfTile = getBlock().getPipeTile(level, pos); - if (selfTile == null) return true; - if (selfTile.getPipeBlock().canConnect(selfTile, side.getOpposite())) { - selfTile.setConnection(side.getOpposite(), true, false); - } - for (Direction facing : GTUtil.DIRECTIONS) { - BlockEntity te = selfTile.getNeighbor(facing); - if (te instanceof IPipeNode otherPipe) { - if (otherPipe.isConnected(facing.getOpposite())) { - if (otherPipe.getPipeBlock().canPipesConnect(otherPipe, facing.getOpposite(), selfTile)) { - selfTile.setConnection(facing, true, true); - } else { - otherPipe.setConnection(facing.getOpposite(), false, true); - } - } - } else if (!ConfigHolder.INSTANCE.machines.gt6StylePipesCables && - selfTile.getPipeBlock().canPipeConnectToBlock(selfTile, facing, te)) { - selfTile.setConnection(facing, true, false); - } - } - } - return superVal; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java b/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java index d31f38b863..368aef62f9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java +++ b/src/main/java/com/gregtechceu/gtceu/api/misc/LaserContainerList.java @@ -95,4 +95,20 @@ public boolean inputsEnergy(Direction side) { public boolean outputsEnergy(Direction side) { return true; } + + @Override + public long receiveLaser(long laserVoltage, long laserAmperage) { + long available = laserAmperage; + List energyContainerList = this.energyContainerList; + for (ILaserContainer container : energyContainerList) { + long transmitted = container.receiveLaser(laserAmperage, laserAmperage); + if (transmitted > 0) { + available -= transmitted; + if (available <= 0) { + return laserAmperage; + } + } + } + return laserAmperage - available; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java index 741185dd2b..f83e058fb5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.api.pipenet; -import com.gregtechceu.gtceu.api.block.PipeBlock; import com.gregtechceu.gtceu.api.blockentity.IPaintable; import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/longdistance/LongDistancePipeType.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/longdistance/LongDistancePipeType.java index 2983ff3bcb..2410556162 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/longdistance/LongDistancePipeType.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pipenet/longdistance/LongDistancePipeType.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.api.pipenet.longdistance; -import com.gregtechceu.gtceu.common.pipelike.fluidpipe.longdistance.LDFluidPipeType; -import com.gregtechceu.gtceu.common.pipelike.item.longdistance.LDItemPipeType; +import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidPipeType; +import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemPipeType; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java index 86c994cdbe..da0351f097 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java @@ -4,7 +4,6 @@ import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.api.item.PipeBlockItem; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java new file mode 100644 index 0000000000..34cfe1bb46 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -0,0 +1,151 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.BlockableSQC; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.RestrictiveSQC; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.PipeSpriteWoodClarifier; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.client.renderer.pipe.util.WoodCacheKey; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.client.model.ModelFactory; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelData; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.BiConsumer; + +@OnlyIn(Dist.CLIENT) +public class PipeModel extends AbstractPipeModel { + + private static final ResourceLocation loc = GTCEu.id("block/pipe_material"); + + public static final PipeModel[] INSTANCES = new PipeModel[7]; + public static final PipeModel[] RESTRICTIVE_INSTANCES = new PipeModel[INSTANCES.length]; + + static { + model(0, wood -> GTCEu.id("blocks/pipe/pipe_tiny_in")); + model(1, wood -> wood ? GTCEu.id("blocks/pipe/pipe_small_in_wood") : GTCEu.id("blocks/pipe/pipe_small_in")); + model(2, wood -> wood ? GTCEu.id("blocks/pipe/pipe_normal_in_wood") : GTCEu.id("blocks/pipe/pipe_normal_in")); + model(3, wood -> wood ? GTCEu.id("blocks/pipe/pipe_large_in_wood") : GTCEu.id("blocks/pipe/pipe_large_in")); + model(4, wood -> GTCEu.id("blocks/pipe/pipe_huge_in")); + model(5, wood -> GTCEu.id("blocks/pipe/pipe_quadruple_in")); + model(6, wood -> GTCEu.id("blocks/pipe/pipe_nonuple_in")); + } + + private static void model(int i, PipeSpriteWoodClarifier clarifier) { + INSTANCES[i] = new PipeModel(clarifier, false, i + "_standard"); + RESTRICTIVE_INSTANCES[i] = new PipeModel(clarifier, true, i + "_restrictive"); + } + + private final @NotNull PipeSpriteWoodClarifier inTex; + private final @NotNull PipeSpriteWoodClarifier sideTex; + private final @Nullable PipeSpriteWoodClarifier restrictiveTex; + private final @NotNull PipeSpriteWoodClarifier blockedTex; + + private SpriteInformation inSprite; + private SpriteInformation sideSprite; + private SpriteInformation restrictiveSprite; + private SpriteInformation blockedSprite; + + public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, @NotNull PipeSpriteWoodClarifier sideTex, + @Nullable PipeSpriteWoodClarifier restrictiveTex, + @NotNull PipeSpriteWoodClarifier blockedTex, String variant) { + super(new ModelResourceLocation(loc, variant)); + this.inTex = inTex; + this.sideTex = sideTex; + this.restrictiveTex = restrictiveTex; + this.blockedTex = blockedTex; + } + + public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, @NotNull PipeSpriteWoodClarifier sideTex, + boolean restrictive, String variant) { + this(inTex, sideTex, restrictive ? wood -> GTCEu.id("blocks/pipe/pipe_restrictive") : null, + wood -> GTCEu.id("blocks/pipe/pipe_blocked"), variant); + } + + public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, boolean restrictive, String variant) { + this(inTex, wood -> wood ? GTCEu.id("block/pipe/pipe_side_wood") : GTCEu.id("block/pipe/pipe_side"), restrictive, variant); + } + + @Override + public SpriteInformation getParticleSprite(@Nullable Material material) { + return sideSprite; + } + + @Override + public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { + return getParticleSprite(null).sprite(); + } + + public @NotNull TextureAtlasSprite getParticleTexture(Material material) { + return sideSprite.sprite(); + } + + @Override + protected @NotNull WoodCacheKey toKey(@NotNull ModelData state) { + return WoodCacheKey.of(state.get(THICKNESS_PROPERTY), state.get(MATERIAL_PROPERTY)); + } + + @Override + protected StructureQuadCache constructForKey(WoodCacheKey key) { + if (inSprite == null) { + inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex.getTexture(key.isWood())), 0); + } + if (sideSprite == null) { + sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex.getTexture(key.isWood())), 0); + } + if (restrictiveSprite == null && restrictiveTex != null) { + restrictiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(restrictiveTex.getTexture(key.isWood())), -1); + } + if (blockedSprite == null) { + blockedSprite = new SpriteInformation(ModelFactory.getBlockSprite(blockedTex.getTexture(key.isWood())), -1); + } + + if (restrictiveTex != null) { + return RestrictiveSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, + sideSprite, blockedSprite, + restrictiveSprite); + } else { + return BlockableSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, + sideSprite, blockedSprite); + } + } + + @Override + protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity) { + PipeBlock block = PipeBlock.getBlockFromItem(stack); + if (block == null) return null; + Material mater = null; + boolean wood = block instanceof PipeMaterialBlock mat && (mater = mat.material) != null && + mater.hasProperty(PropertyKey.WOOD); + return new PipeItemModel<>(this, new WoodCacheKey(block.getStructure().getRenderThickness(), wood), + new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : + PipeBlockEntity.DEFAULT_COLOR)); + } + + public static void registerModels(BiConsumer registry) { + for (PipeModel model : INSTANCES) { + registry.accept(model.getLoc(), model); + } + for (PipeModel model : RESTRICTIVE_INSTANCES) { + registry.accept(model.getLoc(), model); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java new file mode 100644 index 0000000000..3ce564406e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java @@ -0,0 +1,77 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cache; + +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; + +import java.util.EnumMap; +import java.util.List; + +public class BlockableSQC extends StructureQuadCache { + + protected final EnumMap blockedCoords = new EnumMap<>(Direction.class); + + protected final SpriteInformation blockedTex; + + protected BlockableSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteInformation sideTex, + SpriteInformation blockedTex) { + super(helper, endTex, sideTex); + this.blockedTex = blockedTex; + if (helper.getLayerCount() < 2) throw new IllegalStateException( + "Cannot create a BlockableSQC without 2 or more layers present on the helper!"); + } + + public static @NotNull BlockableSQC create(PipeQuadHelper helper, SpriteInformation endTex, + SpriteInformation sideTex, SpriteInformation blockedTex) { + helper.initialize((facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_1)); + BlockableSQC cache = new BlockableSQC(helper, endTex, sideTex, blockedTex); + cache.buildPrototype(); + return cache; + } + + @Override + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); + buildBlocked(quads); + return quads; + } + + protected void buildBlocked(List list) { + helper.setTargetSprite(blockedTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.addAll(helper.visitTube(facing, 1)); + blockedCoords.put(facing, new SubListAddress(start, list.size())); + } + } + + @Override + public void addToList(List list, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, + byte coverMask) { + List quads = cache.getQuads(data); + for (Direction facing : GTUtil.DIRECTIONS) { + if (GTUtil.evalMask(facing, connectionMask)) { + list.addAll(tubeCoords.get(facing).getSublist(quads)); + if (!GTUtil.evalMask(facing, coverMask)) { + if (GTUtil.evalMask(facing, closedMask)) { + list.addAll(capperClosedCoords.get(facing).getSublist(quads)); + } else { + list.addAll(capperCoords.get(facing).getSublist(quads)); + } + } + if (GTUtil.evalMask(facing, blockedMask)) { + list.addAll(blockedCoords.get(facing).getSublist(quads)); + } + } else { + list.addAll(coreCoords.get(facing).getSublist(quads)); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java new file mode 100644 index 0000000000..1e8b4ac3b0 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java @@ -0,0 +1,82 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.cache; + +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; + +import java.util.EnumMap; +import java.util.List; + +public class RestrictiveSQC extends BlockableSQC { + + protected final EnumMap restrictiveCoords = new EnumMap<>(Direction.class); + + private final SpriteInformation restrictiveTex; + + protected RestrictiveSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteInformation sideTex, + SpriteInformation blockedTex, SpriteInformation restrictiveTex) { + super(helper, endTex, sideTex, blockedTex); + this.restrictiveTex = restrictiveTex; + if (helper.getLayerCount() < 3) throw new IllegalStateException( + "Cannot create a RestrictiveSQC without 3 or more layers present on the helper!"); + } + + public static @NotNull RestrictiveSQC create(PipeQuadHelper helper, SpriteInformation endTex, + SpriteInformation sideTex, + SpriteInformation blockedTex, SpriteInformation restrictiveTex) { + helper.initialize( + (facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_2), + (facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_1)); + RestrictiveSQC sqc = new RestrictiveSQC(helper, endTex, sideTex, blockedTex, restrictiveTex); + sqc.buildPrototype(); + return sqc; + } + + @Override + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); + buildRestrictive(quads); + return quads; + } + + protected void buildRestrictive(List list) { + helper.setTargetSprite(restrictiveTex); + for (Direction facing : GTUtil.DIRECTIONS) { + int start = list.size(); + list.addAll(helper.visitTube(facing, 2)); + restrictiveCoords.put(facing, new SubListAddress(start, list.size())); + } + } + + @Override + public void addToList(List list, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, + byte coverMask) { + List quads = cache.getQuads(data); + for (Direction facing : GTUtil.DIRECTIONS) { + if (GTUtil.evalMask(facing, connectionMask)) { + list.addAll(tubeCoords.get(facing).getSublist(quads)); + list.addAll(restrictiveCoords.get(facing).getSublist(quads)); + if (!GTUtil.evalMask(facing, coverMask)) { + if (GTUtil.evalMask(facing, closedMask)) { + list.addAll(capperClosedCoords.get(facing).getSublist(quads)); + } else { + list.addAll(capperCoords.get(facing).getSublist(quads)); + } + } + if (GTUtil.evalMask(facing, blockedMask)) { + list.addAll(blockedCoords.get(facing).getSublist(quads)); + } + } else { + list.addAll(coreCoords.get(facing).getSublist(quads)); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/PipeSpriteWoodClarifier.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/PipeSpriteWoodClarifier.java new file mode 100644 index 0000000000..3c1c14133c --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/PipeSpriteWoodClarifier.java @@ -0,0 +1,12 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +@OnlyIn(Dist.CLIENT) +@FunctionalInterface +public interface PipeSpriteWoodClarifier { + + ResourceLocation getTexture(boolean isWoodVariant); +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java new file mode 100644 index 0000000000..ea5ff3d9dc --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java @@ -0,0 +1,53 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +public class WoodCacheKey extends CacheKey { + + private final boolean wood; + + public WoodCacheKey(float thickness, boolean wood) { + super(thickness); + this.wood = wood; + } + + public static WoodCacheKey of(@Nullable Float thickness, @Nullable Boolean wood) { + float thick = thickness == null ? 0.5f : thickness; + boolean wd = wood != null && wood; + return new WoodCacheKey(thick, wd); + } + + public static WoodCacheKey of(@Nullable Float thickness, @Nullable Material material) { + float thick = thickness == null ? 0.5f : thickness; + boolean wood = material != null && material.hasProperty(PropertyKey.WOOD); + return new WoodCacheKey(thick, wood); + } + + public boolean isWood() { + return wood; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (WoodCacheKey) obj; + return Float.floatToIntBits(thickness) == Float.floatToIntBits(thickness) && + this.wood == that.wood; + } + + @Override + protected int computeHash() { + return Objects.hash(thickness, wood); + } + + @Override + public @NotNull String getSerializedName() { + return super.getSerializedName() + wood; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java index f08d13c97f..73bb668fe5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.common.block; -import com.gregtechceu.gtceu.api.block.PipeBlock; import com.gregtechceu.gtceu.api.blockentity.MetaMachineBlockEntity; import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; @@ -24,6 +23,7 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; @@ -40,7 +40,7 @@ public class DuctPipeBlock extends PipeBlock { - - public FluidPipeBlock(Properties properties, FluidPipeType fluidPipeType, Material material) { - super(properties, fluidPipeType, material); - } - - @Override - protected FluidPipeProperties createProperties(FluidPipeType fluidPipeType, Material material) { - return fluidPipeType.modifyProperties(material.getProperty(PropertyKey.FLUID_PIPE)); - } - - @Override - protected FluidPipeProperties createMaterialData() { - return material.getProperty(PropertyKey.FLUID_PIPE); - } - - @Override - public LevelFluidPipeNet getWorldPipeNet(ServerLevel level) { - return LevelFluidPipeNet.getOrCreate(level); - } - - @Override - public BlockEntityType> getBlockEntityType() { - return GTBlockEntities.FLUID_PIPE.get(); - } - - @Override - public boolean canPipesConnect(IPipeNode selfTile, Direction side, - IPipeNode sideTile) { - return selfTile instanceof FluidPipeBlockEntity && sideTile instanceof FluidPipeBlockEntity; - } - - @Override - public boolean canPipeConnectToBlock(IPipeNode selfTile, Direction side, - @Nullable BlockEntity tile) { - return tile != null && tile.getCapability(ForgeCapabilities.FLUID_HANDLER, side.getOpposite()).isPresent(); - } - - @Override - protected PipeModel createPipeModel() { - return pipeType.createPipeModel(material); - } - - @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, - TooltipFlag flag) { - super.appendHoverText(stack, level, tooltip, flag); - FluidPipeProperties properties = createProperties(defaultBlockState(), stack); - - tooltip.add(Component.translatable("gtceu.universal.tooltip.fluid_transfer_rate", properties.getThroughput())); - tooltip.add(Component.translatable("gtceu.fluid_pipe.max_temperature", properties.getMaxFluidTemperature())); - - if (properties.getChannels() > 1) { - tooltip.add(Component.translatable("gtceu.fluid_pipe.channels", properties.getChannels())); - } - - if (!GTUtil.isShiftDown()) { - tooltip.add(Component.translatable("gtceu.tooltip.fluid_pipe_hold_shift")); - return; - } - - if (properties.isGasProof()) - tooltip.add(Component.translatable("gtceu.fluid_pipe.gas_proof")); - else - tooltip.add(Component.translatable("gtceu.fluid_pipe.not_gas_proof")); - - if (properties.isAcidProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.acid_proof")); - if (properties.isCryoProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.cryo_proof")); - if (properties.isPlasmaProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.plasma_proof")); - } - - @Override - public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { - // dont apply damage if there is a frame box - var pipeNode = getPipeTile(level, pos); - if (pipeNode.getFrameMaterial() != null) { - BlockState frameState = GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, pipeNode.getFrameMaterial()) - .getDefaultState(); - frameState.getBlock().entityInside(frameState, level, pos, entity); - return; - } - if (level.isClientSide) return; - if (level.getBlockEntity(pos) == null) return; - FluidPipeBlockEntity pipe = (FluidPipeBlockEntity) level.getBlockEntity(pos); - - if (pipe.getOffsetTimer() % 10 == 0) { - if (entity instanceof LivingEntity livingEntity) { - if (pipe.getFluidTanks().length > 1) { - // apply temperature damage for the hottest and coldest pipe (multi fluid pipes) - int maxTemperature = Integer.MIN_VALUE; - int minTemperature = Integer.MAX_VALUE; - for (var tank : pipe.getFluidTanks()) { - FluidStack stack = tank.getFluid(); - net.minecraftforge.fluids.FluidStack forgeStack = FluidHelperImpl.toFluidStack(stack); - if (tank.getFluid() != null && tank.getFluid().getAmount() > 0) { - maxTemperature = Math.max(maxTemperature, - stack.getFluid().getFluidType().getTemperature(forgeStack)); - minTemperature = Math.min(minTemperature, - stack.getFluid().getFluidType().getTemperature(forgeStack)); - } - } - if (maxTemperature != Integer.MIN_VALUE) { - EntityDamageUtil.applyTemperatureDamage(livingEntity, maxTemperature, 1.0F, 20); - } - if (minTemperature != Integer.MAX_VALUE) { - EntityDamageUtil.applyTemperatureDamage(livingEntity, minTemperature, 1.0F, 20); - } - } else { - var tank = pipe.getFluidTanks()[0]; - if (tank.getFluid() != null && tank.getFluid().getAmount() > 0) { - // Apply temperature damage for the pipe (single fluid pipes) - FluidStack stack = tank.getFluid(); - net.minecraftforge.fluids.FluidStack forgeStack = FluidHelperImpl.toFluidStack(stack); - EntityDamageUtil.applyTemperatureDamage(livingEntity, - stack.getFluid().getFluidType().getTemperature(forgeStack), 1.0F, 20); - } - } - } - } - super.entityInside(state, level, pos, entity); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/ItemPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/ItemPipeBlock.java deleted file mode 100644 index c7affc0a67..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/block/ItemPipeBlock.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.gregtechceu.gtceu.common.block; - -import com.gregtechceu.gtceu.api.block.MaterialPipeBlock; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.client.model.PipeModel; -import com.gregtechceu.gtceu.common.blockentity.ItemPipeBlockEntity; -import com.gregtechceu.gtceu.common.data.GTBlockEntities; -import com.gregtechceu.gtceu.common.pipelike.item.ItemPipeType; -import com.gregtechceu.gtceu.common.pipelike.item.LevelItemPipeNet; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.Direction; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraftforge.common.capabilities.ForgeCapabilities; - -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -import javax.annotation.ParametersAreNonnullByDefault; - -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public class ItemPipeBlock extends MaterialPipeBlock { - - public ItemPipeBlock(Properties properties, ItemPipeType itemPipeType, Material material) { - super(properties, itemPipeType, material); - } - - @Override - protected ItemPipeProperties createProperties(ItemPipeType itemPipeType, Material material) { - return itemPipeType.modifyProperties(material.getProperty(PropertyKey.ITEM_PIPE)); - } - - @Override - protected ItemPipeProperties createMaterialData() { - return material.getProperty(PropertyKey.ITEM_PIPE); - } - - @Override - protected PipeModel createPipeModel() { - return pipeType.createPipeModel(material); - } - - @Override - public LevelItemPipeNet getWorldPipeNet(ServerLevel level) { - return LevelItemPipeNet.getOrCreate(level); - } - - @Override - public BlockEntityType> getBlockEntityType() { - return GTBlockEntities.ITEM_PIPE.get(); - } - - @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, - TooltipFlag flag) { - super.appendHoverText(stack, level, tooltip, flag); - ItemPipeProperties properties = createProperties(defaultBlockState(), stack); - - if (properties.getTransferRate() % 1 != 0) { - tooltip.add(Component.translatable("gtceu.universal.tooltip.item_transfer_rate", - (int) ((properties.getTransferRate() * 64) + 0.5))); - } else { - tooltip.add(Component.translatable("gtceu.universal.tooltip.item_transfer_rate_stacks", - (int) properties.getTransferRate())); - } - - tooltip.add(Component.translatable("gtceu.item_pipe.priority", properties.getPriority())); - } - - @Override - public boolean canPipesConnect(IPipeNode selfTile, Direction side, - IPipeNode sideTile) { - return selfTile instanceof ItemPipeBlockEntity && sideTile instanceof ItemPipeBlockEntity; - } - - @Override - public boolean canPipeConnectToBlock(IPipeNode selfTile, Direction side, - @Nullable BlockEntity tile) { - return tile != null && - tile.getCapability(ForgeCapabilities.ITEM_HANDLER, side.getOpposite()).isPresent(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/LaserPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/LaserPipeBlock.java deleted file mode 100644 index 7819738747..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/block/LaserPipeBlock.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.gregtechceu.gtceu.common.block; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.block.PipeBlock; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.client.model.PipeModel; -import com.gregtechceu.gtceu.client.renderer.block.PipeBlockRenderer; -import com.gregtechceu.gtceu.common.blockentity.LaserPipeBlockEntity; -import com.gregtechceu.gtceu.common.data.GTBlockEntities; -import com.gregtechceu.gtceu.common.pipelike.laser.LaserPipeProperties; -import com.gregtechceu.gtceu.common.pipelike.laser.LaserPipeType; -import com.gregtechceu.gtceu.common.pipelike.laser.LevelLaserPipeNet; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.client.color.block.BlockColor; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.item.ItemStack; -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.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.Nullable; - -import javax.annotation.ParametersAreNonnullByDefault; - -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public class LaserPipeBlock extends PipeBlock { - - public final PipeBlockRenderer renderer; - public final PipeModel model; - private final LaserPipeProperties properties; - - public LaserPipeBlock(Properties properties, LaserPipeType type) { - super(properties, type); - this.properties = LaserPipeProperties.INSTANCE; - this.model = new PipeModel(LaserPipeType.NORMAL.getThickness(), () -> GTCEu.id("block/pipe/pipe_laser_side"), - () -> GTCEu.id("block/pipe/pipe_laser_in"), null, null); - this.renderer = new PipeBlockRenderer(this.model); - } - - @OnlyIn(Dist.CLIENT) - public static BlockColor tintedColor() { - return (blockState, level, blockPos, index) -> { - if (blockPos != null && level != null && - level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { - if (pipe.getFrameMaterial() != null) { - if (index == 3) { - return pipe.getFrameMaterial().getMaterialRGB(); - } else if (index == 4) { - return pipe.getFrameMaterial().getMaterialSecondaryRGB(); - } - } - if (pipe.isPainted()) { - return pipe.getRealColor(); - } - } - return -1; - }; - } - - @Override - public LevelLaserPipeNet getWorldPipeNet(ServerLevel world) { - return LevelLaserPipeNet.getOrCreate(world); - } - - @Override - public BlockEntityType> getBlockEntityType() { - return GTBlockEntities.LASER_PIPE.get(); - } - - @Override - public LaserPipeProperties createRawData(BlockState pState, @Nullable ItemStack pStack) { - return LaserPipeProperties.INSTANCE; - } - - @Override - public LaserPipeProperties createProperties(IPipeNode pipeTile) { - LaserPipeType pipeType = pipeTile.getPipeType(); - if (pipeType == null) return getFallbackType(); - return this.pipeType.modifyProperties(properties); - } - - @Override - public LaserPipeProperties getFallbackType() { - return LaserPipeProperties.INSTANCE; - } - - @Override - public @Nullable PipeBlockRenderer getRenderer(BlockState state) { - return renderer; - } - - @Override - protected PipeModel getPipeModel() { - return model; - } - - @Override - public boolean canPipesConnect(IPipeNode selfTile, Direction side, - IPipeNode sideTile) { - return selfTile instanceof LaserPipeBlockEntity && sideTile instanceof LaserPipeBlockEntity; - } - - @Override - public boolean canPipeConnectToBlock(IPipeNode selfTile, Direction side, - @Nullable BlockEntity tile) { - return tile != null && tile.getCapability(GTCapability.CAPABILITY_LASER, side.getOpposite()).isPresent(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/FluidPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/FluidPipeBlockEntity.java deleted file mode 100644 index 731c00a2df..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/FluidPipeBlockEntity.java +++ /dev/null @@ -1,572 +0,0 @@ -package com.gregtechceu.gtceu.common.blockentity; - -import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidPipeProperties; -import com.gregtechceu.gtceu.api.fluids.FluidConstants; -import com.gregtechceu.gtceu.api.fluids.FluidState; -import com.gregtechceu.gtceu.api.fluids.GTFluid; -import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; -import com.gregtechceu.gtceu.api.machine.TickableSubscription; -import com.gregtechceu.gtceu.api.machine.feature.IDataInfoProvider; -import com.gregtechceu.gtceu.common.cover.PumpCover; -import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; -import com.gregtechceu.gtceu.common.item.PortableScannerBehavior; -import com.gregtechceu.gtceu.common.pipelike.fluidpipe.FluidPipeType; -import com.gregtechceu.gtceu.common.pipelike.fluidpipe.PipeTankList; -import com.gregtechceu.gtceu.utils.EntityDamageUtil; -import com.gregtechceu.gtceu.utils.FormattingUtil; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.misc.FluidStorage; -import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; -import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; -import com.lowdragmc.lowdraglib.side.fluid.forge.FluidHelperImpl; -import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; - -import net.minecraft.ChatFormatting; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; -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.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.phys.AABB; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.capability.IFluidHandler; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; - -public class FluidPipeBlockEntity extends PipeBlockEntity - implements IDataInfoProvider { - - public static final int FREQUENCY = 5; - - public byte lastReceivedFrom = 0, oldLastReceivedFrom = 0; - private PipeTankList pipeTankList; - private final EnumMap tankLists = new EnumMap<>(Direction.class); - private FluidStorage[] fluidTanks; - private long timer = 0L; - private final int offset = GTValues.RNG.nextInt(20); - - private TickableSubscription updateSubs; - - public FluidPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - } - - public static void onBlockEntityRegister(BlockEntityType fluidPipeBlockEntityBlockEntityType) {} - - public long getOffsetTimer() { - return timer + offset; - } - - @Override - public void onLoad() { - super.onLoad(); - if (updateSubs == null) { - updateSubs = this.subscribeServerTick(this::update); - } - } - - @Override - public void onChunkUnloaded() { - super.onChunkUnloaded(); - if (updateSubs != null) { - this.unsubscribe(updateSubs); - updateSubs = null; - } - } - - @Override - public boolean canAttachTo(Direction side) { - if (level != null) { - if (level.getBlockEntity(getBlockPos().relative(side)) instanceof FluidPipeBlockEntity) { - return false; - } - return FluidTransferHelper.getFluidTransfer(level, getBlockPos().relative(side), side.getOpposite()) != - null; - } - return false; - } - - @NotNull - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - if (facing != null && isConnected(facing)) { - PipeTankList tankList = getTankList(facing); - if (tankList == null) - return LazyOptional.empty(); - return ForgeCapabilities.FLUID_HANDLER.orEmpty(capability, - LazyOptional.of(() -> FluidTransferHelperImpl.toFluidHandler(tankList))); - } - } else if (capability == GTCapability.CAPABILITY_COVERABLE) { - return GTCapability.CAPABILITY_COVERABLE.orEmpty(capability, LazyOptional.of(this::getCoverContainer)); - } else if (capability == GTCapability.CAPABILITY_TOOLABLE) { - return GTCapability.CAPABILITY_TOOLABLE.orEmpty(capability, LazyOptional.of(() -> this)); - } - return super.getCapability(capability, facing); - } - - public long getCapacityPerTank() { - return getNodeData().getThroughput() * 20; - } - - public void update() { - timer++; - if (!level.isClientSide && getOffsetTimer() % FREQUENCY == 0) { - lastReceivedFrom &= 63; - if (lastReceivedFrom == 63) { - lastReceivedFrom = 0; - } - - boolean shouldDistribute = (oldLastReceivedFrom == lastReceivedFrom); - int tanks = getNodeData().getChannels(); - for (int i = 0, j = GTValues.RNG.nextInt(tanks); i < tanks; i++) { - int index = (i + j) % tanks; - FluidStorage tank = getFluidTanks()[index]; - FluidStack fluid = tank.getFluid(); - if (fluid.isEmpty() || fluid.getFluid() == Fluids.EMPTY) - continue; - if (fluid.getAmount() <= 0) { - tank.setFluid(FluidStack.empty()); - continue; - } - - if (shouldDistribute) { - distributeFluid(index, tank, fluid); - lastReceivedFrom = 0; - } - } - oldLastReceivedFrom = lastReceivedFrom; - } - } - - private void distributeFluid(int channel, FluidStorage tank, FluidStack fluid) { - // Tank, From, Amount to receive - List tanks = new ArrayList<>(); - long amount = fluid.getAmount(); - - FluidStack maxFluid = fluid.copy(); - double availableCapacity = 0; - - for (byte i = 0, j = (byte) GTValues.RNG.nextInt(6); i < 6; i++) { - // Get a list of tanks accepting fluids, and what side they're on - byte side = (byte) ((i + j) % 6); - Direction facing = GTUtil.DIRECTIONS[side]; - - if (!isConnected(facing) || (lastReceivedFrom & (1 << side)) != 0) { - continue; - } - - BlockEntity neighbor = getNeighbor(facing); - if (neighbor == null) continue; - IFluidHandler handler = neighbor.getCapability(ForgeCapabilities.FLUID_HANDLER, facing.getOpposite()) - .resolve().orElse(null); - IFluidTransfer fluidHandler = handler == null ? null : FluidTransferHelperImpl.toFluidTransfer(handler); - if (fluidHandler == null) continue; - - IFluidTransfer pipeTank = tank; - CoverBehavior cover = getCoverContainer().getCoverAtSide(facing); - - // pipeTank should only be determined by the cover attached to the actual pipe - if (cover != null) { - pipeTank = cover.getFluidTransferCap(pipeTank); - // Shutter covers return null capability when active, so check here to prevent NPE - if (pipeTank == null || checkForPumpCover(cover)) continue; - } else { - ICoverable coverable = neighbor.getCapability(GTCapability.CAPABILITY_COVERABLE, facing.getOpposite()) - .resolve().orElse(null); - if (coverable != null) { - cover = coverable.getCoverAtSide(facing.getOpposite()); - if (checkForPumpCover(cover)) continue; - } - } - - FluidStack drainable = pipeTank.drain(maxFluid, true); - if (drainable.isEmpty() || drainable.getAmount() <= 0) { - continue; - } - - long filled = Math.min(fluidHandler.fill(maxFluid, true), drainable.getAmount()); - - if (filled > 0) { - tanks.add(new FluidTransaction(fluidHandler, pipeTank, filled)); - availableCapacity += filled; - } - maxFluid.setAmount(amount); // Because some mods do actually modify input fluid stack - } - - if (availableCapacity <= 0) - return; - - // How much of this fluid is available for distribution? - final double maxAmount = Math.min(getCapacityPerTank() / 2, fluid.getAmount()); - - // Now distribute - for (FluidTransaction transaction : tanks) { - if (availableCapacity > maxAmount) { - transaction.amount = Mth.floor(transaction.amount * maxAmount / availableCapacity); // Distribute fluids - // based on - // percentage - // available space - // at destination - } - if (transaction.amount == 0) { - if (tank.getFluidAmount() <= 0) break; // If there is no more stored fluid, stop transferring to prevent - // dupes - transaction.amount = 1; // If the percent is not enough to give at least 1L, try to give 1L - } else if (transaction.amount < 0) { - continue; - } - - FluidStack toInsert = fluid.copy(); - if (toInsert.isEmpty() || toInsert.getFluid() == Fluids.EMPTY) continue; - toInsert.setAmount(transaction.amount); - - long inserted = transaction.target.fill(toInsert, false); - if (inserted > 0) { - transaction.pipeTank.drain(inserted, false); - } - } - } - - private boolean checkForPumpCover(@Nullable CoverBehavior cover) { - if (cover instanceof PumpCover coverPump) { - long pipeThroughput = getNodeData().getThroughput() * 20; - if (coverPump.getCurrentMilliBucketsPerTick() > pipeThroughput) { - coverPump.setTransferRate(pipeThroughput); - } - return coverPump.getManualIOMode() == ManualIOMode.DISABLED; - } - return false; - } - - public void checkAndDestroy(@NotNull FluidStack stack) { - Fluid fluid = stack.getFluid(); - FluidPipeProperties prop = getNodeData(); - - net.minecraftforge.fluids.FluidStack forgeStack = FluidHelperImpl.toFluidStack(stack); - boolean burning = prop.getMaxFluidTemperature() < fluid.getFluidType().getTemperature(forgeStack); - boolean leaking = !prop.isGasProof() && fluid.getFluidType().getDensity(forgeStack) < 0; - boolean shattering = !prop.isCryoProof() && - fluid.getFluidType().getTemperature() < FluidConstants.CRYOGENIC_FLUID_THRESHOLD; - boolean corroding = false; - boolean melting = false; - - if (fluid instanceof GTFluid attributedFluid) { - FluidState state = attributedFluid.getState(); - if (!prop.canContain(state)) { - leaking = state == FluidState.GAS; - melting = state == FluidState.PLASMA; - } - - // carrying plasmas which are too hot when plasma proof does not burn pipes - if (burning && state == FluidState.PLASMA && prop.canContain(FluidState.PLASMA)) { - burning = false; - } - - for (FluidAttribute attribute : attributedFluid.getAttributes()) { - if (!prop.canContain(attribute)) { - // corrodes if the pipe can't handle the attribute, even if it's not an acid - corroding = true; - } - } - } - - if (burning || leaking || corroding || shattering || melting) { - destroyPipe(stack, burning, leaking, corroding, shattering, melting); - } - } - - public void destroyPipe(FluidStack stack, boolean isBurning, boolean isLeaking, boolean isCorroding, - boolean isShattering, boolean isMelting) { - // prevent the sound from spamming when filled from anything not a pipe - if (getOffsetTimer() % 10 == 0) { - level.playSound(null, this.getPipePos(), SoundEvents.LAVA_EXTINGUISH, SoundSource.BLOCKS, 1.0F, 1.0F); - } - - if (isLeaking) { - FluidPipeBlockEntity.spawnParticles(level, worldPosition, Direction.UP, ParticleTypes.SMOKE, - 7 + GTValues.RNG.nextInt(2)); - - // voids 10% - stack.setAmount(Math.max(0, stack.getAmount() * 9 / 10)); - - // apply heat damage in area surrounding the pipe - if (getOffsetTimer() % 20 == 0) { - List entities = getPipeLevel().getEntitiesOfClass(LivingEntity.class, - new AABB(getPipePos()).inflate(2)); - for (LivingEntity entityLivingBase : entities) { - EntityDamageUtil.applyTemperatureDamage(entityLivingBase, - stack.getFluid().getFluidType().getTemperature(FluidHelperImpl.toFluidStack(stack)), - 2.0F, 10); - } - } - - // chance to do a small explosion - if (GTValues.RNG.nextInt(isBurning ? 3 : 7) == 0) { - this.doExplosion(1.0f + GTValues.RNG.nextFloat()); - } - } - - if (isCorroding) { - FluidPipeBlockEntity.spawnParticles(getPipeLevel(), getPipePos(), Direction.UP, ParticleTypes.CRIT, - 3 + GTValues.RNG.nextInt(2)); - - // voids 25% - stack.setAmount(Math.max(0, stack.getAmount() * 3 / 4)); - - // apply chemical damage in area surrounding the pipe - if (getOffsetTimer() % 20 == 0) { - List entities = getPipeLevel().getEntitiesOfClass(LivingEntity.class, - new AABB(getPipePos()).inflate(1)); - for (LivingEntity entityLivingBase : entities) { - EntityDamageUtil.applyChemicalDamage(entityLivingBase, 2); - } - } - - // 1/10 chance to void everything and destroy the pipe - if (GTValues.RNG.nextInt(10) == 0) { - stack.setAmount(0); - level.removeBlock(getPipePos(), false); - } - } - - if (isBurning || isMelting) { - FluidPipeBlockEntity.spawnParticles(level, getBlockPos(), Direction.UP, ParticleTypes.FLAME, - (isMelting ? 7 : 3) + GTValues.RNG.nextInt(2)); - - // voids 75% - stack.setAmount(Math.max(0, stack.getAmount() / 4)); - - // 1/4 chance to burn everything around it - if (GTValues.RNG.nextInt(4) == 0) { - FluidPipeBlockEntity.setNeighboursToFire(level, getBlockPos()); - } - - // apply heat damage in area surrounding the pipe - if (isMelting && getOffsetTimer() % 20 == 0) { - List entities = getPipeLevel().getEntitiesOfClass(LivingEntity.class, - new AABB(getPipePos()).inflate(2)); - for (LivingEntity entityLivingBase : entities) { - EntityDamageUtil.applyTemperatureDamage(entityLivingBase, - stack.getFluid().getFluidType().getTemperature(FluidHelperImpl.toFluidStack(stack)), - 2.0F, 10); - } - } - - // 1/10 chance to void everything and burn the pipe - if (GTValues.RNG.nextInt(10) == 0) { - stack.setAmount(0); - level.setBlockAndUpdate(getBlockPos(), Blocks.FIRE.defaultBlockState()); - } - } - - if (isShattering) { - FluidPipeBlockEntity.spawnParticles(level, getBlockPos(), Direction.UP, ParticleTypes.CLOUD, - 3 + GTValues.RNG.nextInt(2)); - - // voids 75% - stack.setAmount(Math.max(0, stack.getAmount() / 4)); - - // apply frost damage in area surrounding the pipe - if (getOffsetTimer() % 20 == 0) { - List entities = getPipeLevel().getEntitiesOfClass(LivingEntity.class, - new AABB(getPipePos()).inflate(2)); - for (LivingEntity entityLivingBase : entities) { - EntityDamageUtil.applyTemperatureDamage(entityLivingBase, - stack.getFluid().getFluidType().getTemperature(FluidHelperImpl.toFluidStack(stack)), - 2.0F, 10); - } - } - - // 1/10 chance to void everything and freeze the pipe - if (GTValues.RNG.nextInt(10) == 0) { - stack.setAmount(0); - level.removeBlock(getBlockPos(), false); - } - } - } - - public void receivedFrom(Direction facing) { - if (facing != null) { - lastReceivedFrom |= (1 << facing.ordinal()); - } - } - - public FluidStack getContainedFluid(int channel) { - if (channel < 0 || channel >= getFluidTanks().length) return null; - return getFluidTanks()[channel].getFluid(); - } - - private void createTanksList() { - fluidTanks = new FluidStorage[getNodeData().getChannels()]; - for (int i = 0; i < getNodeData().getChannels(); i++) { - fluidTanks[i] = new FluidStorage(getCapacityPerTank()); - } - pipeTankList = new PipeTankList(this, null, fluidTanks); - for (Direction facing : GTUtil.DIRECTIONS) { - tankLists.put(facing, new PipeTankList(this, facing, fluidTanks)); - } - } - - public PipeTankList getTankList() { - if (pipeTankList == null || fluidTanks == null) { - createTanksList(); - } - return pipeTankList; - } - - public PipeTankList getTankList(Direction facing) { - if (tankLists.isEmpty() || fluidTanks == null) { - createTanksList(); - } - return tankLists.getOrDefault(facing, pipeTankList); - } - - public FluidStorage[] getFluidTanks() { - if (pipeTankList == null || fluidTanks == null) { - createTanksList(); - } - return fluidTanks; - } - - public FluidStack[] getContainedFluids() { - FluidStack[] fluids = new FluidStack[getFluidTanks().length]; - for (int i = 0; i < fluids.length; i++) { - fluids[i] = fluidTanks[i].getFluid(); - } - return fluids; - } - - @Override - public void saveCustomPersistedData(CompoundTag tag, boolean forDrop) { - super.saveCustomPersistedData(tag, forDrop); - ListTag list = new ListTag(); - for (int i = 0; i < getFluidTanks().length; i++) { - FluidStack stack1 = getContainedFluid(i); - CompoundTag fluidTag = new CompoundTag(); - if (stack1 == null || stack1.getAmount() <= 0) - fluidTag.putBoolean("isNull", true); - else - stack1.saveToTag(fluidTag); - list.add(fluidTag); - } - tag.put("Fluids", list); - } - - @Override - public void loadCustomPersistedData(CompoundTag nbt) { - super.loadCustomPersistedData(nbt); - ListTag list = nbt.getList("Fluids", Tag.TAG_COMPOUND); - createTanksList(); - for (int i = 0; i < list.size(); i++) { - CompoundTag tag = list.getCompound(i); - if (!tag.getBoolean("isNull")) { - fluidTanks[i].setFluid(FluidStack.loadFromTag(tag)); - } - } - } - - public static void spawnParticles(Level worldIn, BlockPos pos, Direction direction, ParticleOptions particleType, - int particleCount) { - if (worldIn instanceof ServerLevel serverLevel) { - serverLevel.sendParticles(particleType, - pos.getX() + 0.5, - pos.getY() + 0.5, - pos.getZ() + 0.5, - particleCount, - direction.getStepX() * 0.2 + GTValues.RNG.nextDouble() * 0.1, - direction.getStepY() * 0.2 + GTValues.RNG.nextDouble() * 0.1, - direction.getStepZ() * 0.2 + GTValues.RNG.nextDouble() * 0.1, - 0.1); - } - } - - public static void setNeighboursToFire(Level world, BlockPos selfPos) { - for (Direction side : GTUtil.DIRECTIONS) { - if (!GTValues.RNG.nextBoolean()) continue; - BlockPos blockPos = selfPos.relative(side); - BlockState blockState = world.getBlockState(blockPos); - if (world.isEmptyBlock(blockPos) || - blockState.isFlammable(world, blockPos, side.getOpposite())) { - world.setBlockAndUpdate(blockPos, Blocks.FIRE.defaultBlockState()); - } - } - } - - @Override - public @NotNull List getDataInfo(PortableScannerBehavior.DisplayMode mode) { - List list = new ArrayList<>(); - - if (mode == PortableScannerBehavior.DisplayMode.SHOW_ALL || - mode == PortableScannerBehavior.DisplayMode.SHOW_MACHINE_INFO) { - FluidStack[] fluids = getContainedFluids(); - if (fluids != null) { - boolean allTanksEmpty = true; - for (int i = 0; i < fluids.length; i++) { - if (fluids[i] != null) { - if (fluids[i].getFluid() == null || fluids[i].isEmpty()) { - continue; - } - - allTanksEmpty = false; - list.add(Component.translatable("behavior.portable_scanner.tank", i, - Component.translatable(FormattingUtil.formatNumbers(fluids[i].getAmount())) - .withStyle(ChatFormatting.GREEN), - Component.translatable(FormattingUtil.formatNumbers(getCapacityPerTank())) - .withStyle(ChatFormatting.YELLOW), - fluids[i].getDisplayName().copy() - .withStyle(ChatFormatting.GOLD))); - } - } - - if (allTanksEmpty) { - list.add(Component.translatable("behavior.portable_scanner.tanks_empty")); - } - } - } - - return list; - } - - private static class FluidTransaction { - - public final IFluidTransfer target; - public final IFluidTransfer pipeTank; - public long amount; - - private FluidTransaction(IFluidTransfer target, IFluidTransfer pipeTank, long amount) { - this.target = target; - this.pipeTank = pipeTank; - this.amount = amount; - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java deleted file mode 100644 index c9a6863903..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/ItemPipeBlockEntity.java +++ /dev/null @@ -1,193 +0,0 @@ -package com.gregtechceu.gtceu.common.blockentity; - -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.common.block.ItemPipeBlock; -import com.gregtechceu.gtceu.common.pipelike.item.ItemNetHandler; -import com.gregtechceu.gtceu.common.pipelike.item.ItemPipeNet; -import com.gregtechceu.gtceu.common.pipelike.item.ItemPipeType; -import com.gregtechceu.gtceu.utils.FacingPos; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.misc.ItemStackTransfer; -import com.lowdragmc.lowdraglib.side.item.IItemTransfer; -import com.lowdragmc.lowdraglib.side.item.ItemTransferHelper; -import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; - -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.lang.ref.WeakReference; -import java.util.EnumMap; - -public class ItemPipeBlockEntity extends PipeBlockEntity { - - protected WeakReference currentItemPipeNet = new WeakReference<>(null); - - @Getter - private final EnumMap handlers = new EnumMap<>(Direction.class); - @Getter - private final Object2IntMap transferred = new Object2IntOpenHashMap<>(); - @Getter - private ItemNetHandler defaultHandler; - // the ItemNetHandler can only be created on the server so we have a empty placeholder for the client - private final IItemTransfer clientCapability = new ItemStackTransfer(0); - - private int transferredItems = 0; - private long timer = 0; - - public ItemPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - } - - public static ItemPipeBlockEntity create(BlockEntityType type, BlockPos pos, BlockState blockState) { - return new ItemPipeBlockEntity(type, pos, blockState); - } - - public long getLevelTime() { - return hasLevel() ? getLevel().getGameTime() : 0L; - } - - public static void onBlockEntityRegister(BlockEntityType itemPipeBlockEntityBlockEntityType) {} - - @Override - public @NotNull LazyOptional getCapability(@NotNull Capability cap, @Nullable Direction side) { - if (cap == ForgeCapabilities.ITEM_HANDLER) { - Level world = getLevel(); - if (world.isClientSide()) - return LazyOptional.empty(); - - if (side != null && isConnected(side)) { - ensureHandlersInitialized(); - checkNetwork(); - return ForgeCapabilities.ITEM_HANDLER.orEmpty(cap, - LazyOptional.of(() -> ItemTransferHelperImpl.toItemHandler(getHandler(side, true)))); - } - } else if (cap == GTCapability.CAPABILITY_COVERABLE) { - return GTCapability.CAPABILITY_COVERABLE.orEmpty(cap, LazyOptional.of(this::getCoverContainer)); - } else if (cap == GTCapability.CAPABILITY_TOOLABLE) { - return GTCapability.CAPABILITY_TOOLABLE.orEmpty(cap, LazyOptional.of(() -> this)); - } - return super.getCapability(cap, side); - } - - private void ensureHandlersInitialized() { - if (getHandlers().isEmpty()) - initHandlers(); - } - - public void initHandlers() { - ItemPipeNet net = getItemPipeNet(); - if (net == null) { - return; - } - for (Direction facing : GTUtil.DIRECTIONS) { - handlers.put(facing, new ItemNetHandler(net, this, facing)); - } - defaultHandler = new ItemNetHandler(net, this, null); - } - - public void checkNetwork() { - if (defaultHandler != null) { - ItemPipeNet current = getItemPipeNet(); - if (defaultHandler.getNet() != current) { - defaultHandler.updateNetwork(current); - for (ItemNetHandler handler : handlers.values()) { - handler.updateNetwork(current); - } - } - } - } - - @Override - public boolean canAttachTo(Direction side) { - if (level == null) return false; - if (level.getBlockEntity(getBlockPos().relative(side)) instanceof ItemPipeBlockEntity) { - return false; - } - return ItemTransferHelper.getItemTransfer(level, getBlockPos().relative(side), side.getOpposite()) != null; - } - - @Nullable - public ItemPipeNet getItemPipeNet() { - if (level instanceof ServerLevel serverLevel && - getBlockState().getBlock() instanceof ItemPipeBlock itemPipeBlock) { - ItemPipeNet currentItemPipeNet = this.currentItemPipeNet.get(); - if (currentItemPipeNet != null && currentItemPipeNet.isValid() && - currentItemPipeNet.containsNode(getBlockPos())) - return currentItemPipeNet; // return current net if it is still valid - currentItemPipeNet = itemPipeBlock.getWorldPipeNet(serverLevel).getNetFromPos(getBlockPos()); - if (currentItemPipeNet != null) { - this.currentItemPipeNet = new WeakReference<>(currentItemPipeNet); - } - } - return this.currentItemPipeNet.get(); - } - - public void resetTransferred() { - transferred.clear(); - } - - /** - * every time the transferred variable is accessed this method should be called - * if 20 ticks passed since the last access it will reset it - * this method is equal to - * - * @code { - * if (++time % 20 == 0) { - * this.transferredItems = 0; - * } - * } - *

- * if it was in a ticking BlockEntity - */ - private void updateTransferredState() { - long currentTime = getLevelTime(); - long dif = currentTime - this.timer; - if (dif >= 20 || dif < 0) { - this.transferredItems = 0; - this.timer = currentTime; - } - } - - public void addTransferredItems(int amount) { - updateTransferredState(); - this.transferredItems += amount; - } - - public int getTransferredItems() { - updateTransferredState(); - return this.transferredItems; - } - - @Override - public void onChunkUnloaded() { - super.onChunkUnloaded(); - this.handlers.clear(); - } - - public IItemTransfer getHandler(@Nullable Direction side, boolean useCoverCapability) { - ensureHandlersInitialized(); - - ItemNetHandler handler = getHandlers().getOrDefault(side, getDefaultHandler()); - if (!useCoverCapability || side == null) return handler; - - CoverBehavior cover = getCoverContainer().getCoverAtSide(side); - return cover != null ? cover.getItemTransferCap(handler) : handler; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java deleted file mode 100644 index 3101fbdd37..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/LaserPipeBlockEntity.java +++ /dev/null @@ -1,234 +0,0 @@ -package com.gregtechceu.gtceu.common.blockentity; - -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.ILaserContainer; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.item.tool.GTToolType; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.common.pipelike.laser.*; -import com.gregtechceu.gtceu.utils.GTUtil; -import com.gregtechceu.gtceu.utils.TaskHandler; - -import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; -import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -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.Capability; -import net.minecraftforge.common.util.LazyOptional; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.lang.ref.WeakReference; -import java.util.EnumMap; - -public class LaserPipeBlockEntity extends PipeBlockEntity { - - public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(LaserPipeBlockEntity.class, - PipeBlockEntity.MANAGED_FIELD_HOLDER); - - @Getter - protected final EnumMap handlers = new EnumMap<>(Direction.class); - // the LaserNetHandler can only be created on the server, so we have an empty placeholder for the client - public final ILaserContainer clientCapability = new DefaultLaserContainer(); - private WeakReference currentPipeNet = new WeakReference<>(null); - @Getter - protected LaserNetHandler defaultHandler; - - private int ticksActive = 0; - private int activeDuration = 0; - @Getter - @Persisted - @DescSynced - private boolean active = false; - - protected LaserPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - } - - public static LaserPipeBlockEntity create(BlockEntityType type, BlockPos pos, BlockState blockState) { - return new LaserPipeBlockEntity(type, pos, blockState); - } - - public static void onBlockEntityRegister(BlockEntityType cableBlockEntityBlockEntityType) {} - - @Override - public @NotNull LazyOptional getCapability(@NotNull Capability cap, @Nullable Direction side) { - if (cap == GTCapability.CAPABILITY_LASER) { - if (getLevel().isClientSide()) - return GTCapability.CAPABILITY_LASER.orEmpty(cap, LazyOptional.of(() -> clientCapability)); - - if (handlers.isEmpty()) { - initHandlers(); - } - checkNetwork(); - return GTCapability.CAPABILITY_LASER.orEmpty(cap, - LazyOptional.of(() -> handlers.getOrDefault(side, defaultHandler))); - } else if (cap == GTCapability.CAPABILITY_COVERABLE) { - return GTCapability.CAPABILITY_COVERABLE.orEmpty(cap, LazyOptional.of(this::getCoverContainer)); - } else if (cap == GTCapability.CAPABILITY_TOOLABLE) { - return GTCapability.CAPABILITY_TOOLABLE.orEmpty(cap, LazyOptional.of(() -> this)); - } - return super.getCapability(cap, side); - } - - @Override - public boolean canHaveBlockedFaces() { - return false; - } - - public void initHandlers() { - LaserPipeNet net = getLaserPipeNet(); - if (net == null) return; - for (Direction facing : GTUtil.DIRECTIONS) { - handlers.put(facing, new LaserNetHandler(net, this, facing)); - } - defaultHandler = new LaserNetHandler(net, this, null); - } - - public void checkNetwork() { - if (defaultHandler != null) { - LaserPipeNet current = getLaserPipeNet(); - if (defaultHandler.getNet() != current) { - defaultHandler.updateNetwork(current); - for (LaserNetHandler handler : handlers.values()) { - handler.updateNetwork(current); - } - } - } - } - - public LaserPipeNet getLaserPipeNet() { - if (level == null || level.isClientSide) { - return null; - } - LaserPipeNet currentPipeNet = this.currentPipeNet.get(); - if (currentPipeNet != null && currentPipeNet.isValid() && currentPipeNet.containsNode(getPipePos())) { - return currentPipeNet; - } - LevelLaserPipeNet worldNet = (LevelLaserPipeNet) getPipeBlock().getWorldPipeNet((ServerLevel) getPipeLevel()); - currentPipeNet = worldNet.getNetFromPos(getPipePos()); - if (currentPipeNet != null) { - this.currentPipeNet = new WeakReference<>(currentPipeNet); - } - return currentPipeNet; - } - - /** - * @param active if the pipe should become active - * @param duration how long the pipe should be active for - */ - public void setActive(boolean active, int duration) { - if (this.active != active) { - this.active = active; - notifyBlockUpdate(); - setChanged(); - if (active && duration != this.activeDuration) { - TaskHandler.enqueueServerTask((ServerLevel) getLevel(), this::queueDisconnect, 0); - } - } - - this.activeDuration = duration; - if (duration > 0 && active) { - this.ticksActive = 0; - } - } - - public boolean queueDisconnect() { - if (++this.ticksActive % activeDuration == 0) { - this.ticksActive = 0; - setActive(false, -1); - return false; - } - return true; - } - - @Override - public boolean canAttachTo(Direction side) { - if (level != null) { - if (level.getBlockEntity(getBlockPos().relative(side)) instanceof LaserPipeBlockEntity) { - return false; - } - return GTCapabilityHelper.getLaser(level, getBlockPos().relative(side), side.getOpposite()) != null; - } - return false; - } - - @Override - public void setConnection(Direction side, boolean connected, boolean fromNeighbor) { - if (!getLevel().isClientSide && connected && !fromNeighbor) { - int connections = getConnections(); - // block connection if any side other than the requested side and its opposite side are already connected. - connections &= ~(1 << side.ordinal()); - connections &= ~(1 << side.getOpposite().ordinal()); - if (connections != 0) return; - - // check the same for the targeted pipe - BlockEntity tile = getLevel().getBlockEntity(getBlockPos().relative(side)); - if (tile instanceof IPipeNode pipeTile && - pipeTile.getPipeType().getClass() == this.getPipeType().getClass()) { - connections = pipeTile.getConnections(); - connections &= ~(1 << side.ordinal()); - connections &= ~(1 << side.getOpposite().ordinal()); - if (connections != 0) return; - } - } - super.setConnection(side, connected, fromNeighbor); - } - - @Override - public GTToolType getPipeTuneTool() { - return GTToolType.WIRE_CUTTER; - } - - @Override - public ManagedFieldHolder getFieldHolder() { - return MANAGED_FIELD_HOLDER; - } - - private static class DefaultLaserContainer implements ILaserContainer { - - @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { - return 0; - } - - @Override - public boolean inputsEnergy(Direction side) { - return false; - } - - @Override - public long changeEnergy(long differenceAmount) { - return 0; - } - - @Override - public long getEnergyStored() { - return 0; - } - - @Override - public long getEnergyCapacity() { - return 0; - } - - @Override - public long getInputAmperage() { - return 0; - } - - @Override - public long getInputVoltage() { - return 0; - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java index 0e2d6093fa..020282596e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java @@ -10,45 +10,63 @@ import com.gregtechceu.gtceu.api.cover.filter.FilterHandler; import com.gregtechceu.gtceu.api.cover.filter.FilterHandlers; import com.gregtechceu.gtceu.api.cover.filter.ItemFilter; -import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; -import com.gregtechceu.gtceu.api.gui.widget.IntInputWidget; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; +import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; import com.gregtechceu.gtceu.api.machine.ConditionalSubscriptionHandler; import com.gregtechceu.gtceu.api.transfer.item.ItemTransferDelegate; -import com.gregtechceu.gtceu.common.blockentity.ItemPipeBlockEntity; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.DistributionMode; +import com.gregtechceu.gtceu.common.cover.data.ItemFilterMode; import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; +import com.gregtechceu.gtceu.common.cover.filter.MergabilityInfo; +import com.gregtechceu.gtceu.common.pipelike.net.item.*; import com.gregtechceu.gtceu.utils.ItemStackHashStrategy; -import com.lowdragmc.lowdraglib.gui.texture.GuiTextureGroup; -import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; -import com.lowdragmc.lowdraglib.gui.widget.SwitchWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; -import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.side.item.ItemTransferHelper; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; -import com.lowdragmc.lowdraglib.utils.LocalizationUtils; +import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import mezz.jei.api.gui.drawable.IDrawable; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; -import lombok.AllArgsConstructor; import lombok.Getter; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.common.util.LazyOptional; +import net.minecraftforge.items.IItemHandler; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.IntUnaryOperator; import javax.annotation.ParametersAreNonnullByDefault; @@ -59,7 +77,8 @@ */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault -public class ConveyorCover extends CoverBehavior implements IUICover, IControllable { +public class ConveyorCover extends CoverBehavior implements IUICover, IControllable, + TransferControlProvider, IItemTransferController { public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(ConveyorCover.class, CoverBehavior.MANAGED_FIELD_HOLDER); @@ -82,7 +101,6 @@ public class ConveyorCover extends CoverBehavior implements IUICover, IControlla @Getter protected ManualIOMode manualIOMode = ManualIOMode.DISABLED; @Persisted - @Getter protected boolean isWorkingEnabled = true; protected int itemsLeftToTransferLastSecond; private Widget ioModeSwitch; @@ -198,294 +216,483 @@ public void setWorkingEnabled(boolean isWorkingAllowed) { protected void update() { long timer = coverHolder.getOffsetTimer(); - if (timer % 5 == 0) { - if (itemsLeftToTransferLastSecond > 0) { - var adjacentItemTransfer = getAdjacentItemTransfer(); - var myItemHandler = getOwnItemTransfer(); - - if (adjacentItemTransfer != null && myItemHandler != null) { - int totalTransferred = switch (io) { - case IN -> doTransferItems(adjacentItemTransfer, myItemHandler, itemsLeftToTransferLastSecond); - case OUT -> doTransferItems(myItemHandler, adjacentItemTransfer, itemsLeftToTransferLastSecond); - default -> 0; - }; - this.itemsLeftToTransferLastSecond -= totalTransferred; + if (timer % 5 == 0 && isWorkingEnabled && getItemsLeftToTransfer() > 0) { + Direction side = attachedSide; + BlockEntity tileEntity = coverHolder.getNeighbor(side); + IItemHandler itemHandler = tileEntity == null ? null : + tileEntity.getCapability(ForgeCapabilities.ITEM_HANDLER, side.getOpposite()).resolve().orElse(null); + IItemHandler myItemHandler = coverHolder.getCapability(ForgeCapabilities.ITEM_HANDLER, side).resolve().orElse(null); + if (itemHandler != null && myItemHandler != null) { + if (io == IO.OUT) { + performTransferOnUpdate(myItemHandler, itemHandler); + } else { + performTransferOnUpdate(itemHandler, myItemHandler); } } - if (timer % 20 == 0) { - this.itemsLeftToTransferLastSecond = transferRate; - } - subscriptionHandler.updateSubscription(); + } + if (timer % 20 == 0) { + refreshBuffer(transferRate); } } - protected int doTransferItems(IItemTransfer sourceInventory, IItemTransfer targetInventory, int maxTransferAmount) { - return moveInventoryItems(sourceInventory, targetInventory, maxTransferAmount); + protected int getItemsLeftToTransfer() { + return itemsLeftToTransferLastSecond; } - protected int moveInventoryItems(IItemTransfer sourceInventory, IItemTransfer targetInventory, - int maxTransferAmount) { - ItemFilter filter = filterHandler.getFilter(); - int itemsLeftToTransfer = maxTransferAmount; - - for (int srcIndex = 0; srcIndex < sourceInventory.getSlots(); srcIndex++) { - ItemStack sourceStack = sourceInventory.extractItem(srcIndex, itemsLeftToTransfer, true); - if (sourceStack.isEmpty()) { - continue; - } - - if (!filter.test(sourceStack)) { - continue; - } + protected void reportItemsTransfer(int transferred) { + this.itemsLeftToTransferLastSecond -= transferred; + } - ItemStack remainder = ItemTransferHelper.insertItem(targetInventory, sourceStack, true); - int amountToInsert = sourceStack.getCount() - remainder.getCount(); + protected void refreshBuffer(int transferRate) { + this.itemsLeftToTransferLastSecond = transferRate; + } - if (amountToInsert > 0) { - sourceStack = sourceInventory.extractItem(srcIndex, amountToInsert, false); - if (!sourceStack.isEmpty()) { - ItemTransferHelper.insertItem(targetInventory, sourceStack, false); - itemsLeftToTransfer -= sourceStack.getCount(); + protected void performTransferOnUpdate(@NotNull IItemHandler sourceHandler, @NotNull IItemHandler destHandler) { + reportItemsTransfer(performTransfer(sourceHandler, destHandler, false, i -> 0, + i -> getItemsLeftToTransfer(), null)); + } - if (itemsLeftToTransfer == 0) { - break; - } + /** + * Performs transfer + * + * @param sourceHandler the handler to pull from + * @param destHandler the handler to push to + * @param byFilterSlot whether to perform the transfer by filter slot. + * @param minTransfer the minimum allowed transfer amount, when given a filter slot. If no filter exists or not + * transferring by slot, a filter slot of -1 will be passed in. + * @param maxTransfer the maximum allowed transfer amount, when given a filter slot. If no filter exists or not + * transferring by slot, a filter slot of -1 will be passed in. + * @param transferReport where transfer is reported; a is the filter slot, b is the amount of transfer. + * Each filter slot will report its transfer before the next slot is calculated. + * @return how much was transferred in total. + */ + protected int performTransfer(@NotNull IItemHandler sourceHandler, @NotNull IItemHandler destHandler, + boolean byFilterSlot, @NotNull IntUnaryOperator minTransfer, + @NotNull IntUnaryOperator maxTransfer, @Nullable BiConsumer transferReport) { + ItemFilter filter = filterHandler.getFilter(); + byFilterSlot = byFilterSlot && filter != null; // can't be by filter slot if there is no filter + Int2IntArrayMap extractableByFilterSlot = new Int2IntArrayMap(); + Int2ObjectArrayMap> filterSlotToMergability = new Int2ObjectArrayMap<>(); + for (int i = 0; i < sourceHandler.getSlots(); i++) { + ItemStack stack = sourceHandler.extractItem(i, Integer.MAX_VALUE, true); + int extracted = stack.getCount(); + if (extracted == 0) continue; + MatchResult match = null; + if (filter == null || (match = filter.match(stack)).isMatched()) { + int filterSlot = -1; + if (byFilterSlot) { + filterSlot = match.getFilterIndex(); } + extractableByFilterSlot.merge(filterSlot, extracted, Integer::sum); + final int handlerSlot = i; + filterSlotToMergability.compute(filterSlot, (k, v) -> { + if (v == null) v = new MergabilityInfo<>(); + v.add(handlerSlot, new ItemTestObject(stack), extracted); + return v; + }); } } - return maxTransferAmount - itemsLeftToTransfer; - } - - protected static boolean moveInventoryItemsExact(IItemTransfer sourceInventory, IItemTransfer targetInventory, - TypeItemInfo itemInfo) { - // first, compute how much can we extract in reality from the machine, - // because totalCount is based on what getStackInSlot returns, which may differ from what - // extractItem() will return - ItemStack resultStack = itemInfo.itemStack.copy(); - int totalExtractedCount = 0; - int itemsLeftToExtract = itemInfo.totalCount; - - for (int i = 0; i < itemInfo.slots.size(); i++) { - int slotIndex = itemInfo.slots.getInt(i); - ItemStack extractedStack = sourceInventory.extractItem(slotIndex, itemsLeftToExtract, true); - if (!extractedStack.isEmpty() && - ItemStack.isSameItemSameTags(resultStack, extractedStack)) { - totalExtractedCount += extractedStack.getCount(); - itemsLeftToExtract -= extractedStack.getCount(); - } - if (itemsLeftToExtract == 0) { - break; + var iter = extractableByFilterSlot.int2IntEntrySet().fastIterator(); + int totalTransfer = 0; + while (iter.hasNext()) { + var next = iter.next(); + int filterSlot = next.getIntKey(); + int min = minTransfer.applyAsInt(filterSlot); + int max = maxTransfer.applyAsInt(filterSlot); + if (max < min || max <= 0) continue; + int slotTransfer = 0; + if (next.getIntValue() >= min) { + MergabilityInfo mergabilityInfo = filterSlotToMergability.get(filterSlot); + MergabilityInfo.Merge merge = mergabilityInfo.getLargestMerge(); + if (merge.getCount() >= min) { + int transfer = Math.min(merge.getCount(), max); + transfer = insertToHandler(destHandler, merge.getTestObject(), transfer, true); + // since we can't guarantee the insertability of multiple stack types while just simulating, + // if the largest merge is not large enough we have to give up. + if (transfer < min) continue; + int toExtract = transfer; + for (int handlerSlot : merge.getHandlerSlots()) { + toExtract -= sourceHandler.extractItem(handlerSlot, toExtract, false).getCount(); + if (toExtract == 0) break; + } + insertToHandler(destHandler, merge.getTestObject(), transfer - toExtract, false); + int remaining = max - transfer + toExtract; + slotTransfer += transfer; + if (remaining <= 0) continue; + for (MergabilityInfo.Merge otherMerge : mergabilityInfo + .getNonLargestMerges(merge)) { + transfer = Math.min(otherMerge.getCount(), remaining); + transfer = insertToHandler(destHandler, merge.getTestObject(), transfer, true); + toExtract = transfer; + for (int handlerSlot : otherMerge.getHandlerSlots()) { + toExtract -= sourceHandler.extractItem(handlerSlot, toExtract, false).getCount(); + if (toExtract == 0) break; + } + insertToHandler(destHandler, otherMerge.getTestObject(), transfer - toExtract, false); + remaining -= transfer; + slotTransfer += transfer; + if (remaining <= 0) break; + } + } } + if (transferReport != null) transferReport.accept(filterSlot, slotTransfer); + totalTransfer += slotTransfer; } - // if amount of items extracted is not equal to the amount of items we - // wanted to extract, abort item extraction - if (totalExtractedCount != itemInfo.totalCount) { - return false; - } - // adjust size of the result stack accordingly - resultStack.setCount(totalExtractedCount); - - // now, see how much we can insert into destination inventory - // if we can't insert as much as itemInfo requires, and remainder is empty, abort, abort - ItemStack remainder = ItemTransferHelper.insertItem(targetInventory, resultStack, true); - if (!remainder.isEmpty()) { - return false; - } + return totalTransfer; + } - // otherwise, perform real insertion and then remove items from the source inventory - ItemTransferHelper.insertItem(targetInventory, resultStack, false); - - // perform real extraction of the items from the source inventory now - itemsLeftToExtract = itemInfo.totalCount; - for (int i = 0; i < itemInfo.slots.size(); i++) { - int slotIndex = itemInfo.slots.getInt(i); - ItemStack extractedStack = sourceInventory.extractItem(slotIndex, itemsLeftToExtract, false); - if (!extractedStack.isEmpty() && - ItemStack.isSameItemSameTags(resultStack, extractedStack)) { - itemsLeftToExtract -= extractedStack.getCount(); + protected int insertToHandler(@NotNull IItemHandler destHandler, ItemTestObject testObject, int count, + boolean simulate) { + if (!(destHandler instanceof IItemTraverseGuideProvider provider)) { + return simpleInsert(destHandler, testObject, count, simulate); + } + switch (distributionMode) { + case INSERT_FIRST -> { + var guide = provider.getGuide(this::getTD, testObject, count, simulate); + if (guide == null) return 0; + int consumed = (int) TraverseHelpers.traverseFlood(guide.getData(), guide.getPaths(), guide.getFlow()); + guide.reportConsumedFlow(consumed); + return consumed; } - if (itemsLeftToExtract == 0) { - break; + case ROUND_ROBIN_GLOBAL -> { + var guide = provider.getGuide(this::getEQTD, testObject, count, simulate); + if (guide == null) return 0; + int consumed = (int) TraverseHelpers.traverseEqualDistribution(guide.getData(), + guide.getPathsSupplier(), guide.getFlow(), true); + guide.reportConsumedFlow(consumed); + return consumed; + } + case ROUND_ROBIN_PRIO -> { + var guide = provider + .getGuide( + (net, testObject1, simulator, queryTick, sourcePos, inputFacing) -> getRRTD(net, + testObject1, simulator, queryTick, sourcePos, inputFacing, simulate), + testObject, count, simulate); + if (guide == null) return 0; + int consumed = (int) TraverseHelpers.traverseRoundRobin(guide.getData(), guide.getPaths(), + guide.getFlow(), true); + guide.reportConsumedFlow(consumed); + return consumed; } } - return true; + return 0; } - protected int moveInventoryItems(IItemTransfer sourceInventory, IItemTransfer targetInventory, - Map itemInfos, int maxTransferAmount) { - ItemFilter filter = filterHandler.getFilter(); - int itemsLeftToTransfer = maxTransferAmount; + @Contract("_, _, _, _, _, _ -> new") + protected @NotNull ItemTraverseData getTD(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + return new ItemTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } - for (int i = 0; i < sourceInventory.getSlots(); i++) { - ItemStack itemStack = sourceInventory.getStackInSlot(i); - if (itemStack.isEmpty() || !filter.test(itemStack) || !itemInfos.containsKey(itemStack)) { - continue; - } + @Contract("_, _, _, _, _, _ -> new") + protected @NotNull ItemEQTraverseData getEQTD(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + return new ItemEQTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + @Contract("_, _, _, _, _, _, _ -> new") + protected @NotNull ItemRRTraverseData getRRTD(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing, + boolean simulate) { + return new ItemRRTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing, + getRoundRobinCache(simulate)); + } + + protected Object2ObjectLinkedOpenHashMap> getRoundRobinCache(boolean simulate) { + return simulate ? roundRobinCache.clone() : roundRobinCache; + } - GroupItemInfo itemInfo = itemInfos.get(itemStack); + protected int simpleInsert(@NotNull IItemHandler destHandler, ItemTestObject testObject, int count, + boolean simulate) { + int available = count; + for (int i = 0; i < destHandler.getSlots(); i++) { + ItemStack toInsert = testObject.recombine(Math.min(available, destHandler.getSlotLimit(i))); + available -= toInsert.getCount() - destHandler.insertItem(i, toInsert, simulate).getCount(); + if (available == 0) return count; + } + return count - available; + } - ItemStack extractedStack = sourceInventory.extractItem(i, - Math.min(itemInfo.totalCount, itemsLeftToTransfer), true); + @Override + public @Nullable T getControllerForControl(TransferControl control) { + if (control == IItemTransferController.CONTROL) { + return control.cast(this); + } + return null; + } - ItemStack remainderStack = ItemTransferHelper.insertItem(targetInventory, extractedStack, true); - int amountToInsert = extractedStack.getCount() - remainderStack.getCount(); + @Override + public int insertToHandler(@NotNull ItemTestObject testObject, int amount, @NotNull IItemHandler destHandler, + boolean simulate) { + if (getManualImportExportMode() == ManualImportExportMode.DISABLED) return amount; + if (getManualImportExportMode() == ManualImportExportMode.UNFILTERED || + getFilterMode() == ItemFilterMode.FILTER_INSERT) // insert to handler is an extract from us + return IItemTransferController.super.insertToHandler(testObject, amount, destHandler, simulate); + ItemFilterContainer filter = getItemFilter(); + if (filter == null || filter.test(testObject.recombine())) { + return IItemTransferController.super.insertToHandler(testObject, amount, destHandler, simulate); + } else return amount; + } - if (amountToInsert > 0) { - extractedStack = sourceInventory.extractItem(i, amountToInsert, false); + @Override + public int extractFromHandler(@NotNull ItemTestObject testObject, int amount, @NotNull IItemHandler sourceHandler, + boolean simulate) { + if (getManualImportExportMode() == ManualImportExportMode.DISABLED) return 0; + if (getManualImportExportMode() == ManualImportExportMode.UNFILTERED || + getFilterMode() == ItemFilterMode.FILTER_EXTRACT) // extract from handler is an insert to us + return IItemTransferController.super.extractFromHandler(testObject, amount, sourceHandler, simulate); + ItemFilterContainer filter = getItemFilter(); + if (filter == null || filter.test(testObject.recombine())) { + return IItemTransferController.super.extractFromHandler(testObject, amount, sourceHandler, simulate); + } else return 0; + } - if (!extractedStack.isEmpty()) { + protected static class TypeItemInfo { - ItemTransferHelper.insertItem(targetInventory, extractedStack, false); - itemsLeftToTransfer -= extractedStack.getCount(); - itemInfo.totalCount -= extractedStack.getCount(); + public final ItemStack itemStack; + public final int filterSlot; + public final IntList slots; + public int totalCount; - if (itemInfo.totalCount == 0) { - itemInfos.remove(itemStack); - if (itemInfos.isEmpty()) { - break; - } - } - if (itemsLeftToTransfer == 0) { - break; - } - } - } + public TypeItemInfo(ItemStack itemStack, int filterSlot, IntList slots, int totalCount) { + this.itemStack = itemStack; + this.filterSlot = filterSlot; + this.slots = slots; + this.totalCount = totalCount; } - return maxTransferAmount - itemsLeftToTransfer; } @NotNull - protected Map countInventoryItemsByType(@NotNull IItemTransfer inventory) { - ItemFilter filter = filterHandler.getFilter(); + protected Map countInventoryItemsByType(@NotNull IItemHandler inventory) { Map result = new Object2ObjectOpenCustomHashMap<>( ItemStackHashStrategy.comparingAllButCount()); - for (int srcIndex = 0; srcIndex < inventory.getSlots(); srcIndex++) { ItemStack itemStack = inventory.getStackInSlot(srcIndex); - if (itemStack.isEmpty() || !filter.test(itemStack)) { + if (itemStack.isEmpty()) { continue; } - var itemInfo = result.computeIfAbsent(itemStack, s -> new TypeItemInfo(s, new IntArrayList(), 0)); - - itemInfo.totalCount += itemStack.getCount(); - itemInfo.slots.add(srcIndex); + var matchResult = itemFilterContainer.match(itemStack); + if (!matchResult.isMatched()) continue; + + if (!result.containsKey(itemStack)) { + TypeItemInfo itemInfo = new TypeItemInfo(itemStack.copy(), matchResult.getFilterIndex(), + new IntArrayList(), 0); + itemInfo.totalCount += itemStack.getCount(); + itemInfo.slots.add(srcIndex); + result.put(itemStack.copy(), itemInfo); + } else { + TypeItemInfo itemInfo = result.get(itemStack); + itemInfo.totalCount += itemStack.getCount(); + itemInfo.slots.add(srcIndex); + } } - return result; } - @NotNull - protected Map countInventoryItemsByMatchSlot(@NotNull IItemTransfer inventory) { - ItemFilter filter = filterHandler.getFilter(); - Map result = new Object2ObjectOpenCustomHashMap<>( - ItemStackHashStrategy.comparingAllButCount()); + @Override + public boolean canAttach(@NotNull CoverableView coverable, @NotNull Direction side) { + return coverable.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, getAttachedSide()); + } - for (int srcIndex = 0; srcIndex < inventory.getSlots(); srcIndex++) { - ItemStack itemStack = inventory.getStackInSlot(srcIndex); - if (itemStack.isEmpty() || !filter.test(itemStack)) { - continue; - } + @Override + public boolean canInteractWithOutputSide() { + return true; + } - var itemInfo = result.computeIfAbsent(itemStack, s -> new GroupItemInfo(s, 0)); + @Override + public void onRemoval() { + dropInventoryContents(itemFilterContainer); + } - itemInfo.totalCount += itemStack.getCount(); + @Override + public void renderCover(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline, + Cuboid6 plateBox, BlockRenderLayer layer) { + if (conveyorMode == ConveyorMode.EXPORT) { + Textures.CONVEYOR_OVERLAY.renderSided(getAttachedSide(), plateBox, renderState, pipeline, translation); + } else { + Textures.CONVEYOR_OVERLAY_INVERTED.renderSided(getAttachedSide(), plateBox, renderState, pipeline, + translation); } - return result; } - @AllArgsConstructor - protected static class TypeItemInfo { - - public final ItemStack itemStack; - public final IntList slots; - public int totalCount; + @Override + public @NotNull EnumActionResult onScrewdriverClick(@NotNull EntityPlayer playerIn, @NotNull EnumHand hand, + @NotNull RayTraceResult hitResult) { + if (!getCoverableView().getWorld().isRemote) { + openUI((EntityPlayerMP) playerIn); + } + return EnumActionResult.SUCCESS; } - @AllArgsConstructor - protected static class GroupItemInfo { - - public final ItemStack itemStack; - public int totalCount; + @Override + public LazyOptional getCapability(@NotNull Capability capability, LazyOptional defaultValue) { + if (capability == ForgeCapabilities.ITEM_HANDLER) { + if (defaultValue == null) { + return null; + } + IItemHandler delegate = (IItemHandler) defaultValue; + if (itemHandlerWrapper == null || itemHandlerWrapper.delegate != defaultValue) { + this.itemHandlerWrapper = new CoverableItemTransferWrapper(defaultValue); + } + return itemHandlerWrapper; + return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(itemHandlerWrapper); + } + if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) { + return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this); + } + return defaultValue; } - ////////////////////////////////////// - // *********** GUI ***********// - ////////////////////////////////////// @Override - public Widget createUIWidget() { - final var group = new WidgetGroup(0, 0, 176, 137); - group.addWidget(new LabelWidget(10, 5, LocalizationUtils.format(getUITitle(), GTValues.VN[tier]))); - - group.addWidget(new IntInputWidget(10, 20, 156, 20, () -> this.transferRate, this::setTransferRate) - .setMin(1).setMax(maxItemTransferRate)); - - ioModeSwitch = new SwitchWidget(10, 45, 20, 20, - (clickData, value) -> { - setIo(value ? IO.IN : IO.OUT); - ioModeSwitch.setHoverTooltips( - LocalizationUtils.format("cover.conveyor.mode", LocalizationUtils.format(io.tooltip))); - }) - .setTexture( - new GuiTextureGroup(GuiTextures.VANILLA_BUTTON, IO.OUT.icon), - new GuiTextureGroup(GuiTextures.VANILLA_BUTTON, IO.IN.icon)) - .setPressed(io == IO.IN) - .setHoverTooltips( - LocalizationUtils.format("cover.conveyor.mode", LocalizationUtils.format(io.tooltip))); - group.addWidget(ioModeSwitch); - - if (shouldDisplayDistributionMode()) { - group.addWidget(new EnumSelectorWidget<>(146, 67, 20, 20, - DistributionMode.VALUES, distributionMode, this::setDistributionMode)); - } + public boolean usesMui2() { + return true; + } - group.addWidget(new EnumSelectorWidget<>(146, 107, 20, 20, - ManualIOMode.VALUES, manualIOMode, this::setManualIOMode) - .setHoverTooltips("cover.universal.manual_import_export.mode.description")); + @Override + public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncManager) { + var panel = GTGuis.createPanel(this, 176, 192 + 18); - group.addWidget(filterHandler.createFilterSlotUI(125, 108)); - group.addWidget(filterHandler.createFilterConfigUI(10, 72, 156, 60)); + getItemFilterContainer().setMaxTransferSize(getMaxStackSize()); - buildAdditionalUI(group); + return panel.child(CoverWithUI.createTitleRow(getPickItem())) + .child(createUI(panel, guiSyncManager)) + .bindPlayerInventory(); + } - return group; + protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager guiSyncManager) { + var column = new Column().top(24).margin(7, 0) + .widthRel(1f).coverChildrenHeight(); + + EnumSyncValue manualIOmode = new EnumSyncValue<>(ManualImportExportMode.class, + this::getManualImportExportMode, this::setManualImportExportMode); + + EnumSyncValue conveyorMode = new EnumSyncValue<>(ConveyorMode.class, + this::getConveyorMode, this::setConveyorMode); + + IntSyncValue throughput = new IntSyncValue(this::getTransferRate, this::setTransferRate); + throughput.updateCacheFromSource(true); + + StringSyncValue formattedThroughput = new StringSyncValue(throughput::getStringValue, + throughput::setStringValue); + + EnumSyncValue distributionMode = new EnumSyncValue<>(DistributionMode.class, + this::getDistributionMode, this::setDistributionMode); + + guiSyncManager.syncValue("manual_io", manualIOmode); + guiSyncManager.syncValue("conveyor_mode", conveyorMode); + guiSyncManager.syncValue("distribution_mode", distributionMode); + guiSyncManager.syncValue("throughput", throughput); + + if (createThroughputRow()) + column.child(new Row().coverChildrenHeight() + .marginBottom(2).widthRel(1f) + .child(new ButtonWidget<>() + .left(0).width(18) + .onMousePressed(mouseButton -> { + int val = throughput.getValue() - getIncrementValue(MouseData.create(mouseButton)); + throughput.setValue(val, true, true); + Interactable.playButtonClickSound(); + return true; + }) + .onUpdateListener(w -> w.overlay(createAdjustOverlay(false)))) + .child(new TextFieldWidget() + .left(18).right(18) + .setTextColor(Color.WHITE.darker(1)) + .setNumbers(1, maxItemTransferRate) + .value(formattedThroughput) + .background(GTGuiTextures.DISPLAY)) + .child(new ButtonWidget<>() + .right(0).width(18) + .onMousePressed(mouseButton -> { + int val = throughput.getValue() + getIncrementValue(MouseData.create(mouseButton)); + throughput.setValue(val, true, true); + Interactable.playButtonClickSound(); + return true; + }) + .onUpdateListener(w -> w.overlay(createAdjustOverlay(true))))); + + if (createFilterRow()) + column.child(getItemFilterContainer().initUI(mainPanel, guiSyncManager)); + + if (createManualIOModeRow()) + column.child(new EnumRowBuilder<>(ManualImportExportMode.class) + .value(manualIOmode) + .lang("cover.generic.manual_io") + .overlay(new IDrawable[] { + new DynamicDrawable(() -> conveyorMode.getValue().isImport() ? + GTGuiTextures.MANUAL_IO_OVERLAY_OUT[0] : GTGuiTextures.MANUAL_IO_OVERLAY_IN[0]), + new DynamicDrawable(() -> conveyorMode.getValue().isImport() ? + GTGuiTextures.MANUAL_IO_OVERLAY_OUT[1] : GTGuiTextures.MANUAL_IO_OVERLAY_IN[1]), + new DynamicDrawable(() -> conveyorMode.getValue().isImport() ? + GTGuiTextures.MANUAL_IO_OVERLAY_OUT[2] : GTGuiTextures.MANUAL_IO_OVERLAY_IN[2]) + }) + .build()); + + if (createConveyorModeRow()) + column.child(new EnumRowBuilder<>(ConveyorMode.class) + .value(conveyorMode) + .lang("cover.generic.io") + .overlay(GTGuiTextures.CONVEYOR_MODE_OVERLAY) + .build()); + + if (createDistributionModeRow()) + column.child(new EnumRowBuilder<>(DistributionMode.class) + .value(distributionMode) + .overlay(16, GTGuiTextures.DISTRIBUTION_MODE_OVERLAY) + .lang("cover.generic.distribution.name") + .build()); + + return column; } - private boolean shouldDisplayDistributionMode() { - return coverHolder.getLevel().getBlockEntity(coverHolder.getPos()) instanceof ItemPipeBlockEntity || - coverHolder.getLevel() - .getBlockEntity(coverHolder.getPos().relative(attachedSide)) instanceof ItemPipeBlockEntity; + protected boolean createThroughputRow() { + return true; } - @NotNull - protected String getUITitle() { - return "cover.conveyor.title"; + protected boolean createFilterRow() { + return true; } - protected void buildAdditionalUI(WidgetGroup group) { - // Do nothing in the base implementation. This is intended to be overridden by subclasses. + protected boolean createManualIOModeRow() { + return true; } - protected void configureFilter() { - // Do nothing in the base implementation. This is intended to be overridden by subclasses. + protected boolean createConveyorModeRow() { + return true; } - ///////////////////////////////////// - // *** CAPABILITY OVERRIDE ***// - ///////////////////////////////////// + protected boolean createDistributionModeRow() { + return true; + } - private CoverableItemTransferWrapper itemHandlerWrapper; + protected int getMaxStackSize() { + return 1; + }1 - @Nullable @Override - public IItemTransfer getItemTransferCap(@Nullable IItemTransfer defaultValue) { - if (defaultValue == null) { - return null; - } - if (itemHandlerWrapper == null || itemHandlerWrapper.delegate != defaultValue) { - this.itemHandlerWrapper = new CoverableItemTransferWrapper(defaultValue); + public @NotNull CoverRenderer getRenderer() { + if (io == IO.OUT) { + if (renderer == null) renderer = buildRenderer(); + return renderer; + } else { + if (rendererInverted == null) rendererInverted = buildRendererInverted(); + return rendererInverted; } - return itemHandlerWrapper; + } + + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(Textures.CONVEYOR_OVERLAY).build(); + } + + protected CoverRenderer buildRendererInverted() { + return new CoverRendererBuilder(Textures.CONVEYOR_OVERLAY_INVERTED).build(); + } + + @OnlyIn(Dist.CLIENT) + protected @NotNull ResourceLocation getPlateTexture() { + return Textures.VOLTAGE_CASINGS[this.tier].getSpriteOnSide(SimpleSidedCubeRenderer.RenderSide.SIDE); } private class CoverableItemTransferWrapper extends ItemTransferDelegate { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java index a5e4a21d62..c6083c6347 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java @@ -92,6 +92,7 @@ public class PumpCover extends CoverBehavior implements IUICover, IControllable @Persisted @DescSynced + @Getter protected final FilterHandler filterHandler; protected final ConditionalSubscriptionHandler subscriptionHandler; private NumberInputWidget transferRateWidget; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java index f00bbe6e7c..3274eb9402 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java @@ -8,7 +8,6 @@ import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; import com.gregtechceu.gtceu.api.gui.widget.IntInputWidget; import com.gregtechceu.gtceu.common.cover.data.TransferMode; -import com.gregtechceu.gtceu.common.pipelike.item.ItemNetHandler; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java new file mode 100644 index 0000000000..9024aac6e2 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java @@ -0,0 +1,45 @@ +package com.gregtechceu.gtceu.common.cover.filter; + +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public final class MatchResult { + + public static final MatchResult NONE = new MatchResult(false, null, -1); + public static final MatchResult ANY = new MatchResult(true, null, -1); + private final boolean matched; + private final Object matchedObject; + private final int filterIndex; + + private MatchResult(boolean matched, Object matchedObject, int filterIndex) { + this.matched = matched; + this.matchedObject = matchedObject; + this.filterIndex = filterIndex; + } + + public boolean isMatched() { + return matched; + } + + public Object getMatchedObject() { + return matchedObject; + } + + public @NotNull ItemStack getItemStack() { + return matchedObject instanceof ItemStack stack ? stack : ItemStack.EMPTY; + } + + public @Nullable FluidStack getFluidStack() { + return matchedObject instanceof FluidStack stack ? stack : null; + } + + public int getFilterIndex() { + return filterIndex; + } + + public static MatchResult create(boolean matched, Object matchedStack, int filterIndex) { + return new MatchResult(matched, matchedStack, filterIndex); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java new file mode 100644 index 0000000000..39fad01bd0 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java @@ -0,0 +1,60 @@ +package com.gregtechceu.gtceu.common.cover.filter; + +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Comparator; +import java.util.List; + +public final class MergabilityInfo { + + private final Object2ObjectOpenHashMap mergeMap = new Object2ObjectOpenHashMap<>(); + + public void add(int handlerSlot, T testObject, int count) { + mergeMap.compute(testObject, (k, v) -> { + if (v == null) v = new Merge(k); + v.count += count; + v.handlerSlots.add(handlerSlot); + return v; + }); + } + + public Merge getLargestMerge() { + return mergeMap.values().stream().max(Comparator.comparingInt(Merge::getCount)).orElse(null); + } + + public @NotNull List getNonLargestMerges(@Nullable Merge largestMerge) { + List merges = new ObjectArrayList<>(mergeMap.values()); + merges.remove(largestMerge == null ? getLargestMerge() : largestMerge); + return merges; + } + + public final class Merge { + + private final T testObject; + + private int count = 0; + private final IntList handlerSlots = new IntArrayList(); + + public Merge(T testObject) { + this.testObject = testObject; + } + + public int getCount() { + return count; + } + + public T getTestObject() { + return testObject; + } + + public IntList getHandlerSlots() { + return handlerSlots; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index c9b3c77d5a..5b6f2affec 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -29,14 +29,14 @@ public class GTBlockEntities { Stream.concat(Stream.of(GTBlocks.LASER_PIPE), Stream.concat(GTBlocks.ITEM_PIPE_BLOCKS.values().stream(), Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), - GTBlocks.FLUID_PIPE_BLOCKS.values().stream()))))) + GTBlocks.MATERIAL_PIPE_BLOCKS.values().stream()))))) .toArray(NonNullSupplier[]::new)) .register(); public static final BlockEntityEntry FLUID_PIPE = REGISTRATE .blockEntity("fluid_pipe", FluidPipeBlockEntity::new) .onRegister(FluidPipeBlockEntity::onBlockEntityRegister) - .validBlocks(GTBlocks.FLUID_PIPE_BLOCKS.values().toArray(BlockEntry[]::new)) + .validBlocks(GTBlocks.MATERIAL_PIPE_BLOCKS.values().toArray(BlockEntry[]::new)) .register(); public static final BlockEntityEntry ITEM_PIPE = REGISTRATE diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index a17cd3f372..00f57dbad1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -13,6 +13,8 @@ import com.gregtechceu.gtceu.api.data.chemical.material.stack.UnificationEntry; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.data.tag.TagUtil; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem; import com.gregtechceu.gtceu.api.item.*; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.machine.multiblock.IBatteryData; @@ -29,12 +31,11 @@ import com.gregtechceu.gtceu.common.block.explosive.IndustrialTNTBlock; import com.gregtechceu.gtceu.common.block.explosive.PowderbarrelBlock; import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; import com.gregtechceu.gtceu.common.pipelike.duct.DuctPipeType; -import com.gregtechceu.gtceu.common.pipelike.fluidpipe.FluidPipeType; -import com.gregtechceu.gtceu.common.pipelike.fluidpipe.longdistance.LDFluidPipeType; -import com.gregtechceu.gtceu.common.pipelike.item.ItemPipeType; -import com.gregtechceu.gtceu.common.pipelike.item.longdistance.LDItemPipeType; -import com.gregtechceu.gtceu.common.pipelike.laser.LaserPipeType; +import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidPipeType; +import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemPipeType; import com.gregtechceu.gtceu.core.mixins.BlockPropertiesAccessor; import com.gregtechceu.gtceu.data.recipe.CustomTags; import com.gregtechceu.gtceu.utils.FormattingUtil; @@ -119,9 +120,9 @@ public class GTBlocks { .builder(); private static ImmutableTable.Builder> CABLE_BLOCKS_BUILDER = ImmutableTable .builder(); - private static ImmutableTable.Builder> FLUID_PIPE_BLOCKS_BUILDER = ImmutableTable + private static ImmutableTable.Builder> MATERIAL_PIPE_BLOCKS_BUILDER = ImmutableTable .builder(); - private static ImmutableTable.Builder> ITEM_PIPE_BLOCKS_BUILDER = ImmutableTable + private static ImmutableTable.Builder> ITEM_PIPE_BLOCKS_BUILDER = ImmutableTable .builder(); ////////////////////////////////////// @@ -130,8 +131,7 @@ public class GTBlocks { public static Table> MATERIAL_BLOCKS; public static Map> SURFACE_ROCK_BLOCKS; public static Table> CABLE_BLOCKS; - public static Table> FLUID_PIPE_BLOCKS; - public static Table> ITEM_PIPE_BLOCKS; + public static Table> MATERIAL_PIPE_BLOCKS; public static final BlockEntry[] DUCT_PIPES = new BlockEntry[DuctPipeType.VALUES.length]; public static final BlockEntry LASER_PIPE = REGISTRATE .block("normal_laser_pipe", (p) -> new LaserPipeBlock(p, LaserStructure.NORMAL)) @@ -143,7 +143,6 @@ public class GTBlocks { .addLayer(() -> RenderType::cutoutMipped) .item(com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem::new) .model(NonNullBiConsumer.noop()) - .color(() -> LaserPipeBlockItem::tintColor) .build() .register(); public static final BlockEntry OPTICAL_PIPE = REGISTRATE @@ -294,7 +293,7 @@ private static void registerOreIndicator(Material material, GTRegistrate registr // Cable/Wire Blocks private static void generateCableBlocks() { GTCEu.LOGGER.debug("Generating GTCEu Cable/Wire Blocks..."); - CableStructure.registerDefaultStructures(structure -> { + for (CableStructure structure : PipeStructureRegistry.getStructures(CableStructure.class)) { for (MaterialRegistry registry : GTCEuAPI.materialManager.getRegistries()) { GTRegistrate registrate = registry.getRegistrate(); for (Material material : registry.getAllMaterials()) { @@ -303,7 +302,7 @@ private static void generateCableBlocks() { } } } - }); + } CABLE_BLOCKS = CABLE_BLOCKS_BUILDER.build(); GTCEu.LOGGER.debug("Generating GTCEu Cable/Wire Blocks... Complete!"); } @@ -324,10 +323,9 @@ private static void registerCableBlock(Material material, CableStructure insulat .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) - .color(() -> MaterialPipeBlock::tintedColor) - .item(com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem::new) + .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) - .color(() -> MaterialPipeBlockItem::tintColor) + //.color(() -> ::tintColor) .onRegister(compassNodeExist(GTCompassSections.MATERIALS, "wire_and_cable")) .build() .register(); @@ -335,77 +333,31 @@ private static void registerCableBlock(Material material, CableStructure insulat } // Fluid Pipe Blocks - private static void generateFluidPipeBlocks() { - GTCEu.LOGGER.debug("Generating GTCEu Fluid Pipe Blocks..."); - for (var fluidPipeType : FluidPipeType.values()) { + private static void generateMaterialPipeBlocks() { + GTCEu.LOGGER.debug("Generating GTCEu Material Pipe Blocks..."); + for (var structure : PipeStructureRegistry.getStructures(MaterialPipeStructure.class)) { for (MaterialRegistry registry : GTCEuAPI.materialManager.getRegistries()) { GTRegistrate registrate = registry.getRegistrate(); for (Material material : registry.getAllMaterials()) { - if (allowFluidPipeBlock(material, fluidPipeType)) { - registerFluidPipeBlock(material, fluidPipeType, registrate); + if (allowFluidPipeBlock(material, structure)) { + registerFluidPipeBlock(material, structure, registrate); } } } } - FLUID_PIPE_BLOCKS = FLUID_PIPE_BLOCKS_BUILDER.build(); - GTCEu.LOGGER.debug("Generating GTCEu Fluid Pipe Blocks... Complete!"); + MATERIAL_PIPE_BLOCKS = MATERIAL_PIPE_BLOCKS_BUILDER.build(); + GTCEu.LOGGER.debug("Generating GTCEu Material Pipe Blocks... Complete!"); } - private static boolean allowFluidPipeBlock(Material material, FluidPipeType fluidPipeType) { - return material.hasProperty(PropertyKey.FLUID_PIPE) && !fluidPipeType.tagPrefix.isIgnored(material); + private static boolean allowFluidPipeBlock(Material material, MaterialPipeStructure fluidPipeType) { + return material.hasProperty(PropertyKey.FLUID_PIPE) && !fluidPipeType.prefix().isIgnored(material); } - private static void registerFluidPipeBlock(Material material, FluidPipeType fluidPipeType, + private static void registerFluidPipeBlock(Material material, MaterialPipeStructure fluidPipeType, GTRegistrate registrate) { var entry = registrate - .block("%s_%s_fluid_pipe".formatted(material.getName(), fluidPipeType.name), - p -> new FluidPipeBlock(p, fluidPipeType, material)) - .initialProperties(() -> Blocks.IRON_BLOCK) - .properties(p -> { - if (doMetalPipe(material)) { - p.sound(GTSoundTypes.METAL_PIPE); - } - return p.dynamicShape().noOcclusion().noLootTable().forceSolidOn(); - }) - .transform(unificationBlock(fluidPipeType.tagPrefix, material)) - .blockstate(NonNullBiConsumer.noop()) - .setData(ProviderType.LANG, NonNullBiConsumer.noop()) - .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) - .addLayer(() -> RenderType::cutoutMipped) - .color(() -> MaterialPipeBlock::tintedColor) - .item(MaterialPipeBlockItem::new) - .model(NonNullBiConsumer.noop()) - .color(() -> MaterialPipeBlockItem::tintColor) - .build() - .register(); - FLUID_PIPE_BLOCKS_BUILDER.put(fluidPipeType.tagPrefix, material, entry); - } - - // Item Pipe Blocks - private static void generateItemPipeBlocks() { - GTCEu.LOGGER.debug("Generating GTCEu Item Pipe Blocks..."); - for (var itemPipeType : ItemPipeType.values()) { - for (MaterialRegistry registry : GTCEuAPI.materialManager.getRegistries()) { - GTRegistrate registrate = registry.getRegistrate(); - for (Material material : registry.getAllMaterials()) { - if (allowItemPipeBlock(material, itemPipeType)) { - registerItemPipeBlock(material, itemPipeType, registrate); - } - } - } - } - ITEM_PIPE_BLOCKS = ITEM_PIPE_BLOCKS_BUILDER.build(); - GTCEu.LOGGER.debug("Generating GTCEu Item Pipe Blocks... Complete!"); - } - - private static boolean allowItemPipeBlock(Material material, ItemPipeType itemPipeType) { - return material.hasProperty(PropertyKey.ITEM_PIPE) && !itemPipeType.getTagPrefix().isIgnored(material); - } - - private static void registerItemPipeBlock(Material material, ItemPipeType itemPipeType, GTRegistrate registrate) { - var entry = registrate - .block("%s_%s_item_pipe".formatted(material.getName(), itemPipeType.name), - p -> new ItemPipeBlock(p, itemPipeType, material)) + .block("%s_%s_pipe".formatted(material.getName(), fluidPipeType.name()), + p -> new MaterialPipeBlock(p, fluidPipeType, material)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> { if (doMetalPipe(material)) { @@ -413,18 +365,16 @@ private static void registerItemPipeBlock(Material material, ItemPipeType itemPi } return p.dynamicShape().noOcclusion().noLootTable().forceSolidOn(); }) - .transform(unificationBlock(itemPipeType.getTagPrefix(), material)) + .transform(unificationBlock(fluidPipeType.prefix(), material)) .blockstate(NonNullBiConsumer.noop()) .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) - .color(() -> MaterialPipeBlock::tintedColor) - .item(MaterialPipeBlockItem::new) + .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) - .color(() -> MaterialPipeBlockItem::tintColor) .build() .register(); - ITEM_PIPE_BLOCKS_BUILDER.put(itemPipeType.getTagPrefix(), material, entry); + MATERIAL_PIPE_BLOCKS_BUILDER.put(fluidPipeType.prefix(), material, entry); } // Optical Pipe Blocks @@ -1678,16 +1628,14 @@ public static void init() { // Procedural Pipes/Wires REGISTRATE.creativeModeTab(() -> GTCreativeModeTabs.MATERIAL_PIPE); generateCableBlocks(); // Cable & Wire Blocks - generateFluidPipeBlocks(); // Fluid Pipe Blocks - generateItemPipeBlocks(); // Item Pipe Blocks + generateMaterialPipeBlocks(); // Material Pipe Blocks generateDuctPipeBlocks(); // Duct Pipe Blocks // Remove Builder Tables MATERIAL_BLOCKS_BUILDER = null; SURFACE_ROCK_BLOCKS_BUILDER = null; CABLE_BLOCKS_BUILDER = null; - FLUID_PIPE_BLOCKS_BUILDER = null; - ITEM_PIPE_BLOCKS_BUILDER = null; + MATERIAL_PIPE_BLOCKS_BUILDER = null; // GCyM GCyMBlocks.init(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java index f930262e36..a9007ba55e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java @@ -56,8 +56,8 @@ import com.gregtechceu.gtceu.common.machine.steam.SteamSolarBoiler; import com.gregtechceu.gtceu.common.machine.steam.SteamSolidBoilerMachine; import com.gregtechceu.gtceu.common.machine.storage.*; -import com.gregtechceu.gtceu.common.pipelike.fluidpipe.longdistance.LDFluidEndpointMachine; -import com.gregtechceu.gtceu.common.pipelike.item.longdistance.LDItemEndpointMachine; +import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidEndpointMachine; +import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemEndpointMachine; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.data.lang.LangHandler; import com.gregtechceu.gtceu.integration.kjs.GTRegistryInfo; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java index 1119778619..f98673ff01 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java @@ -196,14 +196,14 @@ public static void init() { toolHeadWireCutter .addSecondaryMaterial(new MaterialStack(Steel, ring.materialAmount() + screw.materialAmount() * 2)); - pipeTinyFluid.setIgnored(Wood); - pipeHugeFluid.setIgnored(Wood); - pipeQuadrupleFluid.setIgnored(Wood); - pipeNonupleFluid.setIgnored(Wood); - pipeTinyFluid.setIgnored(TreatedWood); - pipeHugeFluid.setIgnored(TreatedWood); - pipeQuadrupleFluid.setIgnored(TreatedWood); - pipeNonupleFluid.setIgnored(TreatedWood); + pipeTiny.setIgnored(Wood); + pipeHuge.setIgnored(Wood); + pipeQuadruple.setIgnored(Wood); + pipeNonuple.setIgnored(Wood); + pipeTiny.setIgnored(TreatedWood); + pipeHuge.setIgnored(TreatedWood); + pipeQuadruple.setIgnored(TreatedWood); + pipeNonuple.setIgnored(TreatedWood); pipeSmallRestrictive.addSecondaryMaterial(new MaterialStack(Iron, ring.materialAmount() * 2)); pipeNormalRestrictive.addSecondaryMaterial(new MaterialStack(Iron, ring.materialAmount() * 2)); diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index 3d0b3c16a4..4681dad360 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -19,7 +19,6 @@ import com.gregtechceu.gtceu.api.machine.trait.RecipeLogic; import com.gregtechceu.gtceu.api.recipe.GTRecipe; import com.gregtechceu.gtceu.api.recipe.RecipeHelper; -import com.gregtechceu.gtceu.common.blockentity.FluidPipeBlockEntity; import com.gregtechceu.gtceu.common.capability.EnvironmentalHazardSavedData; import com.gregtechceu.gtceu.common.capability.LocalizedHazardSavedData; import com.gregtechceu.gtceu.common.data.GTSoundEntries; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java new file mode 100644 index 0000000000..79e4e0ac93 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -0,0 +1,14 @@ +package com.gregtechceu.gtceu.common.pipelike.block.pipe; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; + +public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, IFreezable { + + public MaterialPipeBlock(BlockBehaviour.Properties properties, MaterialPipeStructure structure, Material material) { + super(properties, structure, material); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java new file mode 100644 index 0000000000..507a5399a1 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -0,0 +1,121 @@ +package com.gregtechceu.gtceu.common.pipelike.block.pipe; + +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeChanneledStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModel; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +public record MaterialPipeStructure(String name, int material, int channelCount, boolean restrictive, TagPrefix prefix, + float renderThickness, PipeModel model) + implements IPipeMaterialStructure, IPipeChanneledStructure { + + public static final MaterialPipeStructure TINY = new MaterialPipeStructure("pipe_tiny", 1, 1, false, + TagPrefix.pipeTiny, 0.25f, + PipeModel.INSTANCES[0]); + public static final MaterialPipeStructure SMALL = new MaterialPipeStructure("pipe_small", 2, 1, false, + TagPrefix.pipeSmall, 0.375f, + PipeModel.INSTANCES[1]); + public static final MaterialPipeStructure NORMAL = new MaterialPipeStructure("pipe_normal", 6, 1, false, + TagPrefix.pipeNormal, 0.5f, + PipeModel.INSTANCES[2]); + public static final MaterialPipeStructure LARGE = new MaterialPipeStructure("pipe_large", 12, 1, false, + TagPrefix.pipeLarge, 0.75f, + PipeModel.INSTANCES[3]); + public static final MaterialPipeStructure HUGE = new MaterialPipeStructure("pipe_huge", 24, 1, false, + TagPrefix.pipeHuge, 0.875f, + PipeModel.INSTANCES[4]); + + public static final MaterialPipeStructure QUADRUPLE = new MaterialPipeStructure("pipe_quadruple", 8, 4, false, + TagPrefix.pipeQuadruple, + 0.95f, PipeModel.INSTANCES[5]); + public static final MaterialPipeStructure NONUPLE = new MaterialPipeStructure("pipe_nonuple", 18, 9, false, + TagPrefix.pipeNonuple, 0.95f, + PipeModel.INSTANCES[6]); + + public static final MaterialPipeStructure TINY_RESTRICTIVE = new MaterialPipeStructure("pipe_tiny_restrictive", 1, + 1, true, + TagPrefix.pipeTinyRestrictive, 0.25f, PipeModel.RESTRICTIVE_INSTANCES[0]); + public static final MaterialPipeStructure SMALL_RESTRICTIVE = new MaterialPipeStructure("pipe_small_restrictive", 2, + 1, true, + TagPrefix.pipeSmallRestrictive, 0.375f, PipeModel.RESTRICTIVE_INSTANCES[1]); + public static final MaterialPipeStructure NORMAL_RESTRICTIVE = new MaterialPipeStructure("pipe_normal_restrictive", + 6, 1, true, + TagPrefix.pipeNormalRestrictive, 0.5f, PipeModel.RESTRICTIVE_INSTANCES[2]); + public static final MaterialPipeStructure LARGE_RESTRICTIVE = new MaterialPipeStructure("pipe_large_restrictive", + 12, 1, true, + TagPrefix.pipeLargeRestrictive, 0.75f, PipeModel.RESTRICTIVE_INSTANCES[3]); + public static final MaterialPipeStructure HUGE_RESTRICTIVE = new MaterialPipeStructure("pipe_huge_restrictive", 24, + 1, true, + TagPrefix.pipeHugeRestrictive, 0.875f, PipeModel.RESTRICTIVE_INSTANCES[4]); + + public static final MaterialPipeStructure QUADRUPLE_RESTRICTIVE = new MaterialPipeStructure( + "pipe_quadruple_restrictive", 8, 4, true, + TagPrefix.pipeQuadrupleRestrictive, 0.95f, PipeModel.RESTRICTIVE_INSTANCES[5]); + public static final MaterialPipeStructure NONUPLE_RESTRICTIVE = new MaterialPipeStructure( + "pipe_nonuple_restrictive", 18, 9, true, + TagPrefix.pipeNonupleRestrictive, 0.95f, PipeModel.RESTRICTIVE_INSTANCES[6]); + + public MaterialPipeStructure(String name, int material, int channelCount, boolean restrictive, TagPrefix prefix, + float renderThickness, PipeModel model) { + this.name = name; + this.material = material; + this.channelCount = channelCount; + this.restrictive = restrictive; + this.prefix = prefix; + this.renderThickness = renderThickness; + this.model = model; + PipeStructureRegistry.register(this); + } + + @Override + public @NotNull String getSerializedName() { + return name; + } + + @Override + public TagPrefix getPrefix() { + return prefix; + } + + @Override + public float getRenderThickness() { + return renderThickness; + } + + @Override + public int getChannelCount() { + return channelCount; + } + + @Override + public AbstractPipeModel getModel() { + return model; + } + + @Override + public boolean isPaintable() { + return true; + } + + public static void registerDefaultStructures(Consumer register) { + register.accept(TINY); + register.accept(SMALL); + register.accept(NORMAL); + register.accept(LARGE); + register.accept(HUGE); + register.accept(QUADRUPLE); + register.accept(NONUPLE); + register.accept(TINY_RESTRICTIVE); + register.accept(SMALL_RESTRICTIVE); + register.accept(NORMAL_RESTRICTIVE); + register.accept(LARGE_RESTRICTIVE); + register.accept(HUGE_RESTRICTIVE); + register.accept(QUADRUPLE_RESTRICTIVE); + register.accept(NONUPLE_RESTRICTIVE); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeData.java deleted file mode 100644 index faa0980a9b..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeData.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.IAttachData; - -import net.minecraft.core.Direction; - -import lombok.Getter; -import lombok.experimental.Accessors; - -import java.util.Objects; - -/** - * @author KilaBash - * @date 2023/3/1 - * @implNote CableData - */ -@Accessors(fluent = true) -public class FluidPipeData implements IAttachData { - - @Getter - FluidPipeProperties properties; - @Getter - byte connections; - - public FluidPipeData(FluidPipeProperties properties, byte connections) { - this.properties = properties; - this.connections = connections; - } - - @Override - public boolean canAttachTo(Direction side) { - return (connections & (1 << side.ordinal())) != 0; - } - - @Override - public boolean setAttached(Direction side, boolean attach) { - var result = canAttachTo(side); - if (result != attach) { - if (attach) { - connections |= (1 << side.ordinal()); - } else { - connections &= ~(1 << side.ordinal()); - } - } - return result != attach; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof FluidPipeData cableData) { - return cableData.properties.equals(properties) && connections == cableData.connections; - } - return super.equals(obj); - } - - @Override - public int hashCode() { - return Objects.hash(properties, connections); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeNet.java deleted file mode 100644 index 5b9702e48d..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeNet.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; -import com.gregtechceu.gtceu.api.pipenet.PipeNet; - -import net.minecraft.nbt.CompoundTag; - -/** - * @author KilaBash - * @date 2023/3/11 - * @implNote FluidPipeNet - */ -public class FluidPipeNet extends PipeNet { - - public FluidPipeNet(LevelPipeNet world) { - super(world); - } - - ///////////////////////////////////// - // *********** NBT ***********// - ///////////////////////////////////// - - @Override - protected void writeNodeData(FluidPipeProperties nodeData, CompoundTag tagCompound) { - tagCompound.putInt("max_temperature", nodeData.getMaxFluidTemperature()); - tagCompound.putLong("throughput", nodeData.getThroughput()); - tagCompound.putBoolean("gas_proof", nodeData.isGasProof()); - tagCompound.putBoolean("acid_proof", nodeData.isAcidProof()); - tagCompound.putBoolean("cryo_proof", nodeData.isCryoProof()); - tagCompound.putBoolean("plasma_proof", nodeData.isPlasmaProof()); - tagCompound.putInt("channels", nodeData.getChannels()); - } - - @Override - protected FluidPipeProperties readNodeData(CompoundTag tagCompound) { - int maxTemperature = tagCompound.getInt("max_temperature"); - long throughput = tagCompound.getLong("throughput"); - boolean gasProof = tagCompound.getBoolean("gas_proof"); - boolean acidProof = tagCompound.getBoolean("acid_proof"); - boolean cryoProof = tagCompound.getBoolean("cryo_proof"); - boolean plasmaProof = tagCompound.getBoolean("plasma_proof"); - int channels = tagCompound.getInt("channels"); - return new FluidPipeProperties(maxTemperature, throughput, gasProof, acidProof, cryoProof, plasmaProof, - channels); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeType.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeType.java deleted file mode 100644 index 73abe9df8d..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidPipeType.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidPipeProperties; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.pipenet.IMaterialPipeType; -import com.gregtechceu.gtceu.client.model.PipeModel; - -import net.minecraft.resources.ResourceLocation; - -import lombok.Getter; - -import static com.gregtechceu.gtceu.api.data.tag.TagPrefix.*; - -public enum FluidPipeType implements IMaterialPipeType { - - TINY("tiny", 0.25f, 1, pipeTinyFluid), - SMALL("small", 0.375f, 2, pipeSmallFluid), - NORMAL("normal", 0.5f, 6, pipeNormalFluid), - LARGE("large", 0.75f, 12, pipeLargeFluid), - HUGE("huge", 0.875f, 24, pipeHugeFluid), - QUADRUPLE("quadruple", 0.95f, 2, pipeQuadrupleFluid, 4), - NONUPLE("nonuple", 0.95f, 2, pipeNonupleFluid, 9); - - public static final ResourceLocation TYPE_ID = GTCEu.id("fluid"); - - public final String name; - public final float thickness; - public final int capacityMultiplier; - @Getter - public final TagPrefix tagPrefix; - public final int channels; - - FluidPipeType(String name, float thickness, int capacityMultiplier, TagPrefix TagPrefix) { - this(name, thickness, capacityMultiplier, TagPrefix, 1); - } - - FluidPipeType(String name, float thickness, int capacityMultiplier, TagPrefix TagPrefix, int channels) { - this.name = name; - this.thickness = thickness; - this.capacityMultiplier = capacityMultiplier; - this.tagPrefix = TagPrefix; - this.channels = channels; - } - - @Override - public float getThickness() { - return thickness; - } - - @Override - public FluidPipeProperties modifyProperties(FluidPipeProperties fluidPipeData) { - return new FluidPipeProperties( - fluidPipeData.getMaxFluidTemperature(), - fluidPipeData.getThroughput() * capacityMultiplier, - fluidPipeData.isGasProof(), - fluidPipeData.isAcidProof(), - fluidPipeData.isCryoProof(), - fluidPipeData.isPlasmaProof(), - channels); - } - - @Override - public boolean isPaintable() { - return true; - } - - @Override - public ResourceLocation type() { - return TYPE_ID; - } - - public PipeModel createPipeModel(Material material) { - if (material.hasProperty(PropertyKey.WOOD)) { - return new PipeModel(thickness, () -> GTCEu.id("block/pipe/pipe_side_wood"), - () -> GTCEu.id("block/pipe/pipe_%s_in_wood".formatted(name)), null, null); - } - return new PipeModel(thickness, () -> GTCEu.id("block/pipe/pipe_side"), - () -> GTCEu.id("block/pipe/pipe_%s_in".formatted(name)), - null, null/* - * () -> GTCEu.id("block/pipe/pipe_side_secondary"), () -> - * GTCEu.id("block/pipe/pipe_%s_in_secondary".formatted(name)) TODO enable once the textures - * are added - */); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidTransferHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidTransferHandler.java deleted file mode 100644 index 92c507e549..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/FluidTransferHandler.java +++ /dev/null @@ -1,161 +0,0 @@ -// package com.gregtechceu.gtceu.common.pipelike.fluidpipe; -// -// import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -// import com.gregtechceu.gtceu.common.blockentity.FluidPipeBlockEntity; -// import com.gregtechceu.gtceu.common.cover.FluidFilterCover; -// import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -// import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; -// import it.unimi.dsi.fastutil.objects.Object2LongMap; -// import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -// import lombok.Setter; -// import net.minecraft.core.BlockPos; -// import net.minecraft.core.Direction; -// import net.minecraft.world.level.material.Fluid; -// import org.jetbrains.annotations.NotNull; -// import org.jetbrains.annotations.Nullable; -// import oshi.util.tuples.Pair; -// -// import java.util.*; -// import java.util.function.Predicate; -// -/// ** -// * @author KilaBash -// * @date 2023/3/11 -// * @implNote FluidTransferHandler -// */ -// public class FluidTransferHandler implements IFluidTransfer { -// -// private final FluidPipeNet net; -// private final FluidPipeBlockEntity pipe; -// private final List paths; -// @Nullable -// private final Direction side; -// @Setter -// private Predicate filter = fluid -> true; -// -// public FluidTransferHandler(FluidPipeNet net, FluidPipeBlockEntity pipe, @Nullable Direction side) { -// this.net = Objects.requireNonNull(net); -// this.pipe = Objects.requireNonNull(pipe); -// this.paths = net.getNetData(pipe.getPipePos()); -// this.side = side; -// } -// -// @Override -// public int getTanks() { -// return 1; -// } -// -// @NotNull -// @Override -// public FluidStack getFluidInTank(int tank) { -// return FluidStack.empty(); -// } -// -// @Override -// public long getTankCapacity(int tank) { -// return tank == 0 ? net.getNodeAt(pipe.getPipePos()).data.properties.getPlatformThroughput() - -// net.getThroughputUsed(pipe.getPipePos()) : 0; -// } -// -// @Override -// public boolean isFluidValid(int tank, @NotNull FluidStack stack) { -// return filter.test(stack); -// } -// -// /** -// * check path. how much fluid can be transferred. -// * @return amount -// */ -// private long checkPathAvailable(FluidStack stack, PipeNetRoutePath routePath, Map> -// simulateChannelUsed, Object2LongMap simulateThroughputUsed) { -// if (stack.isEmpty()) return 0; -// var amount = stack.getAmount(); -// for (Pair node : routePath.getPath()) { -// var properties = node.getB().properties; -// var pos = node.getA(); -// if (!properties.acceptFluid(stack)) { -// return 0; -// } -// var channels = net.getChannelUsed(pos); -// var simulateChannels = simulateChannelUsed.getOrDefault(pos, Collections.emptySet()); -// -// if (!channels.contains(stack.getFluid()) && !simulateChannels.contains(stack.getFluid()) -// && (channels.size() + simulateChannels.size()) >= properties.getChannels()) return 0; -// -// var left = properties.getPlatformThroughput() - net.getThroughputUsed(pos) - simulateThroughputUsed.getOrDefault(pos, -// 0); -// amount = Math.min(amount, left); -// if (amount == 0) return 0; -// } -// return amount; -// } -// -// @Override -// public long fill(FluidStack resource, boolean simulate) { -// if (resource.isEmpty() || !filter.test(resource)) return 0; -// var left = resource.copy(); -// Map> simulateChannelUsed = new HashMap<>(); -// Object2LongMap simulateThroughputUsed = new Object2LongOpenHashMap<>(); -// for (PipeNetRoutePath path : paths) { -// if (Objects.equals(pipe.getPipePos(), path.getPipePos()) && (side == path.getFaceToHandler() || side == null)) { -// //Do not insert into source handler -// continue; -// } -// var handler = path.getHandler(pipe.getPipeLevel()); -// if (handler != null) { -// var coverable = GTCapabilityHelper.getCoverable(net.getLevel(), path.getPipePos(), null); -// if (coverable != null) { -// if (coverable.getCoverAtSide(path.getFaceToHandler()) instanceof FluidFilterCover cover && -// !cover.getFluidFilter().test(resource)) { -// return 0; -// } -// } -// var accepted = checkPathAvailable(left, path, simulateChannelUsed, simulateThroughputUsed); -// if (accepted <= 0) continue; -// var copied = left.copy(); -// copied.setAmount(accepted); -// var filled = handler.fill(copied, simulate); -// if (filled > 0) { // occupy capacity + channel -// for (Pair node : path.getPath()) { -// var pos = node.getA(); -// if (simulate) { -// simulateThroughputUsed.put(pos, simulateThroughputUsed.getOrDefault(pos, 0) + filled); -// simulateChannelUsed.computeIfAbsent(pos, p -> new HashSet<>()).add(resource.getFluid()); -// } else { -// net.useThroughput(pos, filled); -// net.useChannel(pos, resource.getFluid()); -// } -// } -// -// } -// left.shrink(filled); -// if (left.isEmpty()) { -// break; -// } -// } -// } -// return resource.getAmount() - left.getAmount(); -// } -// -// @NotNull -// @Override -// public FluidStack drain(FluidStack resource, boolean simulate) { -// return FluidStack.empty(); -// } -// -// @NotNull -// @Override -// public FluidStack drain(long maxDrain, boolean simulate) { -// return FluidStack.empty(); -// } -// -// @Override -// public boolean supportsFill(int i) { -// return true; -// } -// -// @Override -// public boolean supportsDrain(int i) { -// return false; -// } -// } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/LevelFluidPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/LevelFluidPipeNet.java deleted file mode 100644 index 5e9b8084a4..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/LevelFluidPipeNet.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; - -public class LevelFluidPipeNet extends LevelPipeNet { - - public static LevelFluidPipeNet getOrCreate(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> new LevelFluidPipeNet(serverLevel, tag), - () -> new LevelFluidPipeNet(serverLevel), "gtcue_fluid_pipe_net"); - } - - public LevelFluidPipeNet(ServerLevel serverLevel) { - super(serverLevel); - } - - public LevelFluidPipeNet(ServerLevel serverLevel, CompoundTag tag) { - super(serverLevel, tag); - } - - @Override - protected FluidPipeNet createNetInstance() { - return new FluidPipeNet(this); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeNetRoutePath.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeNetRoutePath.java deleted file mode 100644 index 1777dfdf63..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeNetRoutePath.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe; - -import com.gregtechceu.gtceu.api.pipenet.IRoutePath; - -import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; -import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import oshi.util.tuples.Pair; - -public class PipeNetRoutePath implements IRoutePath { - - @Getter - private final BlockPos pipePos; - @Getter - private final Direction targetFacing; - @Getter - private final int distance; - private final Pair[] path; - - public PipeNetRoutePath(BlockPos pipePos, Direction targetFacing, Pair[] path, - int distance) { - this.pipePos = pipePos; - this.targetFacing = targetFacing; - this.path = path; - this.distance = distance; - } - - public Pair[] getPath() { - return path; - } - - @Override - @NotNull - public BlockPos getTargetPipePos() { - return pipePos.relative(targetFacing); - } - - @Nullable - public IFluidTransfer getHandler(Level world) { - return FluidTransferHelper.getFluidTransfer(world, getTargetPipePos(), targetFacing.getOpposite()); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeTankList.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeTankList.java deleted file mode 100644 index 270748eb2c..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/PipeTankList.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe; - -import com.gregtechceu.gtceu.common.blockentity.FluidPipeBlockEntity; - -import com.lowdragmc.lowdraglib.misc.FluidStorage; -import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; - -import net.minecraft.core.Direction; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Arrays; -import java.util.Iterator; - -@SuppressWarnings("UnstableApiUsage") -public class PipeTankList implements IFluidTransfer, Iterable { - - private final FluidPipeBlockEntity pipe; - private final FluidStorage[] tanks; - private final Direction facing; - - public PipeTankList(FluidPipeBlockEntity pipe, Direction facing, FluidStorage... fluidTanks) { - this.tanks = fluidTanks; - this.pipe = pipe; - this.facing = facing; - } - - private int findChannel(FluidStack stack) { - if (stack.isEmpty() || tanks == null) - return -1; - int empty = -1; - for (int i = tanks.length - 1; i >= 0; i--) { - FluidStack f = tanks[i].getFluid(); - if (f.isEmpty()) - empty = i; - else if (f.isFluidEqual(stack)) - return i; - } - return empty; - } - - @Override - public int getTanks() { - return tanks.length; - } - - @NotNull - @Override - public FluidStack getFluidInTank(int tank) { - return tanks[tank].getFluid(); - } - - @Override - public void setFluidInTank(int tank, @NotNull FluidStack fluidStack) { - tanks[tank].setFluid(fluidStack); - } - - @Override - public long getTankCapacity(int tank) { - return tanks[tank].getCapacity(); - } - - @Override - public boolean isFluidValid(int tank, @NotNull FluidStack stack) { - return tanks[tank].isFluidValid(stack); - } - - @Override - public long fill(int tank, FluidStack resource, boolean simulate, boolean notifyChanges) { - if (pipe.isBlocked(facing) || resource == null || resource.getAmount() <= 0) - return 0; - - return fill(resource, simulate, tank); - } - - @Override - public boolean supportsFill(int tank) { - return true; - } - - @NotNull - @Override - public FluidStack drain(int tank, FluidStack resource, boolean simulate, boolean notifyChanges) { - FluidStorage storage = tanks[tank]; - FluidStack drained = storage.drain(resource, simulate, notifyChanges); - if (!drained.isEmpty()) return drained; - else return FluidStack.empty(); - } - - @Override - public boolean supportsDrain(int tank) { - return true; - } - - @Override - public long fill(FluidStack resource, boolean simulate, boolean notifyChanges) { - int channel; - if (pipe.isBlocked(facing) || resource == null || resource.getAmount() <= 0 || - (channel = findChannel(resource)) < 0) - return 0; - - return fill(resource, simulate, channel); - } - - private long fullCapacity() { - return tanks.length * pipe.getCapacityPerTank(); - } - - private long fill(FluidStack resource, boolean simulate, int channel) { - if (channel >= tanks.length) return 0; - FluidStorage tank = tanks[channel]; - FluidStack currentFluid = tank.getFluid(); - - if (currentFluid.isEmpty() || currentFluid.getAmount() <= 0) { - FluidStack newFluid = resource.copy(); - newFluid.setAmount(Math.min(pipe.getCapacityPerTank(), newFluid.getAmount())); - if (!simulate) { - tank.setFluid(newFluid); - pipe.receivedFrom(facing); - pipe.checkAndDestroy(newFluid); - } - return newFluid.getAmount(); - } - if (currentFluid.isFluidEqual(resource)) { - long toAdd = Math.min(tank.getCapacity() - currentFluid.getAmount(), resource.getAmount()); - if (toAdd > 0) { - if (!simulate) { - currentFluid.setAmount(currentFluid.getAmount() + toAdd); - pipe.receivedFrom(facing); - pipe.checkAndDestroy(currentFluid); - } - return toAdd; - } - } - - return 0; - } - - @NotNull - @Override - public FluidStack drain(long maxDrain, boolean doDrain, boolean notifyChanges) { - if (maxDrain <= 0) return FluidStack.empty(); - for (FluidStorage tank : tanks) { - FluidStack drained = tank.drain(maxDrain, doDrain, notifyChanges); - if (!drained.isEmpty()) return drained; - } - return FluidStack.empty(); - } - - @NotNull - @Override - public Object createSnapshot() { - return new Object(); - } - - @Override - public void restoreFromSnapshot(Object snapshot) {} - - @Nullable - @Override - public FluidStack drain(FluidStack fluidStack, boolean doDrain) { - if (fluidStack.isEmpty() || fluidStack.getAmount() <= 0) return FluidStack.empty(); - fluidStack = fluidStack.copy(); - for (FluidStorage tank : tanks) { - FluidStack drained = tank.drain(fluidStack, doDrain); - if (!drained.isEmpty()) return drained; - } - return FluidStack.empty(); - } - - @Override - @NotNull - public Iterator iterator() { - return Arrays.stream(tanks).iterator(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetHandler.java deleted file mode 100644 index 1887123061..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetHandler.java +++ /dev/null @@ -1,505 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.item; - -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.api.capability.recipe.IO; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.common.blockentity.ItemPipeBlockEntity; -import com.gregtechceu.gtceu.common.cover.ConveyorCover; -import com.gregtechceu.gtceu.common.cover.ItemFilterCover; -import com.gregtechceu.gtceu.common.cover.RobotArmCover; -import com.gregtechceu.gtceu.common.cover.data.DistributionMode; -import com.gregtechceu.gtceu.common.cover.data.ItemFilterMode; -import com.gregtechceu.gtceu.utils.FacingPos; -import com.gregtechceu.gtceu.utils.GTTransferUtils; -import com.gregtechceu.gtceu.utils.ItemStackHashStrategy; - -import com.lowdragmc.lowdraglib.misc.ItemStackTransfer; -import com.lowdragmc.lowdraglib.side.item.IItemTransfer; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; - -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; -import lombok.Getter; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -public class ItemNetHandler implements IItemTransfer { - - @Getter - private ItemPipeNet net; - private ItemPipeBlockEntity pipe; - private final Level world; - @Getter - private final Direction facing; - private final Map simulatedTransfersGlobalRoundRobin = new HashMap<>(); - private int simulatedTransfers = 0; - - private final ItemStackTransfer testHandler = new ItemStackTransfer(1); - - public ItemNetHandler(ItemPipeNet net, ItemPipeBlockEntity pipe, Direction facing) { - this.net = net; - this.pipe = pipe; - this.facing = facing; - this.world = pipe.getPipeLevel(); - } - - private long getLevelTime() { - return net.getLevel().getGameTime(); - } - - public void updateNetwork(ItemPipeNet net) { - this.net = net; - } - - public void updatePipe(ItemPipeBlockEntity pipe) { - this.pipe = pipe; - } - - private void copyTransferred() { - simulatedTransfers = pipe.getTransferredItems(); - simulatedTransfersGlobalRoundRobin.clear(); - simulatedTransfersGlobalRoundRobin.putAll(pipe.getTransferred()); - } - - @NotNull - @Override - public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate, boolean notifyChanges) { - if (stack.isEmpty()) return stack; - - if (net == null || pipe == null || pipe.isInValid() || pipe.isBlocked(facing)) { - return stack; - } - - copyTransferred(); - CoverBehavior pipeCover = pipe.getCoverContainer().getCoverAtSide(facing); - CoverBehavior tileCover = getCoverOnNeighbour(pipe.getPipePos(), facing); - - boolean pipeConveyor = pipeCover instanceof ConveyorCover, tileConveyor = tileCover instanceof ConveyorCover; - // abort if there are two conveyors - if (pipeConveyor && tileConveyor) return stack; - - if (tileCover != null && !checkImportCover(tileCover, false, stack)) - return stack; - - if (!pipeConveyor && !tileConveyor) - return insertFirst(stack, simulate); - - ConveyorCover conveyor = (ConveyorCover) (pipeConveyor ? pipeCover : tileCover); - if (conveyor.getIo() == (pipeConveyor ? IO.IN : IO.OUT)) { - boolean roundRobinGlobal = conveyor.getDistributionMode() == DistributionMode.ROUND_ROBIN_GLOBAL; - if (roundRobinGlobal || conveyor.getDistributionMode() == DistributionMode.ROUND_ROBIN_PRIO) - return insertRoundRobin(stack, simulate, roundRobinGlobal); - } - - return insertFirst(stack, simulate); - } - - public static boolean checkImportCover(CoverBehavior cover, boolean onPipe, ItemStack stack) { - if (cover == null) return true; - if (cover instanceof ItemFilterCover filter) { - return (filter.getFilterMode() != ItemFilterMode.FILTER_BOTH && - (filter.getFilterMode() != ItemFilterMode.FILTER_INSERT || !onPipe) && - (filter.getFilterMode() != ItemFilterMode.FILTER_EXTRACT || onPipe)) || - filter.getItemFilter().test(stack); - } - return true; - } - - public ItemStack insertFirst(ItemStack stack, boolean simulate) { - for (ItemRoutePath inv : net.getNetData(pipe.getPipePos(), facing)) { - stack = insert(inv, stack, simulate); - if (stack.isEmpty()) - return ItemStack.EMPTY; - } - return stack; - } - - public ItemStack insertRoundRobin(ItemStack stack, boolean simulate, boolean global) { - List routePaths = net.getNetData(pipe.getPipePos(), facing); - if (routePaths.isEmpty()) - return stack; - if (routePaths.size() == 1) - return insert(routePaths.get(0), stack, simulate); - List routePathsCopy = new ArrayList<>(routePaths); - - if (global) { - stack = insertToHandlersEnhanced(routePathsCopy, stack, routePaths.size(), simulate); - } else { - stack = insertToHandlers(routePathsCopy, stack, simulate); - if (!stack.isEmpty() && !routePathsCopy.isEmpty()) - stack = insertToHandlers(routePathsCopy, stack, simulate); - } - - return stack; - } - - /** - * Inserts items equally to all handlers - * if it couldn't insert all items, the handler will be removed - * - * @param copy to insert to - * @param stack to insert - * @param simulate simulate - * @return remainder - */ - private ItemStack insertToHandlers(List copy, ItemStack stack, boolean simulate) { - Iterator routePathIterator = copy.listIterator(); - int inserted = 0; - int count = stack.getCount(); - int c = count / copy.size(); - int m = c == 0 ? count % copy.size() : 0; - while (routePathIterator.hasNext()) { - ItemRoutePath routePath = routePathIterator.next(); - - int amount = c; - if (m > 0) { - amount++; - m--; - } - amount = Math.min(amount, stack.getCount() - inserted); - if (amount == 0) break; - ItemStack toInsert = stack.copy(); - toInsert.setCount(amount); - int r = insert(routePath, toInsert, simulate).getCount(); - if (r < amount) { - inserted += (amount - r); - } - if (r == 1 && c == 0 && amount == 1) { - m++; - } - - if (r > 0) - routePathIterator.remove(); - } - - ItemStack remainder = stack.copy(); - remainder.setCount(count - inserted); - return remainder; - } - - private ItemStack insertToHandlersEnhanced(List copy, ItemStack stack, int dest, boolean simulate) { - List transferred = new ArrayList<>(); - IntList steps = new IntArrayList(); - int min = Integer.MAX_VALUE; - ItemStack simStack; - - // find inventories that are not full and get the amount that was inserted in total - for (ItemRoutePath inv : copy) { - simStack = stack.copy(); - int ins = stack.getCount() - insert(inv, simStack, true, true).getCount(); - if (ins <= 0) - continue; - int didTransfer = didTransferTo(inv, simulate); - EnhancedRoundRobinData data = new EnhancedRoundRobinData(inv, ins, didTransfer); - transferred.add(data); - - min = Math.min(min, didTransfer); - - if (!steps.contains(didTransfer)) { - steps.add(didTransfer); - } - } - - if (transferred.isEmpty() || steps.isEmpty()) - return stack; - - if (!simulate && min < Integer.MAX_VALUE) { - decrementBy(min); - } - - transferred.sort(Comparator.comparingInt(data -> data.transferred)); - steps.sort(Integer::compare); - - if (transferred.get(0).transferred != steps.getInt(0)) { - return stack; - } - - int amount = stack.getCount(); - int c = amount / transferred.size(); - int m = amount % transferred.size(); - List transferredCopy = new ArrayList<>(transferred); - int nextStep = steps.removeInt(0); - - // equally distribute items over all inventories - // it takes into account how much was inserted in total - // f.e. if inv1 has 2 inserted and inv2 has 6 inserted, it will first try to insert 4 into inv1 so that both - // have 6 and then it will distribute the rest equally - outer: - while (amount > 0 && !transferredCopy.isEmpty()) { - Iterator iterator = transferredCopy.iterator(); - int i = 0; - while (iterator.hasNext()) { - EnhancedRoundRobinData data = iterator.next(); - if (nextStep >= 0 && data.transferred >= nextStep) - break; - - int toInsert; - if (nextStep <= 0) { - if (amount <= m) { - // break outer; - toInsert = 1; - } else { - toInsert = Math.min(c, amount); - } - } else { - toInsert = Math.min(amount, nextStep - data.transferred); - } - if (data.toTransfer + toInsert >= data.maxInsertable) { - data.toTransfer = data.maxInsertable; - iterator.remove(); - } else { - data.toTransfer += toInsert; - } - - data.transferred += toInsert; - - if ((amount -= toInsert) == 0) { - break outer; - } - i++; - } - - for (EnhancedRoundRobinData data : transferredCopy) { - if (data.transferred < nextStep) - continue outer; - } - if (steps.isEmpty()) { - if (nextStep >= 0) { - c = amount / transferredCopy.size(); - m = amount % transferredCopy.size(); - nextStep = -1; - } - } else { - nextStep = steps.removeInt(0); - } - } - - int inserted = 0; - - // finally actually insert the item - for (EnhancedRoundRobinData data : transferred) { - ItemStack toInsert = stack.copy(); - toInsert.setCount(data.toTransfer); - int ins = data.toTransfer - insert(data.routePath, toInsert, simulate).getCount(); - inserted += ins; - transferTo(data.routePath, simulate, ins); - } - - ItemStack remainder = stack.copy(); - remainder.shrink(inserted); - return remainder; - } - - public ItemStack insert(ItemRoutePath handler, ItemStack stack, boolean simulate) { - return insert(handler, stack, simulate, false); - } - - public ItemStack insert(ItemRoutePath routePath, ItemStack stack, boolean simulate, boolean ignoreLimit) { - int allowed = ignoreLimit ? stack.getCount() : - checkTransferable(routePath.getProperties().getTransferRate(), stack.getCount(), simulate); - if (allowed == 0 || !routePath.matchesFilters(stack)) { - return stack; - } - CoverBehavior pipeCover = routePath.getTargetPipe().getCoverContainer() - .getCoverAtSide(routePath.getTargetFacing()); - CoverBehavior tileCover = getCoverOnNeighbour(routePath.getTargetPipe().getPipePos(), - routePath.getTargetFacing()); - - if (pipeCover != null) { - testHandler.setStackInSlot(0, stack.copy()); - IItemTransfer itemHandler = pipeCover.getItemTransferCap(testHandler); - if (itemHandler == null || (itemHandler != testHandler && - (allowed = itemHandler.extractItem(0, allowed, true).getCount()) <= 0)) { - testHandler.setStackInSlot(0, ItemStack.EMPTY); - return stack; - } - testHandler.setStackInSlot(0, ItemStack.EMPTY); - } - IItemTransfer neighbourHandler = routePath.getHandler(net.getLevel()); - if (pipeCover instanceof RobotArmCover robotArm && robotArm.getIo() == IO.OUT) { - return insertOverRobotArm(neighbourHandler, robotArm, stack, simulate, allowed, ignoreLimit); - } - if (tileCover instanceof RobotArmCover robotArm && robotArm.getIo() == IO.IN) { - return insertOverRobotArm(neighbourHandler, robotArm, stack, simulate, allowed, ignoreLimit); - } - - return insert(neighbourHandler, stack, simulate, allowed, ignoreLimit); - } - - private ItemStack insert(IItemTransfer handler, ItemStack stack, boolean simulate, int allowed, - boolean ignoreLimit) { - if (stack.getCount() == allowed) { - ItemStack re = GTTransferUtils.insertItem(handler, stack, simulate); - if (!ignoreLimit) - transfer(simulate, stack.getCount() - re.getCount()); - return re; - } - ItemStack toInsert = stack.copy(); - toInsert.setCount(Math.min(allowed, stack.getCount())); - int r = GTTransferUtils.insertItem(handler, toInsert, simulate).getCount(); - if (!ignoreLimit) - transfer(simulate, toInsert.getCount() - r); - ItemStack remainder = stack.copy(); - remainder.setCount(r + (stack.getCount() - toInsert.getCount())); - return remainder; - } - - public CoverBehavior getCoverOnNeighbour(BlockPos pos, Direction handlerFacing) { - BlockEntity tile = pipe.getLevel().getBlockEntity(pos.relative(handlerFacing)); - if (tile != null) { - ICoverable coverable = GTCapabilityHelper.getCoverable(pipe.getLevel(), pos.relative(handlerFacing), - handlerFacing.getOpposite()); - if (coverable == null) return null; - return coverable.getCoverAtSide(handlerFacing.getOpposite()); - } - return null; - } - - public ItemStack insertOverRobotArm(IItemTransfer handler, RobotArmCover arm, ItemStack stack, boolean simulate, - int allowed, boolean ignoreLimit) { - int rate; - boolean isStackSpecific = false; - rate = arm.getFilterHandler().getFilter().testItemCount(stack); - int count; - switch (arm.getTransferMode()) { - case TRANSFER_ANY: - return insert(handler, stack, simulate, allowed, ignoreLimit); - case KEEP_EXACT: - count = rate - countStack(handler, stack, arm, isStackSpecific); - if (count <= 0) return stack; - count = Math.min(allowed, Math.min(stack.getCount(), count)); - return insert(handler, stack, simulate, count, ignoreLimit); - case TRANSFER_EXACT: - int max = allowed + arm.getBuffer(); - count = Math.min(max, Math.min(rate, stack.getCount())); - if (count < rate) { - arm.buffer(allowed); - return stack; - } else { - arm.clearBuffer(); - } - if (insert(handler, stack, true, count, ignoreLimit).getCount() != stack.getCount() - count) { - return stack; - } - return insert(handler, stack, simulate, count, ignoreLimit); - } - return stack; - } - - public static int countStack(IItemTransfer handler, ItemStack stack, RobotArmCover arm, boolean isStackSpecific) { - if (arm == null) return 0; - int count = 0; - for (int i = 0; i < handler.getSlots(); i++) { - ItemStack slot = handler.getStackInSlot(i); - if (slot.isEmpty()) continue; - if (isStackSpecific ? ItemStackHashStrategy.comparingAllButCount().equals(stack, slot) : - arm.getFilterHandler().getFilter().test(slot)) { - count += slot.getCount(); - } - } - return count; - } - - private int checkTransferable(float rate, int amount, boolean simulate) { - int max = (int) ((rate * 64) + 0.5); - if (simulate) - return Math.max(0, Math.min(max - simulatedTransfers, amount)); - else - return Math.max(0, Math.min(max - pipe.getTransferredItems(), amount)); - } - - private void transfer(boolean simulate, int amount) { - if (simulate) - simulatedTransfers += amount; - else - pipe.addTransferredItems(amount); - } - - @Override - public int getSlots() { - return 1; - } - - @NotNull - @Override - public ItemStack getStackInSlot(int i) { - return ItemStack.EMPTY; - } - - @NotNull - @Override - public ItemStack extractItem(int slot, int amount, boolean simulate, boolean notifyChanges) { - return ItemStack.EMPTY; - } - - @Override - public int getSlotLimit(int i) { - return 64; - } - - @Override - public boolean isItemValid(int slot, @NotNull ItemStack stack) { - return true; - } - - @NotNull - @Override - public Object createSnapshot() { - return new Object(); - } - - @Override - public void restoreFromSnapshot(Object snapshot) {} - - private void transferTo(ItemRoutePath handler, boolean simulate, int amount) { - if (simulate) - simulatedTransfersGlobalRoundRobin.merge(handler.toFacingPos(), amount, Integer::sum); - else - pipe.getTransferred().merge(handler.toFacingPos(), amount, Integer::sum); - } - - private boolean contains(ItemRoutePath handler, boolean simulate) { - return simulate ? simulatedTransfersGlobalRoundRobin.containsKey(handler.toFacingPos()) : - pipe.getTransferred().containsKey(handler.toFacingPos()); - } - - private int didTransferTo(ItemRoutePath handler, boolean simulate) { - if (simulate) - return simulatedTransfersGlobalRoundRobin.getOrDefault(handler.toFacingPos(), 0); - return pipe.getTransferred().getOrDefault(handler.toFacingPos(), 0); - } - - private void resetTransferred(boolean simulated) { - if (simulated) - simulatedTransfersGlobalRoundRobin.clear(); - else - pipe.resetTransferred(); - } - - private void decrementBy(int amount) { - for (Map.Entry entry : pipe.getTransferred().entrySet()) { - entry.setValue(entry.getValue() - amount); - } - } - - private static class EnhancedRoundRobinData { - - private final ItemRoutePath routePath; - private final int maxInsertable; - private int transferred; - private int toTransfer = 0; - - private EnhancedRoundRobinData(ItemRoutePath routePath, int maxInsertable, int transferred) { - this.maxInsertable = maxInsertable; - this.transferred = transferred; - this.routePath = routePath; - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetWalker.java deleted file mode 100644 index b70324fefc..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemNetWalker.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.item; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.PipeNetWalker; -import com.gregtechceu.gtceu.common.blockentity.ItemPipeBlockEntity; -import com.gregtechceu.gtceu.common.cover.ItemFilterCover; -import com.gregtechceu.gtceu.common.cover.ShutterCover; -import com.gregtechceu.gtceu.common.cover.data.ItemFilterMode; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.function.Predicate; - -public class ItemNetWalker extends PipeNetWalker { - - public static List createNetData(ItemPipeNet pipeNet, BlockPos sourcePipe, Direction sourceFacing) { - if (!(pipeNet.getLevel().getBlockEntity(sourcePipe) instanceof ItemPipeBlockEntity)) { - return null; - } - try { - ItemNetWalker walker = new ItemNetWalker(pipeNet, sourcePipe, 1, new ArrayList<>(), null); - walker.sourcePipe = sourcePipe; - walker.facingToHandler = sourceFacing; - walker.traversePipeNet(); - return walker.inventories; - } catch (Exception e) { - GTCEu.LOGGER.error("error while create net data for ItemPipeNet", e); - } - return null; - } - - private ItemPipeProperties minProperties; - private final List inventories; - private final List> filters = new ArrayList<>(); - private final EnumMap>> nextFilters = new EnumMap<>(Direction.class); - private BlockPos sourcePipe; - private Direction facingToHandler; - - protected ItemNetWalker(ItemPipeNet world, BlockPos sourcePipe, int distance, List inventories, - ItemPipeProperties properties) { - super(world, sourcePipe, distance); - this.inventories = inventories; - this.minProperties = properties; - } - - @NotNull - @Override - protected PipeNetWalker createSubWalker(ItemPipeNet pipeNet, - Direction facingToNextPos, - BlockPos nextPos, - int walkedBlocks) { - ItemNetWalker walker = new ItemNetWalker(pipeNet, nextPos, walkedBlocks, inventories, minProperties); - walker.facingToHandler = facingToHandler; - walker.sourcePipe = sourcePipe; - walker.filters.addAll(filters); - List> moreFilters = nextFilters.get(facingToNextPos); - if (moreFilters != null && !moreFilters.isEmpty()) { - walker.filters.addAll(moreFilters); - } - return walker; - } - - @Override - protected Class getBasePipeClass() { - return ItemPipeBlockEntity.class; - } - - @Override - protected void checkPipe(ItemPipeBlockEntity pipeTile, BlockPos pos) { - for (List> filters : nextFilters.values()) { - if (!filters.isEmpty()) { - this.filters.addAll(filters); - } - } - nextFilters.clear(); - ItemPipeProperties pipeProperties = pipeTile.getNodeData(); - if (minProperties == null) { - minProperties = pipeProperties; - } else { - minProperties = new ItemPipeProperties(minProperties.getPriority() + pipeProperties.getPriority(), - Math.min(minProperties.getTransferRate(), pipeProperties.getTransferRate())); - } - } - - @Override - protected void checkNeighbour(ItemPipeBlockEntity pipeTile, BlockPos pipePos, Direction faceToNeighbour, - @Nullable BlockEntity neighbourTile) { - if (neighbourTile == null || (pipePos.equals(sourcePipe) && faceToNeighbour == facingToHandler)) { - return; - } - LazyOptional handler = neighbourTile.getCapability(ForgeCapabilities.ITEM_HANDLER, - faceToNeighbour.getOpposite()); - if (handler.isPresent()) { - List> filters = new ArrayList<>(this.filters); - List> moreFilters = nextFilters.get(faceToNeighbour); - if (moreFilters != null && !moreFilters.isEmpty()) { - filters.addAll(moreFilters); - } - inventories.add(new ItemRoutePath(pipeTile, faceToNeighbour, getWalkedBlocks(), minProperties, filters)); - } - } - - @Override - protected boolean isValidPipe(ItemPipeBlockEntity currentPipe, ItemPipeBlockEntity neighbourPipe, BlockPos pipePos, - Direction faceToNeighbour) { - CoverBehavior thisCover = currentPipe.getCoverContainer().getCoverAtSide(faceToNeighbour); - CoverBehavior neighbourCover = neighbourPipe.getCoverContainer().getCoverAtSide(faceToNeighbour.getOpposite()); - List> filters = new ArrayList<>(); - if (thisCover instanceof ShutterCover shutter) { - filters.add(stack -> !shutter.isWorkingEnabled()); - } else if (thisCover instanceof ItemFilterCover itemFilterCover && - itemFilterCover.getFilterMode() != ItemFilterMode.FILTER_INSERT) { - filters.add(itemFilterCover.getItemFilter()); - } - if (neighbourCover instanceof ShutterCover shutter) { - filters.add(stack -> !shutter.isWorkingEnabled()); - } else if (neighbourCover instanceof ItemFilterCover itemFilterCover && - itemFilterCover.getFilterMode() != ItemFilterMode.FILTER_EXTRACT) { - filters.add(itemFilterCover.getItemFilter()); - } - if (!filters.isEmpty()) { - nextFilters.put(faceToNeighbour, filters); - } - return true; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeData.java deleted file mode 100644 index 97f9e0a8e7..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeData.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.item; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.IAttachData; - -import net.minecraft.core.Direction; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.experimental.Accessors; - -import java.util.Objects; - -@Accessors(fluent = true) -@AllArgsConstructor -public class ItemPipeData implements IAttachData { - - @Getter - ItemPipeProperties properties; - @Getter - byte connections; - - @Override - public boolean canAttachTo(Direction side) { - return (connections & (1 << side.ordinal())) != 0; - } - - @Override - public boolean setAttached(Direction side, boolean attach) { - var result = canAttachTo(side); - if (result != attach) { - if (attach) { - connections |= (1 << side.ordinal()); - } else { - connections &= ~(1 << side.ordinal()); - } - } - return result != attach; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof ItemPipeData cableData) { - return cableData.properties.equals(properties) && connections == cableData.connections; - } - return super.equals(obj); - } - - @Override - public int hashCode() { - return Objects.hash(properties, connections); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeNet.java deleted file mode 100644 index ef5f1d9206..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeNet.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.item; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; -import com.gregtechceu.gtceu.api.pipenet.Node; -import com.gregtechceu.gtceu.api.pipenet.PipeNet; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; - -import java.util.*; - -public class ItemPipeNet extends PipeNet { - - private final Map> NET_DATA = new HashMap<>(); - - public ItemPipeNet(LevelPipeNet> world) { - super(world); - } - - public List getNetData(BlockPos pipePos, Direction facing) { - List data = NET_DATA.get(pipePos); - if (data == null) { - data = ItemNetWalker.createNetData(this, pipePos, facing); - if (data == null) { - // walker failed, don't cache so it tries again on next insertion - return Collections.emptyList(); - } - data.sort(Comparator.comparingInt(inv -> inv.getProperties().getPriority())); - NET_DATA.put(pipePos, data); - } - return data; - } - - @Override - public void onNeighbourUpdate(BlockPos fromPos) { - NET_DATA.clear(); - } - - @Override - public void onPipeConnectionsUpdate() { - NET_DATA.clear(); - } - - @Override - protected void transferNodeData(Map> transferredNodes, - PipeNet parentNet) { - super.transferNodeData(transferredNodes, parentNet); - NET_DATA.clear(); - ((ItemPipeNet) parentNet).NET_DATA.clear(); - } - - @Override - protected void writeNodeData(ItemPipeProperties nodeData, CompoundTag tagCompound) { - tagCompound.putInt("Resistance", nodeData.getPriority()); - tagCompound.putFloat("Rate", nodeData.getTransferRate()); - } - - @Override - protected ItemPipeProperties readNodeData(CompoundTag tagCompound) { - return new ItemPipeProperties(tagCompound.getInt("Resistance"), tagCompound.getFloat("Rate")); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeType.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeType.java deleted file mode 100644 index e37dd7286a..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemPipeType.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.item; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.pipenet.IMaterialPipeType; -import com.gregtechceu.gtceu.client.model.PipeModel; - -import net.minecraft.resources.ResourceLocation; - -import lombok.Getter; - -public enum ItemPipeType implements IMaterialPipeType { - - SMALL("small", 0.375f, TagPrefix.pipeSmallItem, 0.5f, 1.5f), - NORMAL("normal", 0.5f, TagPrefix.pipeNormalItem, 1f, 1f), - LARGE("large", 0.75f, TagPrefix.pipeLargeItem, 2f, 0.75f), - HUGE("huge", 0.875f, TagPrefix.pipeHugeItem, 4f, 0.5f), - - RESTRICTIVE_SMALL("small_restrictive", 0.375f, TagPrefix.pipeSmallRestrictive, 0.5f, 150f), - RESTRICTIVE_NORMAL("normal_restrictive", 0.5f, TagPrefix.pipeNormalRestrictive, 1f, 100f), - RESTRICTIVE_LARGE("large_restrictive", 0.75f, TagPrefix.pipeLargeRestrictive, 2f, 75f), - RESTRICTIVE_HUGE("huge_restrictive", 0.875f, TagPrefix.pipeHugeRestrictive, 4f, 50f); - - public static final ResourceLocation TYPE_ID = GTCEu.id("item"); - public static final ItemPipeType[] VALUES = values(); - - @Getter - public final String name; - @Getter - private final float thickness; - @Getter - private final float rateMultiplier; - private final float resistanceMultiplier; - @Getter - private final TagPrefix tagPrefix; - - ItemPipeType(String name, float thickness, TagPrefix orePrefix, float rateMultiplier, float resistanceMultiplier) { - this.name = name; - this.thickness = thickness; - this.tagPrefix = orePrefix; - this.rateMultiplier = rateMultiplier; - this.resistanceMultiplier = resistanceMultiplier; - } - - public boolean isRestrictive() { - return ordinal() > 3; - } - - public String getSizeForTexture() { - if (!isRestrictive()) - return name; - else - return name.substring(0, name.length() - 12); - } - - @Override - public ItemPipeProperties modifyProperties(ItemPipeProperties baseProperties) { - return new ItemPipeProperties((int) ((baseProperties.getPriority() * resistanceMultiplier) + 0.5), - baseProperties.getTransferRate() * rateMultiplier); - } - - @Override - public boolean isPaintable() { - return true; - } - - @Override - public ResourceLocation type() { - return TYPE_ID; - } - - public PipeModel createPipeModel(Material material) { - PipeModel model; - if (material.hasProperty(PropertyKey.WOOD)) { - model = new PipeModel(thickness, () -> GTCEu.id("block/pipe/pipe_side_wood"), - () -> GTCEu.id("block/pipe/pipe_%s_in_wood" - .formatted(this.isRestrictive() ? values()[this.ordinal() - 4].name : name)), - null, null); - } else { - model = new PipeModel(thickness, () -> GTCEu.id("block/pipe/pipe_side"), - () -> GTCEu.id("block/pipe/pipe_%s_in" - .formatted(this.isRestrictive() ? values()[this.ordinal() - 4].name : name)), - null, null/* - * () -> GTCEu.id("block/pipe/pipe_side_secondary"), () -> - * GTCEu.id("block/pipe/pipe_%s_in_secondary".formatted(this.isRestrictive() ? - * values()[this.ordinal() - 4].name : name)) TODO enable once the textures are added - */); - } - if (isRestrictive()) { - model.setSideOverlayTexture(GTCEu.id("block/pipe/pipe_restrictive")); - } - return model; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemRoutePath.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemRoutePath.java deleted file mode 100644 index 2fd14ffb01..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/ItemRoutePath.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.item; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.IRoutePath; -import com.gregtechceu.gtceu.common.blockentity.ItemPipeBlockEntity; -import com.gregtechceu.gtceu.utils.FacingPos; - -import com.lowdragmc.lowdraglib.side.item.IItemTransfer; -import com.lowdragmc.lowdraglib.side.item.ItemTransferHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.function.Predicate; - -public class ItemRoutePath implements IRoutePath { - - @Getter - private final ItemPipeBlockEntity targetPipe; - @NotNull - @Getter - private final Direction targetFacing; - @Getter - private final int distance; - @Getter - private final ItemPipeProperties properties; - private final Predicate filters; - - public ItemRoutePath(ItemPipeBlockEntity targetPipe, @NotNull Direction facing, int distance, - ItemPipeProperties properties, - List> filters) { - this.targetPipe = targetPipe; - this.targetFacing = facing; - this.distance = distance; - this.properties = properties; - this.filters = stack -> { - for (Predicate filter : filters) - if (!filter.test(stack)) return false; - return true; - }; - } - - @Override - public @NotNull BlockPos getTargetPipePos() { - return targetPipe.getPipePos(); - } - - @Override - public @Nullable IItemTransfer getHandler(Level world) { - return ItemTransferHelper.getItemTransfer(world, getTargetPipePos().relative(targetFacing), - targetFacing.getOpposite()); - } - - public boolean matchesFilters(ItemStack stack) { - return filters.test(stack); - } - - public FacingPos toFacingPos() { - return new FacingPos(getTargetPipePos(), targetFacing); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/LevelItemPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/LevelItemPipeNet.java deleted file mode 100644 index b15987806c..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/LevelItemPipeNet.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.item; - -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; - -public class LevelItemPipeNet extends LevelPipeNet { - - public static LevelItemPipeNet getOrCreate(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> new LevelItemPipeNet(serverLevel, tag), - () -> new LevelItemPipeNet(serverLevel), "gtceu_item_pipe_net"); - } - - public LevelItemPipeNet(ServerLevel serverLevel) { - super(serverLevel); - } - - public LevelItemPipeNet(ServerLevel serverLevel, CompoundTag tag) { - super(serverLevel, tag); - } - - @Override - protected ItemPipeNet createNetInstance() { - return new ItemPipeNet(this); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java deleted file mode 100644 index c0f6c67ddc..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetHandler.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.laser; - -import com.gregtechceu.gtceu.api.capability.ILaserContainer; -import com.gregtechceu.gtceu.common.blockentity.LaserPipeBlockEntity; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class LaserNetHandler implements ILaserContainer { - - private LaserPipeNet net; - private final LaserPipeBlockEntity pipe; - private final Direction facing; - private final Level world; - - public LaserNetHandler(LaserPipeNet net, @NotNull LaserPipeBlockEntity pipe, @Nullable Direction facing) { - this.net = net; - this.pipe = pipe; - this.facing = facing; - this.world = pipe.getLevel(); - } - - public void updateNetwork(LaserPipeNet net) { - this.net = net; - } - - private void setPipesActive() { - for (BlockPos pos : net.getAllNodes().keySet()) { - if (world.getBlockEntity(pos) instanceof LaserPipeBlockEntity laserPipe) { - laserPipe.setActive(true, 100); - } - } - } - - @Nullable - private ILaserContainer getInnerContainer() { - if (net == null || pipe == null || pipe.isInValid() || (facing == null || pipe.isBlocked(facing))) { - return null; - } - - LaserRoutePath data = net.getNetData(pipe.getPipePos(), facing); - if (data == null) { - return null; - } - - return data.getHandler(net.getLevel()); - } - - @Override - public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, boolean simulate) { - ILaserContainer handler = getInnerContainer(); - if (handler == null) return 0; - setPipesActive(); - return handler.acceptEnergyFromNetwork(side, voltage, amperage, false); - } - - @Override - public boolean inputsEnergy(Direction side) { - ILaserContainer handler = getInnerContainer(); - if (handler == null) return false; - return handler.inputsEnergy(side); - } - - @Override - public boolean outputsEnergy(Direction side) { - ILaserContainer handler = getInnerContainer(); - if (handler == null) return false; - return handler.outputsEnergy(side); - } - - @Override - public long changeEnergy(long amount) { - ILaserContainer handler = getInnerContainer(); - if (handler == null) return 0; - setPipesActive(); - return handler.changeEnergy(amount); - } - - @Override - public long getEnergyStored() { - ILaserContainer handler = getInnerContainer(); - if (handler == null) return 0; - return handler.getEnergyStored(); - } - - @Override - public long getEnergyCapacity() { - ILaserContainer handler = getInnerContainer(); - if (handler == null) return 0; - return handler.getEnergyCapacity(); - } - - @Override - public long getInputAmperage() { - return 0; - } - - @Override - public long getInputVoltage() { - return 0; - } - - public LaserPipeNet getNet() { - return net; - } - - @Override - public boolean isOneProbeHidden() { - return true; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java deleted file mode 100644 index c8cbeb8bed..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserNetWalker.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.laser; - -import com.gregtechceu.gtceu.api.capability.ILaserContainer; -import com.gregtechceu.gtceu.api.capability.ILaserRelay; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.pipenet.PipeNetWalker; -import com.gregtechceu.gtceu.common.blockentity.LaserPipeBlockEntity; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.entity.BlockEntity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class LaserNetWalker extends PipeNetWalker { - - public static final LaserRoutePath FAILED_MARKER = new LaserRoutePath(null, null, 0); - - @Nullable - public static LaserRoutePath createNetData(LaserPipeNet world, BlockPos sourcePipe, Direction faceToSourceHandler) { - try { - LaserNetWalker walker = new LaserNetWalker(world, sourcePipe, 1); - walker.sourcePipe = sourcePipe; - walker.facingToHandler = faceToSourceHandler; - walker.axis = faceToSourceHandler.getAxis(); - walker.traversePipeNet(); - return walker.routePath; - } catch (Exception e) { - return FAILED_MARKER; - } - } - - private static final Direction[] X_AXIS_FACINGS = { Direction.WEST, Direction.EAST }; - private static final Direction[] Y_AXIS_FACINGS = { Direction.UP, Direction.DOWN }; - private static final Direction[] Z_AXIS_FACINGS = { Direction.NORTH, Direction.SOUTH }; - - private LaserRoutePath routePath; - private BlockPos sourcePipe; - private Direction facingToHandler; - private Direction.Axis axis; - - protected LaserNetWalker(LaserPipeNet world, BlockPos sourcePipe, int distance) { - super(world, sourcePipe, distance); - } - - @NotNull - @Override - protected PipeNetWalker createSubWalker(LaserPipeNet net, - Direction direction, - BlockPos nextPos, - int walkedBlocks) { - LaserNetWalker walker = new LaserNetWalker(net, nextPos, walkedBlocks); - walker.facingToHandler = facingToHandler; - walker.sourcePipe = sourcePipe; - walker.axis = axis; - return walker; - } - - @Override - protected Class getBasePipeClass() { - return LaserPipeBlockEntity.class; - } - - @Override - protected void checkPipe(LaserPipeBlockEntity pipeTile, BlockPos pos) {} - - @Override - protected Direction[] getSurroundingPipeSides() { - return switch (axis) { - case X -> X_AXIS_FACINGS; - case Y -> Y_AXIS_FACINGS; - case Z -> Z_AXIS_FACINGS; - }; - } - - @Override - protected void checkNeighbour(LaserPipeBlockEntity pipeNode, BlockPos pipePos, Direction faceToNeighbour, - @org.jetbrains.annotations.Nullable BlockEntity neighbourTile) { - if (neighbourTile == null || (pipePos.equals(sourcePipe) && faceToNeighbour == facingToHandler)) { - return; - } - - if (((LaserNetWalker) root).routePath == null) { - ILaserRelay handler = neighbourTile - .getCapability(GTCapability.CAPABILITY_LASER, faceToNeighbour.getOpposite()).resolve().orElse(null); - if (handler != null) { - ((LaserNetWalker) root).routePath = new LaserRoutePath(pipePos.immutable(), faceToNeighbour, - getWalkedBlocks()); - stop(); - } - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java deleted file mode 100644 index de5e6d58f9..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeNet.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.laser; - -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.ILaserContainer; -import com.gregtechceu.gtceu.api.capability.ILaserRelay; -import com.gregtechceu.gtceu.api.pipenet.IAttachData; -import com.gregtechceu.gtceu.api.pipenet.PipeNet; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.level.Level; - -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import lombok.AllArgsConstructor; -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Map; - -public class LaserPipeNet extends PipeNet { - - private final Map netData = new Object2ObjectOpenHashMap<>(); - - public LaserPipeNet(LevelLaserPipeNet world) { - super(world); - } - - @Nullable - public LaserRoutePath getNetData(BlockPos pipePos, Direction facing) { - LaserRoutePath data = netData.get(pipePos); - if (data == null) { - data = LaserNetWalker.createNetData(this, pipePos, facing); - if (data == LaserNetWalker.FAILED_MARKER) { - // walker failed, don't cache, so it tries again on next insertion - return null; - } - - netData.put(pipePos, data); - } - return data; - } - - @Override - public void onNeighbourUpdate(BlockPos fromPos) { - netData.clear(); - } - - @Override - public void onPipeConnectionsUpdate() { - netData.clear(); - } - - @Override - protected void writeNodeData(LaserPipeProperties laserPipeProperties, CompoundTag compoundTag) {} - - @Override - protected LaserPipeProperties readNodeData(CompoundTag tagCompound) { - return LaserPipeProperties.INSTANCE; - } - - @AllArgsConstructor - public static class LaserData implements IAttachData { - - /** - * The current position of the pipe - */ - @Getter - private final BlockPos pipePos; - /** - * The current face to handler - */ - @Getter - private final Direction faceToHandler; - /** - * The manhattan distance traveled during walking - */ - @Getter - private final int distance; - /** - * The laser pipe properties of the current pipe - */ - @Getter - private final LaserPipeProperties properties; - @Getter - byte connections; - - @Override - public boolean canAttachTo(Direction side) { - return (connections & (1 << side.ordinal())) != 0 && side.getAxis() == this.faceToHandler.getAxis(); - } - - @Override - public boolean setAttached(Direction side, boolean attach) { - var result = canAttachTo(side); - if (result != attach) { - if (attach) { - connections |= (1 << side.ordinal()); - } else { - connections &= ~(1 << side.ordinal()); - } - } - return result != attach; - } - - /** - * @return The position of where the handler would be - */ - @NotNull - public BlockPos getHandlerPos() { - return pipePos.relative(faceToHandler); - } - - /** - * Gets the handler if it exists - * - * @param world the world to get the handler from - * @return the handler - */ - @Nullable - public ILaserRelay getHandler(@NotNull Level world) { - return GTCapabilityHelper.getLaser(world, getHandlerPos(), faceToHandler.getOpposite()); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeProperties.java deleted file mode 100644 index ec8daffb2b..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeProperties.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.laser; - -import lombok.NoArgsConstructor; - -@NoArgsConstructor -public class LaserPipeProperties { - - public static final LaserPipeProperties INSTANCE = new LaserPipeProperties(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeType.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeType.java deleted file mode 100644 index 18fafe18fb..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserPipeType.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.laser; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.pipenet.IPipeType; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.StringRepresentable; - -import java.util.Locale; - -public enum LaserPipeType implements IPipeType, StringRepresentable { - - NORMAL; - - public static final ResourceLocation TYPE_ID = GTCEu.id("laser"); - - @Override - public float getThickness() { - return 0.375f; - } - - @Override - public LaserPipeProperties modifyProperties(LaserPipeProperties baseProperties) { - return baseProperties; - } - - @Override - public boolean isPaintable() { - return true; - } - - @Override - public ResourceLocation type() { - return TYPE_ID; - } - - @Override - public String getSerializedName() { - return name().toLowerCase(Locale.ROOT); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java deleted file mode 100644 index 523e24d4a5..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LaserRoutePath.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.laser; - -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.ILaserContainer; -import com.gregtechceu.gtceu.api.capability.ILaserRelay; -import com.gregtechceu.gtceu.api.pipenet.IAttachData; -import com.gregtechceu.gtceu.api.pipenet.IRoutePath; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class LaserRoutePath implements IRoutePath, IAttachData { - - @Getter - private final BlockPos targetPipePos; - /** - * the current face to handler - */ - @NotNull - @Getter - private final Direction targetFacing; - /** - * the manhattan distance traveled during walking - */ - @Getter - private final int distance; - @Getter - byte connections; - - public LaserRoutePath(BlockPos targetPipePos, Direction targetFacing, int distance) { - this.targetPipePos = targetPipePos; - this.targetFacing = targetFacing; - this.distance = distance; - } - - /** - * Gets the handler if it exists - * - * @return the handler - */ - @Nullable - public ILaserRelay getHandler(Level level) { - return GTCapabilityHelper.getLaser(level, getTargetPipePos().relative(targetFacing), - targetFacing.getOpposite()); - } - - @Override - public boolean canAttachTo(Direction side) { - return (connections & (1 << side.ordinal())) != 0 && side.getAxis() == this.targetFacing.getAxis(); - } - - @Override - public boolean setAttached(Direction side, boolean attach) { - var result = canAttachTo(side); - if (result != attach) { - if (attach) { - connections |= (1 << side.ordinal()); - } else { - connections &= ~(1 << side.ordinal()); - } - } - return result != attach; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LevelLaserPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LevelLaserPipeNet.java deleted file mode 100644 index a7164186f9..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/laser/LevelLaserPipeNet.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.laser; - -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; - -public class LevelLaserPipeNet extends LevelPipeNet { - - private static final String DATA_ID = "gtceu_laser_pipe_net"; - - public static LevelLaserPipeNet getOrCreate(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> new LevelLaserPipeNet(serverLevel, tag), - () -> new LevelLaserPipeNet(serverLevel), DATA_ID); - } - - public LevelLaserPipeNet(ServerLevel serverLevel) { - super(serverLevel); - } - - public LevelLaserPipeNet(ServerLevel serverLevel, CompoundTag tag) { - super(serverLevel, tag); - } - - @Override - protected LaserPipeNet createNetInstance() { - return new LaserPipeNet(this); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/longdistance/LDFluidEndpointMachine.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/fluid/LDFluidEndpointMachine.java similarity index 97% rename from src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/longdistance/LDFluidEndpointMachine.java rename to src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/fluid/LDFluidEndpointMachine.java index 485c9763aa..f04942612b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/longdistance/LDFluidEndpointMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/fluid/LDFluidEndpointMachine.java @@ -1,4 +1,4 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe.longdistance; +package com.gregtechceu.gtceu.common.pipelike.longdistance.fluid; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.common.machine.storage.LongDistanceEndpointMachine; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/longdistance/LDFluidPipeType.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/fluid/LDFluidPipeType.java similarity index 86% rename from src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/longdistance/LDFluidPipeType.java rename to src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/fluid/LDFluidPipeType.java index c4ef7baeb5..3a15326b98 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/fluidpipe/longdistance/LDFluidPipeType.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/fluid/LDFluidPipeType.java @@ -1,4 +1,4 @@ -package com.gregtechceu.gtceu.common.pipelike.fluidpipe.longdistance; +package com.gregtechceu.gtceu.common.pipelike.longdistance.fluid; import com.gregtechceu.gtceu.api.pipenet.longdistance.LongDistancePipeType; import com.gregtechceu.gtceu.config.ConfigHolder; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemEndpointMachine.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/item/LDItemEndpointMachine.java similarity index 96% rename from src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemEndpointMachine.java rename to src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/item/LDItemEndpointMachine.java index 4239e180fd..df84737003 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemEndpointMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/item/LDItemEndpointMachine.java @@ -1,4 +1,4 @@ -package com.gregtechceu.gtceu.common.pipelike.item.longdistance; +package com.gregtechceu.gtceu.common.pipelike.longdistance.item; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.common.machine.storage.LongDistanceEndpointMachine; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemPipeType.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/item/LDItemPipeType.java similarity index 87% rename from src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemPipeType.java rename to src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/item/LDItemPipeType.java index cedcb69abf..d45e3c200e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/item/longdistance/LDItemPipeType.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/longdistance/item/LDItemPipeType.java @@ -1,4 +1,4 @@ -package com.gregtechceu.gtceu.common.pipelike.item.longdistance; +package com.gregtechceu.gtceu.common.pipelike.longdistance.item; import com.gregtechceu.gtceu.api.pipenet.longdistance.LongDistancePipeType; import com.gregtechceu.gtceu.config.ConfigHolder; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java new file mode 100644 index 0000000000..4fc822c5f1 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java @@ -0,0 +1,151 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.fluids.FluidState; +import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; +import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttributes; +import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossResult; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.IWorldPipeNetTile; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; +import com.gregtechceu.gtceu.utils.EntityDamageUtil; +import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.core.Direction; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.resources.ResourceLocation; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import org.jetbrains.annotations.NotNull; + +import java.util.EnumMap; +import java.util.Map; + +@FunctionalInterface +public interface ContainmentFailure { + + ContainmentFailure FALLBACK = stack -> NodeLossResult.IDENTITY; + + EnumMap STATE_FAILURES = new EnumMap<>(FluidState.class); + + Map ATTRIBUTE_FAILURES = new Object2ObjectOpenHashMap<>(); + + static void registerFailure(FluidState state, ContainmentFailure failure) { + STATE_FAILURES.put(state, failure); + } + + static void registerFailure(FluidAttribute attribute, ContainmentFailure failure) { + ATTRIBUTE_FAILURES.put(attribute.getResourceLocation(), failure); + } + + static @NotNull ContainmentFailure getFailure(FluidState state) { + return STATE_FAILURES.getOrDefault(state, FALLBACK); + } + + static @NotNull ContainmentFailure getFailure(FluidAttribute attribute) { + return ATTRIBUTE_FAILURES.getOrDefault(attribute.getResourceLocation(), FALLBACK); + } + + static @NotNull ContainmentFailure getFailure(ResourceLocation attribute) { + return ATTRIBUTE_FAILURES.getOrDefault(attribute, FALLBACK); + } + + @NotNull + NodeLossResult computeLossResult(FluidStack fluid); + + static void init() { + registerFailure(FluidState.GAS, stack -> { + if (GTValues.RNG.nextInt(8) == 0) { + return new NodeLossResult(node -> { + IWorldPipeNetTile tile = node.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + tile.spawnParticles(Direction.UP, ParticleTypes.SMOKE, 7 + GTValues.RNG.nextInt(2)); + tile.dealAreaDamage(2, entity -> EntityDamageUtil.applyTemperatureDamage(entity, + FluidHelper.getTemperature(stack), 1, 10)); + } + }, MultLossOperator.TENTHS[9]); + } else { + return new NodeLossResult(node -> { + node.getNet().getLevel().removeBlock(node.getEquivalencyData(), false); + IWorldPipeNetTile tile = node.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + tile.visuallyExplode(); + tile.spawnParticles(Direction.UP, ParticleTypes.LARGE_SMOKE, 9 + GTValues.RNG.nextInt(3)); + tile.dealAreaDamage(2, entity -> EntityDamageUtil.applyTemperatureDamage(entity, + FluidHelper.getTemperature(stack), 1.5f, 15)); + } + }, MultLossOperator.TENTHS[2]); + } + }); + registerFailure(FluidState.LIQUID, stack -> new NodeLossResult(node -> { + IWorldPipeNetTile tile = node.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + for (Direction facing : Direction.Plane.HORIZONTAL) { + int particles = GTValues.RNG.nextInt(5); + if (particles != 0) { + tile.spawnParticles(facing, ParticleTypes.DRIPPING_WATER, particles); + } + } + tile.dealAreaDamage(1, entity -> EntityDamageUtil.applyTemperatureDamage(entity, + FluidHelper.getTemperature(stack), 2f, 20)); + } + }, MultLossOperator.TENTHS[6])); + registerFailure(FluidState.PLASMA, stack -> { + if (GTValues.RNG.nextInt(4) == 0) { + return new NodeLossResult(node -> { + IWorldPipeNetTile tile = node.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + tile.spawnParticles(Direction.UP, ParticleTypes.SMOKE, 1 + GTValues.RNG.nextInt(2)); + tile.dealAreaDamage(3, entity -> EntityDamageUtil.applyTemperatureDamage(entity, + FluidHelper.getTemperature(stack), 1, 25)); + } + }, MultLossOperator.TENTHS[8]); + } else { + return new NodeLossResult(node -> { + node.getNet().getLevel().removeBlock(node.getEquivalencyData(), false); + IWorldPipeNetTile tile = node.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + tile.visuallyExplode(); + tile.spawnParticles(Direction.UP, ParticleTypes.LARGE_SMOKE, 3 + GTValues.RNG.nextInt(3)); + tile.dealAreaDamage(3, entity -> EntityDamageUtil.applyTemperatureDamage(entity, + FluidHelper.getTemperature(stack), 1.5f, 30)); + } + }, MultLossOperator.TENTHS[2]); + } + }); + registerFailure(FluidAttributes.ACID, stack -> { + if (GTValues.RNG.nextInt(10) == 0) { + return new NodeLossResult(node -> { + IWorldPipeNetTile tile = node.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + boolean gaseous = stack.getFluid().getFluidType().isLighterThanAir(); + tile.spawnParticles(gaseous ? Direction.UP : Direction.DOWN, ParticleTypes.CRIT, + 3 + GTValues.RNG.nextInt(2)); + tile.dealAreaDamage(gaseous ? 2 : 1, + entity -> EntityDamageUtil.applyChemicalDamage(entity, gaseous ? 2 : 3)); + } + }, MultLossOperator.TENTHS[9]); + } else { + return new NodeLossResult(node -> { + node.getNet().getLevel().removeBlock(node.getEquivalencyData(), false); + IWorldPipeNetTile tile = node.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + boolean gaseous = stack.getFluid().getFluidType().isLighterThanAir(); + for (Direction facing : Direction.Plane.HORIZONTAL) { + tile.spawnParticles(facing, ParticleTypes.CRIT, 3 + GTValues.RNG.nextInt(2)); + } + tile.spawnParticles(gaseous ? Direction.UP : Direction.DOWN, ParticleTypes.CRIT, + 6 + GTValues.RNG.nextInt(4)); + tile.dealAreaDamage(gaseous ? 2 : 1, + entity -> EntityDamageUtil.applyChemicalDamage(entity, gaseous ? 3 : 4)); + } + }, MultLossOperator.EIGHTHS[6]); + } + }); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java new file mode 100644 index 0000000000..c57a53f8e4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java @@ -0,0 +1,303 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.logic.ChannelCountLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseData; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseDataProvider; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; +import lombok.Getter; +import lombok.Setter; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumMap; +import java.util.Iterator; +import java.util.function.LongConsumer; + +public class FluidCapabilityObject implements IPipeCapabilityObject, IFluidTransfer, + IFluidTraverseGuideProvider { + + private final WorldPipeNet net; + @Getter @Setter + private @Nullable PipeBlockEntity tile; + @Getter + private final int tanks; + + private final EnumMap wrappers = new EnumMap<>(Direction.class); + private final WorldPipeNetNode node; + + private boolean transferring = false; + + public FluidCapabilityObject(@NotNull N net, + WorldPipeNetNode node) { + this.net = net; + this.node = node; + this.tanks = node.getData().getLogicEntryDefaultable(ChannelCountLogic.INSTANCE) + .getValue(); + for (Direction facing : GTUtil.DIRECTIONS) { + AbstractNetFlowEdge edge = (AbstractNetFlowEdge) net.getNewEdge(); + edge.setData(NetLogicData.union(node.getData(), (NetLogicData) null)); + wrappers.put(facing, new Wrapper(facing, edge)); + } + } + + private FlowWorldPipeNetPath.Provider getProvider() { + return (FlowWorldPipeNetPath.Provider) net; + } + + private boolean inputDisallowed(Direction side) { + if (side == null) return false; + if (tile == null) return true; + else return tile.isBlocked(side); + } + + private Iterator getPaths(@NotNull ITraverseData data) { + assert tile != null; + return getProvider().getPaths(net.getNode(tile.getBlockPos()), data.getTestObject(), data.getSimulatorKey(), + data.getQueryTick()); + } + + @Override + public Capability[] getCapabilities() { + return WorldFluidNet.CAPABILITIES; + } + + @Override + public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { + if (capability == ForgeCapabilities.FLUID_HANDLER) { + return ForgeCapabilities.FLUID_HANDLER.orEmpty(capability, facing == null ? + LazyOptional.of(() -> FluidTransferHelperImpl.toFluidHandler(this)) : + LazyOptional.of(() -> FluidTransferHelperImpl.toFluidHandler(wrappers.get(facing)))); + } + return null; + } + + @Override + public long fill(int tank, FluidStack resource, boolean simulate, boolean notifyChanges) { + return fill(resource, simulate, null); + } + + public int fill(FluidStack resource, boolean simulate, Direction side) { + if (this.transferring) return 0; + this.transferring = true; + + var guide = getGuide(FluidTraverseData::new, new FluidTestObject(resource), resource.getAmount(), simulate, side); + if (guide == null) return 0; + int accepted = (int) TraverseHelpers.traverseFlood(guide.getData(), guide.getPaths(), guide.getFlow()); + guide.reportConsumedFlow(accepted); + + this.transferring = false; + return accepted; + } + + @NotNull + @Override + public FluidStack drain(int tank, FluidStack resource, boolean simulate, boolean notifyChanges) { + return FluidStack.empty(); + } + + @Override + public @Nullable < + D extends ITraverseData> TraverseGuide getGuide( + TraverseDataProvider provider, + FluidTestObject testObject, + long flow, + boolean simulate) { + return getGuide(provider, testObject, flow, simulate, null); + } + + public @Nullable < + D extends ITraverseData> TraverseGuide getGuide( + TraverseDataProvider provider, + FluidTestObject testObject, + long flow, + boolean simulate, + Direction side) { + if (tile == null || inputDisallowed(side)) return null; + SimulatorKey simulator = simulate ? SimulatorKey.getNewSimulatorInstance() : null; + long tick = Platform.getMinecraftServer().getTickCount(); + D data = provider.of(net, testObject, simulator, tick, tile.getBlockPos(), side); + + LongConsumer flowReport = null; + Wrapper wrapper = this.wrappers.get(side); + if (wrapper != null) { + AbstractNetFlowEdge internalBuffer = wrapper.getBuffer(); + if (internalBuffer != null) { + long limit = internalBuffer.getFlowLimit(testObject, net, tick, simulator); + if (limit <= 0) { + this.transferring = false; + return null; + } + flow = Math.min(limit, flow); + flowReport = l -> data.consumeFlowLimit(internalBuffer, node, l); + } + } + return new TraverseGuide<>(data, () -> getPaths(data), flow, flowReport); + } + + @NotNull + @Override + public FluidStack drain(long maxDrain, boolean simulate, boolean notifyChanges) { + return FluidStack.empty(); + } + + @NotNull + @Override + public Object createSnapshot() { + return null; + } + + @Override + public void restoreFromSnapshot(Object snapshot) { + + } + + @NotNull + @Override + public FluidStack drain(FluidStack resource, boolean simulate, boolean notifyChanges) { + return FluidStack.empty(); + } + + @NotNull + @Override + public FluidStack getFluidInTank(int tank) { + return FluidStack.empty(); + } + + @Override + public void setFluidInTank(int tank, @NotNull FluidStack fluidStack) { + + } + + @Override + public long getTankCapacity(int tank) { + return Long.MAX_VALUE; + } + + @Override + public boolean isFluidValid(int tank, @NotNull FluidStack stack) { + return false; + } + + @Override + public boolean supportsFill(int tank) { + return true; + } + + @Override + public boolean supportsDrain(int tank) { + return false; + } + + protected class Wrapper implements IFluidTransfer, IFluidTraverseGuideProvider { + + private final Direction facing; + @Getter + private final AbstractNetFlowEdge buffer; + + public Wrapper(Direction facing, AbstractNetFlowEdge buffer) { + this.facing = facing; + this.buffer = buffer; + } + + @Override + public @Nullable < + D extends ITraverseData> TraverseGuide getGuide( + TraverseDataProvider provider, + FluidTestObject testObject, + long flow, + boolean simulate) { + return FluidCapabilityObject.this.getGuide(provider, testObject, flow, simulate, facing); + } + + @Override + public int getTanks() { + return FluidCapabilityObject.this.tanks; + } + + @Override + public long fill(int tank, FluidStack resource, boolean simulate, boolean notifyChanges) { + return FluidCapabilityObject.this.fill(resource, simulate, facing); + } + + @NotNull + @Override + public FluidStack drain(long maxDrain, boolean simulate, boolean notifyChanges) { + return FluidStack.empty(); + } + + @NotNull + @Override + public FluidStack drain(FluidStack resource, boolean simulate, boolean notifyChanges) { + return FluidStack.empty(); + } + + @NotNull + @Override + public FluidStack drain(int tank, FluidStack resource, boolean simulate, boolean notifyChanges) { + return FluidStack.empty(); + } + + // Unused. + @NotNull + @Override + public Object createSnapshot() { + return new Object(); + } + + // Unused. + @Override + public void restoreFromSnapshot(Object snapshot) { + + } + + @NotNull + @Override + public FluidStack getFluidInTank(int tank) { + return FluidStack.empty(); + } + + @Override + public void setFluidInTank(int tank, @NotNull FluidStack fluidStack) { + + } + + @Override + public long getTankCapacity(int tank) { + return (int) Math.min(Integer.MAX_VALUE, buffer.getThroughput()); + } + + @Override + public boolean isFluidValid(int tank, @NotNull FluidStack stack) { + return true; + } + + @Override + public boolean supportsFill(int tank) { + return true; + } + + @Override + public boolean supportsDrain(int tank) { + return false; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java new file mode 100644 index 0000000000..851b04a0d0 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java @@ -0,0 +1,149 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.fluids.FluidState; +import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.utils.GTUtil; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.BitSet; +import java.util.Collection; +import java.util.EnumSet; +import java.util.Set; + +public final class FluidContainmentLogic extends NetLogicEntry { + + public static final FluidContainmentLogic INSTANCE = new FluidContainmentLogic().contain(FluidState.LIQUID); + + private int maximumTemperature; + + private final Set containableAttributes = new ObjectOpenHashSet<>(); + private @NotNull EnumSet containableStates = EnumSet.noneOf(FluidState.class); + + public FluidContainmentLogic() { + super("FluidContainment"); + } + + public @NotNull FluidContainmentLogic getWith(Collection states, + @NotNull Collection attributes, + int maximumTemperature) { + FluidContainmentLogic logic = getNew(); + logic.containableStates.addAll(states); + for (FluidAttribute attribute : attributes) { + logic.contain(attribute); + } + logic.maximumTemperature = maximumTemperature; + return logic; + } + + @Contract("_ -> this") + public FluidContainmentLogic contain(FluidState state) { + this.containableStates.add(state); + return this; + } + + @Contract("_ -> this") + public FluidContainmentLogic contain(@NotNull FluidAttribute attribute) { + this.containableAttributes.add(attribute.getResourceLocation()); + return this; + } + + @Contract("_ -> this") + public FluidContainmentLogic notContain(FluidState state) { + this.containableStates.remove(state); + return this; + } + + @Contract("_ -> this") + public FluidContainmentLogic notContain(@NotNull FluidAttribute attribute) { + this.containableAttributes.remove(attribute.getResourceLocation()); + return this; + } + + public boolean contains(FluidState state) { + return this.containableStates.contains(state); + } + + public boolean contains(@NotNull FluidAttribute attribute) { + return this.containableAttributes.contains(attribute.getResourceLocation()); + } + + public void setMaximumTemperature(int maximumTemperature) { + this.maximumTemperature = maximumTemperature; + } + + public int getMaximumTemperature() { + return maximumTemperature; + } + + @Override + public @Nullable FluidContainmentLogic union(NetLogicEntry other) { + if (other instanceof FluidContainmentLogic logic) { + if (this.containableAttributes.equals(logic.containableAttributes) && + this.containableStates.equals(logic.containableStates)) { + return this; + } else { + FluidContainmentLogic returnable = getNew(); + returnable.containableStates = EnumSet.copyOf(this.containableStates); + returnable.containableStates.retainAll(logic.containableStates); + returnable.containableAttributes.addAll(this.containableAttributes); + returnable.containableAttributes.retainAll(logic.containableAttributes); + return returnable; + } + } + return this; + } + + @Override + public CompoundTag serializeNBT() { + CompoundTag tag = new CompoundTag(); + ListTag list = new ListTag(); + for (ResourceLocation loc : containableAttributes) { + list.add(StringTag.valueOf(loc.toString())); + } + tag.put("Attributes", list); + tag.putByteArray("States", GTUtil.setToMask(containableStates).toByteArray()); + return tag; + } + + @Override + public void deserializeNBT(CompoundTag nbt) { + ListTag list = nbt.getList("Attributes", Tag.TAG_STRING); + for (int i = 0; i < list.size(); i++) { + containableAttributes.add(new ResourceLocation(list.getString(i))); + } + containableStates = GTUtil.maskToSet(FluidState.class, BitSet.valueOf(nbt.getByteArray("States"))); + } + + @Override + public @NotNull FluidContainmentLogic getNew() { + return new FluidContainmentLogic(); + } + + @Override + public void encode(FriendlyByteBuf buf, boolean fullChange) { + buf.writeVarInt(containableAttributes.size()); + for (ResourceLocation loc : containableAttributes) { + buf.writeUtf(loc.toString()); + } + buf.writeByteArray(GTUtil.setToMask(containableStates).toByteArray()); + } + + @Override + public void decode(FriendlyByteBuf buf, boolean fullChange) { + int attributes = buf.readVarInt(); + for (int i = 0; i < attributes; i++) { + containableAttributes.add(new ResourceLocation(buf.readUtf(255))); + } + containableStates = GTUtil.maskToSet(FluidState.class, BitSet.valueOf(buf.readByteArray(255))); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java new file mode 100644 index 0000000000..4ed3e192f5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java @@ -0,0 +1,64 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.IEqualizableTraverseData; +import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; +import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraftforge.fluids.capability.IFluidHandler; +import org.jetbrains.annotations.NotNull; + +public class FluidEQTraverseData extends FluidTraverseData + implements IEqualizableTraverseData { + + protected int destCount; + protected long maxMinFlow; + + public FluidEQTraverseData(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + protected void compute(@NotNull WorldPipeNetNode destination) { + this.destCount = 0; + this.maxMinFlow = 0; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IFluidTransfer container = FluidTransferHelper.getFluidTransfer(capability.getValue().getLevel(), + capability.getValue().getBlockPos(), capability.getKey().getOpposite()); + if (container != null) { + if (destCount == 0) maxMinFlow = Integer.MAX_VALUE; + destCount += 1; + maxMinFlow = Math.min(maxMinFlow, + IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + Integer.MAX_VALUE, + container, false)); + } + } + } + + @Override + public int getDestinationsAtNode(@NotNull WorldPipeNetNode node) { + return destCount; + } + + @Override + public boolean shouldSkipPath(@NotNull FlowWorldPipeNetPath path) { + compute(path.getTargetNode()); + return maxMinFlow == 0; + } + + @Override + public long getMaxFlowToLeastDestination(@NotNull WorldPipeNetNode destination) { + return maxMinFlow; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java new file mode 100644 index 0000000000..bb035fce34 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java @@ -0,0 +1,63 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinTraverseData; +import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.fluids.capability.IFluidHandler; +import org.jetbrains.annotations.NotNull; + +public class FluidRRTraverseData extends FluidTraverseData implements + IRoundRobinTraverseData, WorldPipeNetNode, FlowWorldPipeNetPath> { + + private final Object2ObjectLinkedOpenHashMap> cache; + + public FluidRRTraverseData(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing, + @NotNull Object2ObjectLinkedOpenHashMap> cache) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + this.cache = cache; + } + + @Override + public @NotNull Object2ObjectLinkedOpenHashMap> getTraversalCache() { + return cache; + } + + @Override + public boolean shouldSkipPath(@NotNull FlowWorldPipeNetPath path) { + return false; + } + + @Override + public @NotNull SimpleTileRoundRobinData createRRData(@NotNull WorldPipeNetNode destination) { + return new SimpleTileRoundRobinData<>(ForgeCapabilities.FLUID_HANDLER); + } + + @Override + public long finalizeAtDestination(@NotNull SimpleTileRoundRobinData data, + @NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + Direction pointerFacing = data.getPointerFacing(getSimulatorKey()); + // anti insert-to-our-source logic + if (!destination.getEquivalencyData().equals(sourcePos) || !(pointerFacing == inputFacing)) { + IFluidHandler handler = data.getAtPointer(destination, getSimulatorKey()); + if (handler != null) { + IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(handler); + availableFlow -= IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(pointerFacing)).insertToHandler(getTestObject(), + (int) Math.min(Integer.MAX_VALUE, availableFlow), container, getSimulatorKey() == null); + } + } + return flowReachingDestination - availableFlow; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java new file mode 100644 index 0000000000..460a100f73 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java @@ -0,0 +1,177 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.fluids.FluidState; +import com.gregtechceu.gtceu.api.fluids.GTFluid; +import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossCache; +import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossResult; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.IWorldPipeNetTile; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.AbstractTraverseData; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; +import com.gregtechceu.gtceu.utils.EntityDamageUtil; +import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; +import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; +import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.particles.ParticleTypes; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; + +public class FluidTraverseData extends AbstractTraverseData { + + public static final float TEMPERATURE_EFFECT = 0.05f; + + static { + ContainmentFailure.init(); + } + + protected final BlockPos sourcePos; + protected final Direction inputFacing; + + protected final FluidStack stack; + protected final FluidState state; + protected final int fluidTemp; + protected final boolean gaseous; + protected final @Nullable Collection attributes; + + public FluidTraverseData(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick); + this.sourcePos = sourcePos; + this.inputFacing = inputFacing; + this.stack = testObject.recombine(); + this.state = FluidState.inferState(stack); + this.fluidTemp = FluidHelper.getTemperature(stack); + this.gaseous = stack.getFluid().getFluidType().isLighterThanAir(); + if (stack.getFluid() instanceof GTFluid at) { + attributes = at.getAttributes(); + } else attributes = null; + } + + @Override + public FluidTestObject getTestObject() { + return (FluidTestObject) super.getTestObject(); + } + + @Override + public boolean prepareForPathWalk(@NotNull FlowWorldPipeNetPath path, long flow) { + return flow <= 0; + } + + @Override + public ReversibleLossOperator traverseToNode(@NotNull WorldPipeNetNode node, long flowReachingNode) { + NodeLossCache.Key key = NodeLossCache.key(node, this); + NodeLossResult result = NodeLossCache.getLossResult(key); + if (result != null) { + return result.getLossFunction(); + } else { + FluidContainmentLogic containmentLogic = node.getData() + .getLogicEntryDefaultable(FluidContainmentLogic.INSTANCE); + + TemperatureLogic temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + if (temperatureLogic != null) { + result = temperatureLogic.getLossResult(getQueryTick()); + boolean overMax = fluidTemp > containmentLogic.getMaximumTemperature() && + !(state == FluidState.PLASMA && containmentLogic.contains(FluidState.PLASMA)); + if (overMax) { + result = NodeLossResult.combine(result, new NodeLossResult(GTValues.RNG.nextInt(4) == 0 ? pipe -> { + IWorldPipeNetTile tile = pipe.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + tile.spawnParticles(Direction.UP, ParticleTypes.CLOUD, 3 + GTValues.RNG.nextInt(2)); + tile.dealAreaDamage(gaseous ? 2 : 1, + entity -> EntityDamageUtil.applyTemperatureDamage(entity, + fluidTemp, 2.0F, 10)); + tile.setNeighborsToFire(); + } + } : pipe -> { + IWorldPipeNetTile tile = pipe.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + tile.spawnParticles(Direction.UP, ParticleTypes.CLOUD, 3 + GTValues.RNG.nextInt(2)); + tile.dealAreaDamage(gaseous ? 2 : 1, + entity -> EntityDamageUtil.applyTemperatureDamage(entity, + fluidTemp, 2.0F, 10)); + } + }, MultLossOperator.EIGHTHS[2])); + } else if (temperatureLogic.isUnderMinimum(fluidTemp)) { + result = NodeLossResult.combine(result, new NodeLossResult(pipe -> { + IWorldPipeNetTile tile = pipe.getBlockEntityNoLoading(); + if (tile != null) { + tile.playLossSound(); + tile.spawnParticles(Direction.UP, ParticleTypes.CLOUD, 3 + GTValues.RNG.nextInt(2)); + tile.dealAreaDamage(gaseous ? 2 : 1, + entity -> EntityDamageUtil.applyTemperatureDamage(entity, + fluidTemp, 2.0F, 10)); + } + }, MultLossOperator.EIGHTHS[2])); + } + } + + if (!containmentLogic.contains(state)) { + result = NodeLossResult.combine(result, ContainmentFailure.getFailure(state).computeLossResult(stack)); + } + + if (attributes != null) { + for (FluidAttribute attribute : attributes) { + if (!containmentLogic.contains(attribute)) { + result = NodeLossResult.combine(result, + ContainmentFailure.getFailure(attribute).computeLossResult(stack)); + } + } + } + + if (result == null) return ReversibleLossOperator.IDENTITY; + NodeLossCache.registerLossResult(key, result); + return result.getLossFunction(); + } + } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IFluidTransfer container = FluidTransferHelper.getFluidTransfer(capability.getValue().getLevel(), + capability.getValue().getBlockPos(), capability.getKey().getOpposite()); + if (container != null) { + availableFlow -= IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(Integer.MAX_VALUE, availableFlow), container, getSimulatorKey() == null); + } + } + return flowReachingDestination - availableFlow; + } + + @Override + public void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNode, + long consumption) { + super.consumeFlowLimit(edge, targetNode, consumption); + TemperatureLogic temperatureLogic = targetNode.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + if (temperatureLogic != null) { + FluidContainmentLogic containmentLogic = targetNode.getData() + .getLogicEntryDefaultable(FluidContainmentLogic.INSTANCE); + boolean overMax = fluidTemp > containmentLogic.getMaximumTemperature() && + !(state == FluidState.PLASMA && containmentLogic.contains(FluidState.PLASMA)); + temperatureLogic.moveTowardsTemperature(fluidTemp, + getQueryTick(), consumption * TEMPERATURE_EFFECT, !overMax); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java new file mode 100644 index 0000000000..f835be0693 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java @@ -0,0 +1,72 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface IFluidTransferController { + + TransferControl CONTROL = new TransferControl<>("Fluid") { + + @Override + public @NotNull IFluidTransferController get(@Nullable Object potentialHolder) { + if (!(potentialHolder instanceof TransferControlProvider holder)) return DEFAULT; + IFluidTransferController found = holder.getControllerForControl(CONTROL); + return found == null ? DEFAULT : found; + } + + @Override + public @NotNull IFluidTransferController getNoPassage() { + return NO_PASSAGE; + } + }; + + IFluidTransferController DEFAULT = new IFluidTransferController() {}; + + IFluidTransferController NO_PASSAGE = new IFluidTransferController() { + + @Override + public long insertToHandler(@NotNull FluidTestObject testObject, int amount, + @NotNull IFluidTransfer destHandler, boolean doFill) { + return 0; + } + + @Override + public @Nullable FluidStack extractFromHandler(@Nullable FluidTestObject testObject, int amount, + IFluidTransfer sourceHandler, boolean doDrain) { + return null; + } + }; + + /** + * @return the amount filled. + */ + default long insertToHandler(@NotNull FluidTestObject testObject, int amount, @NotNull IFluidTransfer destHandler, + boolean doFill) { + return destHandler.fill(testObject.recombine(amount), doFill); + } + + /** + * @return the fluidstack drained. + */ + @Nullable + default FluidStack extractFromHandler(@Nullable FluidTestObject testObject, int amount, IFluidTransfer sourceHandler, + boolean doDrain) { + if (testObject == null) return sourceHandler.drain(amount, doDrain); + else { + FluidStack recombined = testObject.recombine(); + FluidStack drained = sourceHandler.drain(recombined, false); + if (testObject.test(drained)) { + if (doDrain) { + return sourceHandler.drain(recombined, true); + } else { + return drained; + } + } else return null; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java new file mode 100644 index 0000000000..a5b5756853 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java @@ -0,0 +1,22 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseData; +import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseGuideProvider; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseDataProvider; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; +import org.jetbrains.annotations.Nullable; + +public interface IFluidTraverseGuideProvider extends + ITraverseGuideProvider { + + @Nullable + @Override + > TraverseGuide getGuide( + TraverseDataProvider provider, + FluidTestObject testObject, + long flow, + boolean simulate); +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java new file mode 100644 index 0000000000..16a692a16f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java @@ -0,0 +1,116 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.api.capability.recipe.IO; +import com.gregtechceu.gtceu.api.cover.CoverBehavior; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.alg.DynamicWeightsShortestPathsAlgorithm; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.NetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.BlockedPredicate; +import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.FilterPredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.common.cover.PumpCover; +import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; +import com.gregtechceu.gtceu.common.pipelike.net.item.WorldItemNet; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public class WorldFluidNet extends WorldPipeNet implements FlowWorldPipeNetPath.Provider { + + public static final Capability[] CAPABILITIES = new Capability[] { ForgeCapabilities.FLUID_HANDLER }; + + private static final String DATA_ID = "gtceu_world_fluid_net"; + + public static WorldFluidNet getWorldNet(ServerLevel serverLevel) { + return serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldFluidNet net = new WorldFluidNet(); + net.load(tag); + return net; + }, WorldFluidNet::new, DATA_ID); + } + + public WorldFluidNet() { + super(false, DynamicWeightsShortestPathsAlgorithm::new); + } + + @Override + public boolean supportsPredication() { + return true; + } + + @Override + protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) { + super.coverPredication(edge, a, b); + if (edge.getPredicateHandler().hasPredicate(BlockedPredicate.INSTANCE)) return; + FilterPredicate predicate = null; + if (a instanceof PumpCover filter) { + if (filter.getManualIOMode() == ManualIOMode.DISABLED) { + edge.getPredicateHandler().clearPredicates(); + edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + return; + } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && + filter.getIo() != IO.IN) { + predicate = FilterPredicate.INSTANCE.getNew(); + predicate.setSourceFilter(filter.getFilterHandler().getFilter()); + } + } + if (b instanceof PumpCover filter) { + if (filter.getManualIOMode() == ManualIOMode.DISABLED) { + edge.getPredicateHandler().clearPredicates(); + edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + return; + } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && + filter.getIo() != IO.OUT) { + if (predicate == null) predicate = FilterPredicate.INSTANCE.getNew(); + predicate.setTargetFilter(filter.getFilterHandler().getFilter()); + } + } + if (predicate != null) edge.getPredicateHandler().setPredicate(predicate); + } + + @Override + public boolean usesDynamicWeights(int algorithmID) { + return true; + } + + @Override + public boolean clashesWith(IGraphNet net) { + return net instanceof WorldItemNet; + } + + @Override + public Capability[] getTargetCapabilities() { + return CAPABILITIES; + } + + @Override + public IPipeCapabilityObject[] getNewCapabilityObjects(WorldPipeNetNode node) { + return new IPipeCapabilityObject[] { new FluidCapabilityObject(this, node) }; + } + + @Override + public Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + return backer.getPaths(node, 0, FlowWorldPipeNetPath.MAPPER, testObject, simulator, queryTick); + } + + @Override + public @NotNull NetFlowEdge getNewEdge() { + return new NetFlowEdge(10); + } + + @Override + public int getNetworkID() { + return 1; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java new file mode 100644 index 0000000000..17181b32b7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java @@ -0,0 +1,78 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; +import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.lowdragmc.lowdraglib.side.item.IItemTransfer; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.items.IItemHandler; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface IItemTransferController { + + TransferControl CONTROL = new TransferControl<>("Item") { + + @Override + public @NotNull IItemTransferController get(@Nullable Object potentialHolder) { + if (!(potentialHolder instanceof TransferControlProvider holder)) return DEFAULT; + IItemTransferController found = holder.getControllerForControl(CONTROL); + return found == null ? DEFAULT : found; + } + + @Override + public @NotNull IItemTransferController getNoPassage() { + return NO_PASSAGE; + } + }; + + IItemTransferController DEFAULT = new IItemTransferController() {}; + + IItemTransferController NO_PASSAGE = new IItemTransferController() { + + @Override + public int insertToHandler(@NotNull ItemTestObject testObject, int amount, @NotNull IItemTransfer destHandler, + boolean simulate) { + return amount; + } + + @Override + public int extractFromHandler(@NotNull ItemTestObject testObject, int amount, + @NotNull IItemTransfer sourceHandler, boolean simulate) { + return 0; + } + }; + + /** + * @return the amount left uninserted; aka the remainder + */ + default int insertToHandler(@NotNull ItemTestObject testObject, int amount, + @NotNull IItemTransfer destHandler, boolean simulate) { + int available = amount; + for (int i = 0; i < destHandler.getSlots(); i++) { + int allowed = Math.min(available, Math.min(destHandler.getSlotLimit(i), testObject.getStackLimit())); + available -= allowed - destHandler.insertItem(i, testObject.recombine(allowed), simulate).getCount(); + } + return available; + } + + /** + * @return the amount extracted + */ + default int extractFromHandler(@NotNull ItemTestObject testObject, int amount, + @NotNull IItemTransfer sourceHandler, boolean simulate) { + int extracted = 0; + for (int i = 0; i < sourceHandler.getSlots(); i++) { + ItemStack stack = sourceHandler.extractItem(i, amount - extracted, true); + if (testObject.test(stack)) { + if (simulate) { + extracted += stack.getCount(); + } else { + extracted += sourceHandler.extractItem(i, amount - extracted, false).getCount(); + } + + } + } + return extracted; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java new file mode 100644 index 0000000000..c9a437a4fa --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java @@ -0,0 +1,22 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseData; +import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseGuideProvider; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseDataProvider; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; +import org.jetbrains.annotations.Nullable; + +public interface IItemTraverseGuideProvider extends + ITraverseGuideProvider { + + @Nullable + @Override + > TraverseGuide getGuide( + TraverseDataProvider provider, + ItemTestObject testObject, + long flow, + boolean simulate); +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java new file mode 100644 index 0000000000..f23a1a37a7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java @@ -0,0 +1,251 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseData; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseDataProvider; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; +import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.side.item.IItemTransfer; +import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; +import lombok.Getter; +import lombok.Setter; +import net.minecraft.core.Direction; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumMap; +import java.util.Iterator; +import java.util.function.LongConsumer; + +public class ItemCapabilityObject implements IPipeCapabilityObject, IItemTransfer, IItemTraverseGuideProvider { + + private final WorldPipeNet net; + @Setter + private @Nullable PipeBlockEntity tile; + + private final EnumMap wrappers = new EnumMap<>(Direction.class); + private final WorldPipeNetNode node; + + private boolean transferring = false; + + public ItemCapabilityObject(@NotNull N net, + WorldPipeNetNode node) { + this.net = net; + this.node = node; + for (Direction facing : GTUtil.DIRECTIONS) { + AbstractNetFlowEdge edge = (AbstractNetFlowEdge) net.getNewEdge(); + edge.setData(NetLogicData.union(node.getData(), (NetLogicData) null)); + wrappers.put(facing, new Wrapper(facing, edge)); + } + } + + private FlowWorldPipeNetPath.Provider getProvider() { + return (FlowWorldPipeNetPath.Provider) net; + } + + private boolean inputDisallowed(Direction side) { + if (side == null) return false; + if (tile == null) return true; + else return tile.isBlocked(side); + } + + private Iterator getPaths(@NotNull ITraverseData data) { + assert tile != null; + return getProvider().getPaths(net.getNode(tile.getBlockPos()), data.getTestObject(), data.getSimulatorKey(), + data.getQueryTick()); + } + + @Override + public Capability[] getCapabilities() { + return WorldItemNet.CAPABILITIES; + } + + @Override + public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { + if (capability == ForgeCapabilities.ITEM_HANDLER) { + return ForgeCapabilities.ITEM_HANDLER.orEmpty(capability, facing == null ? + LazyOptional.of(() -> ItemTransferHelperImpl.toItemHandler(this)) : + LazyOptional.of(() -> ItemTransferHelperImpl.toItemHandler(wrappers.get(facing)))); + } + return null; + } + + public @NotNull ItemStack insertItem(@NotNull ItemStack stack, boolean simulate, boolean notifyChanges, Direction side) { + if (this.transferring) return stack; + this.transferring = true; + + var guide = getGuide(ItemTraverseData::new, new ItemTestObject(stack), stack.getCount(), simulate, side); + if (guide == null) return stack; + int consumed = (int) TraverseHelpers.traverseFlood(guide.getData(), guide.getPaths(), guide.getFlow()); + guide.reportConsumedFlow(consumed); + + this.transferring = false; + return guide.getData().getTestObject().recombine(stack.getCount() - consumed); + } + + @Nullable + @Override + public > TraverseGuide getGuide( + TraverseDataProvider provider, + ItemTestObject testObject, + long flow, + boolean simulate) { + return getGuide(provider, testObject, flow, simulate, null); + } + + @Nullable + protected < + D extends ITraverseData> TraverseGuide getGuide( + TraverseDataProvider provider, + ItemTestObject testObject, + long flow, + boolean simulate, + Direction side) { + if (tile == null || inputDisallowed(side)) return null; + + SimulatorKey simulator = simulate ? SimulatorKey.getNewSimulatorInstance() : null; + long tick = Platform.getMinecraftServer().getTickCount(); + D data = provider.of(net, testObject, simulator, tick, tile.getBlockPos(), side); + + LongConsumer flowReport = null; + Wrapper wrapper = this.wrappers.get(side); + if (wrapper != null) { + AbstractNetFlowEdge internalBuffer = wrapper.getBuffer(); + if (internalBuffer != null) { + long limit = internalBuffer.getFlowLimit(testObject, net, tick, simulator); + if (limit <= 0) { + this.transferring = false; + return null; + } + flow = Math.min(limit, flow); + flowReport = l -> data.consumeFlowLimit(internalBuffer, node, l); + } + } + return new TraverseGuide<>(data, () -> getPaths(data), flow, flowReport); + } + + @Override + public int getSlots() { + return 1; + } + + @Override + public @NotNull ItemStack getStackInSlot(int slot) { + return ItemStack.EMPTY; + } + + @Override + public @NotNull ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate, boolean notifyChanges) { + return insertItem(stack, simulate, notifyChanges, null); + } + + @NotNull + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate, boolean notifyChanges) { + return ItemStack.EMPTY; + } + + @Override + public int getSlotLimit(int slot) { + return 64; + } + + @Override + public boolean isItemValid(int slot, @NotNull ItemStack stack) { + return false; + } + + // Unused + @NotNull + @Override + public Object createSnapshot() { + return new Object(); + } + + // Unused + @Override + public void restoreFromSnapshot(Object snapshot) { + + } + + protected class Wrapper implements IItemTransfer, IItemTraverseGuideProvider { + + private final Direction facing; + @Getter + private final AbstractNetFlowEdge buffer; + + public Wrapper(Direction facing, AbstractNetFlowEdge buffer) { + this.facing = facing; + this.buffer = buffer; + } + + @Nullable + @Override + public > TraverseGuide getGuide( + TraverseDataProvider provider, + ItemTestObject testObject, + long flow, + boolean simulate) { + return ItemCapabilityObject.this.getGuide(provider, testObject, flow, simulate, facing); + } + + @Override + public int getSlots() { + return 1; + } + + @Override + public @NotNull ItemStack getStackInSlot(int slot) { + return ItemStack.EMPTY; + } + + @NotNull + @Override + public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate, boolean notifyChanges) { + return ItemCapabilityObject.this.insertItem(stack, simulate, notifyChanges, facing); + } + + @NotNull + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate, boolean notifyChanges) { + return ItemStack.EMPTY; + } + + @Override + public int getSlotLimit(int slot) { + return 64; + } + + @Override + public boolean isItemValid(int slot, @NotNull ItemStack stack) { + return false; + } + + // Unused + @NotNull + @Override + public Object createSnapshot() { + return new Object(); + } + + // Unused + @Override + public void restoreFromSnapshot(Object snapshot) { + + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java new file mode 100644 index 0000000000..64d0dc9527 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java @@ -0,0 +1,66 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.IEqualizableTraverseData; +import com.lowdragmc.lowdraglib.side.item.IItemTransfer; +import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.items.IItemHandler; +import org.jetbrains.annotations.NotNull; + +public class ItemEQTraverseData extends ItemTraverseData + implements IEqualizableTraverseData { + + protected int destCount; + protected int maxMinFlow; + + public ItemEQTraverseData(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + protected void compute(@NotNull WorldPipeNetNode destination) { + this.destCount = 0; + this.maxMinFlow = 0; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IItemHandler cap = capability.getValue() + .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + if (cap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(cap); + if (destCount == 0) maxMinFlow = Integer.MAX_VALUE; + destCount += 1; + int test = Integer.MAX_VALUE; + maxMinFlow = Math.min(maxMinFlow, test - + IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), test, + container, true)); + } + } + } + + @Override + public int getDestinationsAtNode(@NotNull WorldPipeNetNode node) { + return destCount; + } + + @Override + public boolean shouldSkipPath(@NotNull FlowWorldPipeNetPath path) { + compute(path.getTargetNode()); + return maxMinFlow == 0; + } + + @Override + public long getMaxFlowToLeastDestination(@NotNull WorldPipeNetNode destination) { + return maxMinFlow; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java new file mode 100644 index 0000000000..13fc0ec9ab --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java @@ -0,0 +1,64 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinTraverseData; +import com.lowdragmc.lowdraglib.side.item.IItemTransfer; +import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.items.IItemHandler; +import org.jetbrains.annotations.NotNull; + +public class ItemRRTraverseData extends ItemTraverseData implements + IRoundRobinTraverseData, WorldPipeNetNode, FlowWorldPipeNetPath> { + + private final Object2ObjectLinkedOpenHashMap> cache; + + public ItemRRTraverseData(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing, + @NotNull Object2ObjectLinkedOpenHashMap> cache) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + this.cache = cache; + } + + @Override + public @NotNull Object2ObjectLinkedOpenHashMap> getTraversalCache() { + return cache; + } + + @Override + public boolean shouldSkipPath(@NotNull FlowWorldPipeNetPath path) { + return false; + } + + @Override + public @NotNull SimpleTileRoundRobinData createRRData(@NotNull WorldPipeNetNode destination) { + return new SimpleTileRoundRobinData<>(ForgeCapabilities.ITEM_HANDLER); + } + + @Override + public long finalizeAtDestination(@NotNull SimpleTileRoundRobinData data, + @NotNull WorldPipeNetNode destination, + long flowReachingDestination) { + long availableFlow = flowReachingDestination; + Direction pointerFacing = data.getPointerFacing(getSimulatorKey()); + if (destination.getEquivalencyData().equals(sourcePos) && pointerFacing == inputFacing) + return 0; // anti insert-to-our-source logic + + IItemHandler cap = data.getAtPointer(destination, getSimulatorKey()); + if (cap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(cap); + availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(pointerFacing)).insertToHandler(getTestObject(), + (int) Math.min(Integer.MAX_VALUE, availableFlow), container, getSimulatorKey() != null); + } + return flowReachingDestination - availableFlow; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java new file mode 100644 index 0000000000..91c5f33ef3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java @@ -0,0 +1,64 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.AbstractTraverseData; +import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; +import com.lowdragmc.lowdraglib.side.item.IItemTransfer; +import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.items.IItemHandler; +import org.jetbrains.annotations.NotNull; + +public class ItemTraverseData extends AbstractTraverseData { + + protected final BlockPos sourcePos; + protected final Direction inputFacing; + + public ItemTraverseData(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick); + this.sourcePos = sourcePos; + this.inputFacing = inputFacing; + } + + @Override + public ItemTestObject getTestObject() { + return (ItemTestObject) super.getTestObject(); + } + + @Override + public boolean prepareForPathWalk(@NotNull FlowWorldPipeNetPath path, long flow) { + return flow <= 0; + } + + @Override + public ReversibleLossOperator traverseToNode(@NotNull WorldPipeNetNode node, long flowReachingNode) { + return ReversibleLossOperator.IDENTITY; + } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IItemHandler cap = capability.getValue() + .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + if (cap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(cap); + availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(Integer.MAX_VALUE, availableFlow), container, getSimulatorKey() != null); + } + } + return flowReachingDestination - availableFlow; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java new file mode 100644 index 0000000000..af188c5d8d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java @@ -0,0 +1,118 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.api.capability.recipe.IO; +import com.gregtechceu.gtceu.api.cover.CoverBehavior; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.alg.DynamicWeightsShortestPathsAlgorithm; +import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.NetFlowEdge; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.BlockedPredicate; +import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.FilterPredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.common.cover.ConveyorCover; +import com.gregtechceu.gtceu.common.cover.data.ItemFilterMode; +import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.WorldFluidNet; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public class WorldItemNet extends WorldPipeNet implements FlowWorldPipeNetPath.Provider { + + public static final Capability[] CAPABILITIES = new Capability[] { + ForgeCapabilities.ITEM_HANDLER }; + + private static final String DATA_ID = "gtceu_world_item_net"; + + public static WorldItemNet getWorldNet(ServerLevel serverLevel) { + return serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldItemNet net = new WorldItemNet(); + net.load(tag); + return net; + }, WorldItemNet::new, DATA_ID); + } + + public WorldItemNet() { + super(false, DynamicWeightsShortestPathsAlgorithm::new); + } + + @Override + public boolean supportsPredication() { + return true; + } + + @Override + protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) { + super.coverPredication(edge, a, b); + if (edge.getPredicateHandler().hasPredicate(BlockedPredicate.INSTANCE)) return; + FilterPredicate predicate = null; + if (a instanceof ConveyorCover filter) { + if (filter.getManualIOMode() == ManualIOMode.DISABLED) { + edge.getPredicateHandler().clearPredicates(); + edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + return; + } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && + filter.getIo() != IO.IN) { + predicate = FilterPredicate.INSTANCE.getNew(); + predicate.setSourceFilter(filter.getFilterHandler().getFilter()); + } + } + if (b instanceof ConveyorCover filter) { + if (filter.getManualIOMode() == ManualIOMode.DISABLED) { + edge.getPredicateHandler().clearPredicates(); + edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + return; + } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && + filter.getIo() != IO.OUT) { + if (predicate == null) predicate = FilterPredicate.INSTANCE.getNew(); + predicate.setTargetFilter(filter.getFilterHandler().getFilter()); + } + } + if (predicate != null) edge.getPredicateHandler().setPredicate(predicate); + } + + @Override + public boolean usesDynamicWeights(int algorithmID) { + return true; + } + + @Override + public boolean clashesWith(IGraphNet net) { + return net instanceof WorldFluidNet; + } + + @Override + public Capability[] getTargetCapabilities() { + return CAPABILITIES; + } + + @Override + public IPipeCapabilityObject[] getNewCapabilityObjects(WorldPipeNetNode node) { + return new IPipeCapabilityObject[] { new ItemCapabilityObject(this, node) }; + } + + @Override + public Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + return backer.getPaths(node, 0, FlowWorldPipeNetPath.MAPPER, testObject, simulator, queryTick); + } + + @Override + public @NotNull NetFlowEdge getNewEdge() { + return new NetFlowEdge(2, 5); + } + + @Override + public int getNetworkID() { + return 2; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java index 24e12d07d6..e9fa2fb375 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java @@ -96,7 +96,7 @@ public static void generateGTDynamicTags(Map { MixinHelpers.addMaterialBlockTags(tagMap, prefix, map); }); - GTBlocks.FLUID_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { + GTBlocks.MATERIAL_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { MixinHelpers.addMaterialBlockTags(tagMap, prefix, map); }); GTBlocks.ITEM_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { @@ -246,7 +246,7 @@ public static void generateGTDynamicLoot(Map lootTa GTBlocks.CABLE_BLOCKS.rowMap().forEach((prefix, map) -> { MixinHelpers.addMaterialBlockLootTables(lootTables, prefix, map); }); - GTBlocks.FLUID_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { + GTBlocks.MATERIAL_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { MixinHelpers.addMaterialBlockLootTables(lootTables, prefix, map); }); GTBlocks.ITEM_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/CraftingComponent.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/CraftingComponent.java index 3af900c254..8672ff1623 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/CraftingComponent.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/CraftingComponent.java @@ -428,42 +428,42 @@ public static void initializeComponents() { PIPE_NORMAL = new Component(Stream.of(new Object[][] { - { 0, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Bronze) }, - { 1, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Bronze) }, - { 2, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Steel) }, - { 3, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.StainlessSteel) }, - { 4, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Titanium) }, - { 5, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.TungstenSteel) }, - { 6, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.NiobiumTitanium) }, - { 7, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Iridium) }, - { 8, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Naquadah) }, - { FALLBACK, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Naquadah) }, + { 0, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Bronze) }, + { 1, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Bronze) }, + { 2, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Steel) }, + { 3, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.StainlessSteel) }, + { 4, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Titanium) }, + { 5, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.TungstenSteel) }, + { 6, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.NiobiumTitanium) }, + { 7, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Iridium) }, + { 8, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Naquadah) }, + { FALLBACK, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Naquadah) }, }).collect(Collectors.toMap(data -> (Integer) data[0], data -> data[1]))); PIPE_LARGE = new Component(Stream.of(new Object[][] { - { 0, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Bronze) }, - { 1, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Bronze) }, - { 2, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Steel) }, - { 3, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.StainlessSteel) }, - { 4, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Titanium) }, - { 5, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.TungstenSteel) }, - { 6, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.NiobiumTitanium) }, - { 7, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Ultimet) }, - { 8, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Naquadah) }, - { FALLBACK, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Neutronium) }, + { 0, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Bronze) }, + { 1, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Bronze) }, + { 2, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Steel) }, + { 3, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.StainlessSteel) }, + { 4, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Titanium) }, + { 5, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.TungstenSteel) }, + { 6, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.NiobiumTitanium) }, + { 7, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Ultimet) }, + { 8, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Naquadah) }, + { FALLBACK, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Neutronium) }, }).collect(Collectors.toMap(data -> (Integer) data[0], data -> data[1]))); PIPE_NONUPLE = new Component(Stream.of(new Object[][] { - { 4, new UnificationEntry(TagPrefix.pipeNonupleFluid, GTMaterials.Titanium) }, - { 5, new UnificationEntry(TagPrefix.pipeNonupleFluid, GTMaterials.TungstenSteel) }, - { 6, new UnificationEntry(TagPrefix.pipeNonupleFluid, GTMaterials.NiobiumTitanium) }, - { 7, new UnificationEntry(TagPrefix.pipeNonupleFluid, GTMaterials.Iridium) }, - { 8, new UnificationEntry(TagPrefix.pipeNonupleFluid, GTMaterials.Naquadah) }, - { GTValues.FALLBACK, new UnificationEntry(TagPrefix.pipeNonupleFluid, GTMaterials.Neutronium) }, + { 4, new UnificationEntry(TagPrefix.pipeNonuple, GTMaterials.Titanium) }, + { 5, new UnificationEntry(TagPrefix.pipeNonuple, GTMaterials.TungstenSteel) }, + { 6, new UnificationEntry(TagPrefix.pipeNonuple, GTMaterials.NiobiumTitanium) }, + { 7, new UnificationEntry(TagPrefix.pipeNonuple, GTMaterials.Iridium) }, + { 8, new UnificationEntry(TagPrefix.pipeNonuple, GTMaterials.Naquadah) }, + { GTValues.FALLBACK, new UnificationEntry(TagPrefix.pipeNonuple, GTMaterials.Neutronium) }, }).collect(Collectors.toMap(data -> (Integer) data[0], data -> data[1]))); @@ -832,13 +832,13 @@ public static void initializeComponents() { { 0, new ItemStack(Blocks.GLASS, 1) }, { 1, new ItemStack(Blocks.GLASS, 1) }, { 2, new ItemStack(Blocks.GLASS, 1) }, - { 3, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Polyethylene) }, - { 4, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Polyethylene) }, - { 5, new UnificationEntry(TagPrefix.pipeHugeFluid, GTMaterials.Polyethylene) }, - { 6, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Polytetrafluoroethylene) }, - { 7, new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Polytetrafluoroethylene) }, - { 8, new UnificationEntry(TagPrefix.pipeHugeFluid, GTMaterials.Polytetrafluoroethylene) }, - { GTValues.FALLBACK, new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Polyethylene) }, + { 3, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Polyethylene) }, + { 4, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Polyethylene) }, + { 5, new UnificationEntry(TagPrefix.pipeHuge, GTMaterials.Polyethylene) }, + { 6, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Polytetrafluoroethylene) }, + { 7, new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Polytetrafluoroethylene) }, + { 8, new UnificationEntry(TagPrefix.pipeHuge, GTMaterials.Polytetrafluoroethylene) }, + { GTValues.FALLBACK, new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Polyethylene) }, }).collect(Collectors.toMap(data -> (Integer) data[0], data -> data[1]))); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/configurable/RecipeAddition.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/configurable/RecipeAddition.java index fa8be29532..6a8ced6376 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/configurable/RecipeAddition.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/configurable/RecipeAddition.java @@ -57,7 +57,7 @@ private static void steelSteamMultiblocks(Consumer provider) { GTMachines.STEAM_MACERATOR.right().asStack(), 'C', GTBlocks.CASING_STEEL_SOLID.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_hatch", GTMachines.STEAM_HATCH.asStack(), "BPB", "BTB", "BPB", 'B', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'P', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Steel), 'T', + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Steel), 'T', GTMachines.STEEL_DRUM.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_input_bus", GTMachines.STEAM_IMPORT_BUS.asStack(), "C", "H", 'H', GTBlocks.STEEL_HULL.asStack(), 'C', @@ -75,7 +75,7 @@ private static void steelSteamMultiblocks(Consumer provider) { GTMachines.STEAM_MACERATOR.left().asStack(), 'C', GTBlocks.CASING_BRONZE_BRICKS.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_hatch", GTMachines.STEAM_HATCH.asStack(), "BPB", "BTB", "BPB", 'B', new UnificationEntry(TagPrefix.plate, GTMaterials.Bronze), 'P', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Bronze), 'T', + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Bronze), 'T', GTMachines.BRONZE_DRUM.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_input_bus", GTMachines.STEAM_IMPORT_BUS.asStack(), "C", "H", 'H', GTBlocks.BRONZE_HULL.asStack(), 'C', diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java index d8a943a49a..21240354bf 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java @@ -29,14 +29,14 @@ public class PipeRecipeHandler { public static void init(Consumer provider) { - pipeTinyFluid.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeTiny); - pipeSmallFluid.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeSmall); - pipeNormalFluid.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeNormal); - pipeLargeFluid.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeLarge); - pipeHugeFluid.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeHuge); + pipeTiny.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeTiny); + pipeSmall.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeSmall); + pipeNormal.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeNormal); + pipeLarge.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeLarge); + pipeHuge.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeHuge); - pipeQuadrupleFluid.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeQuadruple); - pipeNonupleFluid.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeNonuple); + pipeQuadruple.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeQuadruple); + pipeNonuple.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeNonuple); pipeSmallItem.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processPipeSmall); pipeNormalItem.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processPipeNormal); @@ -215,7 +215,7 @@ private static void processPipeHuge(TagPrefix pipePrefix, Material material, IMa private static void processPipeQuadruple(TagPrefix pipePrefix, Material material, FluidPipeProperties property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; - ItemStack smallPipe = ChemicalHelper.get(pipeSmallFluid, material); + ItemStack smallPipe = ChemicalHelper.get(pipeSmall, material); ItemStack quadPipe = ChemicalHelper.get(pipePrefix, material); VanillaRecipeHelper.addShapedRecipe(provider, String.format("quadruple_%s_pipe", material.getName()), quadPipe, "XX", "XX", @@ -233,7 +233,7 @@ private static void processPipeQuadruple(TagPrefix pipePrefix, Material material private static void processPipeNonuple(TagPrefix pipePrefix, Material material, FluidPipeProperties property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; - ItemStack smallPipe = ChemicalHelper.get(pipeSmallFluid, material); + ItemStack smallPipe = ChemicalHelper.get(pipeSmall, material); ItemStack nonuplePipe = ChemicalHelper.get(pipePrefix, material); VanillaRecipeHelper.addShapedRecipe(provider, String.format("nonuple_%s_pipe", material.getName()), nonuplePipe, "XXX", "XXX", "XXX", diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/AssemblerRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/AssemblerRecipeLoader.java index 4af017ec57..6c06578eae 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/AssemblerRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/AssemblerRecipeLoader.java @@ -61,14 +61,14 @@ public static void init(Consumer provider) { // Other ASSEMBLER_RECIPES.recipeBuilder("stable_titanium_casing") .inputItems(rotor, Titanium, 2) - .inputItems(pipeNormalFluid, Titanium, 4) + .inputItems(pipeNormal, Titanium, 4) .inputItems(CASING_TITANIUM_STABLE.asStack()) .outputItems(CASING_ENGINE_INTAKE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft)) .duration(50).EUt(16).save(provider); ASSEMBLER_RECIPES.recipeBuilder("stable_tungstensteel_casing") .inputItems(rotor, TungstenSteel, 2) - .inputItems(pipeNormalFluid, TungstenSteel, 4) + .inputItems(pipeNormal, TungstenSteel, 4) .inputItems(CASING_TUNGSTENSTEEL_ROBUST.asStack()) .outputItems(CASING_EXTREME_ENGINE_INTAKE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft)) .duration(50).EUt(16).save(provider); @@ -127,21 +127,21 @@ public static void init(Consumer provider) { .inputItems(plate, Wood) .circuitMeta(12) .inputFluids(Glue.getFluid(50)) - .outputItems(pipeSmallFluid, Wood) + .outputItems(pipeSmall, Wood) .save(provider); ASSEMBLER_RECIPES.recipeBuilder("normal_wood_pipe").duration(200).EUt(VA[LV]) .inputItems(plate, Wood, 3) .circuitMeta(6) .inputFluids(Glue.getFluid(20)) - .outputItems(pipeNormalFluid, Wood) + .outputItems(pipeNormal, Wood) .save(provider); ASSEMBLER_RECIPES.recipeBuilder("large_wood_pipe").duration(100).EUt(VA[LV]) .inputItems(plate, Wood, 6) .circuitMeta(2) .inputFluids(Glue.getFluid(10)) - .outputItems(pipeLargeFluid, Wood) + .outputItems(pipeLarge, Wood) .save(provider); // Treated Wood Pipes @@ -149,21 +149,21 @@ public static void init(Consumer provider) { .inputItems(plate, TreatedWood) .circuitMeta(12) .inputFluids(Glue.getFluid(50)) - .outputItems(pipeSmallFluid, TreatedWood) + .outputItems(pipeSmall, TreatedWood) .save(provider); ASSEMBLER_RECIPES.recipeBuilder("normal_treated_wood_pipe").duration(200).EUt(VA[LV]) .inputItems(plate, TreatedWood, 3) .circuitMeta(6) .inputFluids(Glue.getFluid(20)) - .outputItems(pipeNormalFluid, TreatedWood) + .outputItems(pipeNormal, TreatedWood) .save(provider); ASSEMBLER_RECIPES.recipeBuilder("large_treated_wood_pipe").duration(100).EUt(VA[LV]) .inputItems(plate, TreatedWood, 6) .circuitMeta(2) .inputFluids(Glue.getFluid(10)) - .outputItems(pipeLargeFluid, TreatedWood) + .outputItems(pipeLarge, TreatedWood) .save(provider); // Voltage Coils diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CircuitRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CircuitRecipes.java index 4bcfc3b9a8..900a4b1a76 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CircuitRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CircuitRecipes.java @@ -1477,7 +1477,7 @@ private static void circuitRecipes(Consumer provider) { CIRCUIT_ASSEMBLER_RECIPES.recipeBuilder("neuro_processor").EUt(80000).duration(600) .inputItems(WETWARE_CIRCUIT_BOARD) .inputItems(STEM_CELLS, 16) - .inputItems(pipeSmallFluid, Polybenzimidazole, 8) + .inputItems(pipeSmall, Polybenzimidazole, 8) .inputItems(plate, Electrum, 8) .inputItems(foil, SiliconeRubber, 16) .inputItems(bolt, HSSE, 8) diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java index a4c3214182..bb532e2707 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java @@ -228,34 +228,34 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, material.equals(Rubber), String.format("electric_pump_lv_%s", name), ELECTRIC_PUMP_LV.asStack(), "SXR", "dPw", "RMC", 'S', new UnificationEntry(screw, Tin), 'X', new UnificationEntry(rotor, Tin), 'P', - new UnificationEntry(pipeNormalFluid, Bronze), 'R', new UnificationEntry(ring, material), 'C', + new UnificationEntry(pipeNormal, Bronze), 'R', new UnificationEntry(ring, material), 'C', new UnificationEntry(cableGtSingle, Tin), 'M', ELECTRIC_MOTOR_LV.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, material.equals(Rubber), String.format("electric_pump_mv_%s", name), ELECTRIC_PUMP_MV.asStack(), "SXR", "dPw", "RMC", 'S', new UnificationEntry(screw, Bronze), 'X', new UnificationEntry(rotor, Bronze), 'P', - new UnificationEntry(pipeNormalFluid, Steel), 'R', new UnificationEntry(ring, material), 'C', + new UnificationEntry(pipeNormal, Steel), 'R', new UnificationEntry(ring, material), 'C', new UnificationEntry(cableGtSingle, Copper), 'M', ELECTRIC_MOTOR_MV.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, material.equals(Rubber), String.format("electric_pump_hv_%s", name), ELECTRIC_PUMP_HV.asStack(), "SXR", "dPw", "RMC", 'S', new UnificationEntry(screw, Steel), 'X', new UnificationEntry(rotor, Steel), 'P', - new UnificationEntry(pipeNormalFluid, StainlessSteel), 'R', new UnificationEntry(ring, material), + new UnificationEntry(pipeNormal, StainlessSteel), 'R', new UnificationEntry(ring, material), 'C', new UnificationEntry(cableGtSingle, Gold), 'M', ELECTRIC_MOTOR_HV.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, material.equals(Rubber), String.format("electric_pump_ev_%s", name), ELECTRIC_PUMP_EV.asStack(), "SXR", "dPw", "RMC", 'S', new UnificationEntry(screw, StainlessSteel), 'X', new UnificationEntry(rotor, StainlessSteel), 'P', - new UnificationEntry(pipeNormalFluid, Titanium), 'R', new UnificationEntry(ring, material), 'C', + new UnificationEntry(pipeNormal, Titanium), 'R', new UnificationEntry(ring, material), 'C', new UnificationEntry(cableGtSingle, Aluminium), 'M', ELECTRIC_MOTOR_EV.asStack()); if (!material.equals(Rubber)) VanillaRecipeHelper.addShapedRecipe(provider, material.equals(SiliconeRubber), String.format("electric_pump_iv_%s", name), ELECTRIC_PUMP_IV.asStack(), "SXR", "dPw", "RMC", 'S', new UnificationEntry(screw, TungstenSteel), 'X', new UnificationEntry(rotor, TungstenSteel), 'P', - new UnificationEntry(pipeNormalFluid, TungstenSteel), 'R', new UnificationEntry(ring, material), + new UnificationEntry(pipeNormal, TungstenSteel), 'R', new UnificationEntry(ring, material), 'C', new UnificationEntry(cableGtSingle, Tungsten), 'M', ELECTRIC_MOTOR_IV.asStack()); ASSEMBLER_RECIPES.recipeBuilder("electric_pump_lv_" + name) .inputItems(cableGtSingle, Tin) - .inputItems(pipeNormalFluid, Bronze) + .inputItems(pipeNormal, Bronze) .inputItems(screw, Tin) .inputItems(rotor, Tin) .inputItems(ring, materialEntry.getValue(), 2) @@ -265,7 +265,7 @@ public static void init(Consumer provider) { ASSEMBLER_RECIPES.recipeBuilder("electric_pump_mv_" + name) .inputItems(cableGtSingle, Copper) - .inputItems(pipeNormalFluid, Steel) + .inputItems(pipeNormal, Steel) .inputItems(screw, Bronze) .inputItems(rotor, Bronze) .inputItems(ring, materialEntry.getValue(), 2) @@ -275,7 +275,7 @@ public static void init(Consumer provider) { ASSEMBLER_RECIPES.recipeBuilder("electric_pump_hv_" + name) .inputItems(cableGtSingle, Gold) - .inputItems(pipeNormalFluid, StainlessSteel) + .inputItems(pipeNormal, StainlessSteel) .inputItems(screw, Steel) .inputItems(rotor, Steel) .inputItems(ring, materialEntry.getValue(), 2) @@ -285,7 +285,7 @@ public static void init(Consumer provider) { ASSEMBLER_RECIPES.recipeBuilder("electric_pump_ev_" + name) .inputItems(cableGtSingle, Aluminium) - .inputItems(pipeNormalFluid, Titanium) + .inputItems(pipeNormal, Titanium) .inputItems(screw, StainlessSteel) .inputItems(rotor, StainlessSteel) .inputItems(ring, materialEntry.getValue(), 2) @@ -296,7 +296,7 @@ public static void init(Consumer provider) { if (!materialEntry.getValue().equals(Rubber)) ASSEMBLER_RECIPES.recipeBuilder("electric_pump_iv_" + name) .inputItems(cableGtSingle, Tungsten) - .inputItems(pipeNormalFluid, TungstenSteel) + .inputItems(pipeNormal, TungstenSteel) .inputItems(screw, TungstenSteel) .inputItems(rotor, TungstenSteel) .inputItems(ring, materialEntry.getValue(), 2) @@ -359,7 +359,7 @@ public static void init(Consumer provider) { ASSEMBLY_LINE_RECIPES.recipeBuilder("electric_pump_luv") .inputItems(ELECTRIC_MOTOR_LuV) - .inputItems(pipeSmallFluid, NiobiumTitanium) + .inputItems(pipeSmall, NiobiumTitanium) .inputItems(plate, HSSS, 2) .inputItems(screw, HSSS, 8) .inputItems(ring, SiliconeRubber, 4) @@ -376,7 +376,7 @@ public static void init(Consumer provider) { ASSEMBLY_LINE_RECIPES.recipeBuilder("electric_pump_zpm") .inputItems(ELECTRIC_MOTOR_ZPM) - .inputItems(pipeNormalFluid, Polybenzimidazole) + .inputItems(pipeNormal, Polybenzimidazole) .inputItems(plate, Osmiridium, 2) .inputItems(screw, Osmiridium, 8) .inputItems(ring, SiliconeRubber, 8) @@ -393,7 +393,7 @@ public static void init(Consumer provider) { ASSEMBLY_LINE_RECIPES.recipeBuilder("electric_pump_uv") .inputItems(ELECTRIC_MOTOR_UV) - .inputItems(pipeLargeFluid, Naquadah) + .inputItems(pipeLarge, Naquadah) .inputItems(plate, Tritanium, 2) .inputItems(screw, Tritanium, 8) .inputItems(ring, SiliconeRubber, 16) @@ -506,12 +506,12 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "cover_fluid_voiding", COVER_FLUID_VOIDING.asStack(), "SDS", "dPw", " E ", 'S', new UnificationEntry(screw, Steel), 'D', COVER_FLUID_DETECTOR.asStack(), 'P', - new UnificationEntry(pipeNormalFluid, Bronze), 'E', Items.ENDER_PEARL); + new UnificationEntry(pipeNormal, Bronze), 'E', Items.ENDER_PEARL); ASSEMBLER_RECIPES.recipeBuilder("cover_fluid_voiding") .inputItems(screw, Steel, 2) .inputItems(COVER_FLUID_DETECTOR) - .inputItems(pipeNormalFluid, Bronze) + .inputItems(pipeNormal, Bronze) .inputItems(Items.ENDER_PEARL) .outputItems(COVER_FLUID_VOIDING) .duration(100).EUt(VA[LV]).save(provider); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java index f23fbf431d..8c4f435a71 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java @@ -75,7 +75,7 @@ public static void init(Consumer provider) { .inputItems(frameGt, StainlessSteel) .inputItems(ELECTRIC_MOTOR_IV, 2) .inputItems(rotor, StainlessSteel, 2) - .inputItems(pipeTinyFluid, StainlessSteel, 16) + .inputItems(pipeTiny, StainlessSteel, 16) .inputItems(plate, Copper, 16) .inputItems(wireGtSingle, SamariumIronArsenicOxide) .outputItems(COMPUTER_HEAT_VENT, @@ -87,7 +87,7 @@ public static void init(Consumer provider) { .inputItems(foil, Silver, 8) .inputFluids(Polytetrafluoroethylene.getFluid(L)) .cleanroom(CleanroomType.CLEANROOM) - .outputItems(OPTICAL_PIPE[0]) + .outputItems(OPTICAL_PIPE) .duration(100).EUt(VA[IV]).save(provider); ASSEMBLY_LINE_RECIPES.recipeBuilder("data_bank") @@ -96,7 +96,7 @@ public static void init(Consumer provider) { .inputItems(TOOL_DATA_ORB) .inputItems(wireFine, Cobalt, 64) .inputItems(wireFine, Copper, 64) - .inputItems(OPTICAL_PIPE[0].asStack(4)) + .inputItems(OPTICAL_PIPE.asStack(4)) .inputItems(wireGtDouble, IndiumTinBariumTitaniumCuprate, 16) .inputFluids(SolderingAlloy.getFluid(L * 2)) .inputFluids(Lubricant.getFluid(500)) @@ -115,7 +115,7 @@ public static void init(Consumer provider) { .inputItems(ELECTRIC_MOTOR_ZPM, 2) .inputItems(wireGtDouble, UraniumRhodiumDinaquadide, 32) .inputItems(foil, Trinium, 32) - .inputItems(OPTICAL_PIPE[0].asStack(16)) + .inputItems(OPTICAL_PIPE.asStack(16)) .inputFluids(SolderingAlloy.getFluid(L * 8)) .inputFluids(VanadiumGallium.getFluid(L * 8)) .outputItems(RESEARCH_STATION) @@ -132,7 +132,7 @@ public static void init(Consumer provider) { .inputItems(ROBOT_ARM_ZPM, 2) .inputItems(ELECTRIC_MOTOR_ZPM, 2) .inputItems(wireGtDouble, UraniumRhodiumDinaquadide, 16) - .inputItems(OPTICAL_PIPE[0].asStack(2)) + .inputItems(OPTICAL_PIPE.asStack(2)) .inputFluids(SolderingAlloy.getFluid(L * 4)) .inputFluids(Polybenzimidazole.getFluid(L * 2)) .outputItems(OBJECT_HOLDER) @@ -150,12 +150,12 @@ public static void init(Consumer provider) { .inputItems(wireGtDouble, EnrichedNaquadahTriniumEuropiumDuranide, 32) .inputItems(foil, Tritanium, 64) .inputItems(foil, Tritanium, 64) - .inputItems(OPTICAL_PIPE[0].asStack(8)) + .inputItems(OPTICAL_PIPE.asStack(8)) .inputFluids(SolderingAlloy.getFluid(L * 4)) .inputFluids(Polybenzimidazole.getFluid(L * 4)) .outputItems(NETWORK_SWITCH) .stationResearch(b -> b - .researchStack(new ItemStack(OPTICAL_PIPE[0])) + .researchStack(new ItemStack(OPTICAL_PIPE)) .CWUt(32) .EUt(VA[ZPM])) .duration(1200).EUt(100000).save(provider); @@ -167,7 +167,7 @@ public static void init(Consumer provider) { .inputItems(TOOL_DATA_ORB) .inputItems(COVER_SCREEN) .inputItems(wireGtDouble, UraniumRhodiumDinaquadide, 64) - .inputItems(OPTICAL_PIPE[0].asStack(16)) + .inputItems(OPTICAL_PIPE.asStack(16)) .inputFluids(SolderingAlloy.getFluid(L * 8)) .inputFluids(VanadiumGallium.getFluid(L * 8)) .inputFluids(PCBCoolant.getFluid(4000)) @@ -199,7 +199,7 @@ public static void init(Consumer provider) { ASSEMBLER_RECIPES.recipeBuilder("hpca_active_cooler_component") .inputItems(ADVANCED_COMPUTER_CASING.asStack()) .inputItems(plate, Aluminium, 16) - .inputItems(pipeTinyFluid, StainlessSteel, 16) + .inputItems(pipeTiny, StainlessSteel, 16) .inputItems(screw, StainlessSteel, 8) .outputItems(HPCA_ACTIVE_COOLER_COMPONENT) .inputFluids(PCBCoolant.getFluid(1000)) @@ -210,7 +210,7 @@ public static void init(Consumer provider) { .inputItems(ADVANCED_COMPUTER_CASING.asStack()) .inputItems(CustomTags.UV_CIRCUITS) .inputItems(EMITTER_ZPM) - .inputItems(OPTICAL_PIPE[0].asStack(2)) + .inputItems(OPTICAL_PIPE.asStack(2)) .outputItems(HPCA_BRIDGE_COMPONENT) .inputFluids(PCBCoolant.getFluid(1000)) .cleanroom(CleanroomType.CLEANROOM) @@ -239,7 +239,7 @@ public static void init(Consumer provider) { .inputItems(ITEM_IMPORT_BUS[LuV]) .inputItems(CustomTags.LuV_CIRCUITS) .inputItems(SENSOR_IV) - .inputItems(OPTICAL_PIPE[0].asStack(2)) + .inputItems(OPTICAL_PIPE.asStack(2)) .inputFluids(Polybenzimidazole.getFluid(L * 2)) .outputItems(DATA_HATCH_RECEIVER) .cleanroom(CleanroomType.CLEANROOM) @@ -250,7 +250,7 @@ public static void init(Consumer provider) { .inputItems(ITEM_EXPORT_BUS[LuV]) .inputItems(CustomTags.LuV_CIRCUITS) .inputItems(EMITTER_IV) - .inputItems(OPTICAL_PIPE[0].asStack(2)) + .inputItems(OPTICAL_PIPE.asStack(2)) .inputFluids(Polybenzimidazole.getFluid(L * 2)) .outputItems(DATA_HATCH_TRANSMITTER) .cleanroom(CleanroomType.CLEANROOM) @@ -287,7 +287,7 @@ public static void init(Consumer provider) { .inputItems(CASING_LAMINATED_GLASS.asStack(1)) .inputItems(foil, Osmiridium, 2) .inputFluids(Polytetrafluoroethylene.getFluid(L)) - .outputItems(LASER_PIPE[0]) + .outputItems(LASER_PIPE) .cleanroom(CleanroomType.CLEANROOM) .duration(100).EUt(VA[IV]).save(provider); } diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CraftingRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CraftingRecipeLoader.java index 62554759b5..a2b1081b8d 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CraftingRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/CraftingRecipeLoader.java @@ -28,20 +28,20 @@ public static void init(Consumer provider) { // todo facades // registerFacadeRecipe(provider, Iron, 4); - VanillaRecipeHelper.addShapedRecipe(provider, "small_wooden_pipe", ChemicalHelper.get(pipeSmallFluid, Wood), + VanillaRecipeHelper.addShapedRecipe(provider, "small_wooden_pipe", ChemicalHelper.get(pipeSmall, Wood), "sWr", 'W', ItemTags.PLANKS); - VanillaRecipeHelper.addShapedRecipe(provider, "normal_wooden_pipe", ChemicalHelper.get(pipeNormalFluid, Wood), + VanillaRecipeHelper.addShapedRecipe(provider, "normal_wooden_pipe", ChemicalHelper.get(pipeNormal, Wood), "WWW", "s r", 'W', ItemTags.PLANKS); - VanillaRecipeHelper.addShapedRecipe(provider, "large_wooden_pipe", ChemicalHelper.get(pipeLargeFluid, Wood), + VanillaRecipeHelper.addShapedRecipe(provider, "large_wooden_pipe", ChemicalHelper.get(pipeLarge, Wood), "WWW", "s r", "WWW", 'W', ItemTags.PLANKS); VanillaRecipeHelper.addShapedRecipe(provider, "small_treated_wooden_pipe", - ChemicalHelper.get(pipeSmallFluid, TreatedWood), "sWr", 'W', GTBlocks.TREATED_WOOD_PLANK.asStack()); + ChemicalHelper.get(pipeSmall, TreatedWood), "sWr", 'W', GTBlocks.TREATED_WOOD_PLANK.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, "normal_treated_wooden_pipe", - ChemicalHelper.get(pipeNormalFluid, TreatedWood), "WWW", "s r", 'W', + ChemicalHelper.get(pipeNormal, TreatedWood), "WWW", "s r", 'W', GTBlocks.TREATED_WOOD_PLANK.asStack()); VanillaRecipeHelper.addShapedRecipe(provider, "large_treated_wooden_pipe", - ChemicalHelper.get(pipeLargeFluid, TreatedWood), "WWW", "s r", "WWW", 'W', + ChemicalHelper.get(pipeLarge, TreatedWood), "WWW", "s r", "WWW", 'W', GTBlocks.TREATED_WOOD_PLANK.asStack()); VanillaRecipeHelper.addShapelessRecipe(provider, "integrated_circuit", INTEGRATED_CIRCUIT.asStack(), @@ -155,7 +155,7 @@ public static void init(Consumer provider) { new UnificationEntry(rotor, Steel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "filter_casing_sterile", GTBlocks.FILTER_CASING_STERILE.asStack(), "BEB", "ISI", "MFR", 'B', - new UnificationEntry(pipeLargeFluid, Polybenzimidazole), 'E', EMITTER_ZPM.asStack(), 'I', + new UnificationEntry(pipeLarge, Polybenzimidazole), 'E', EMITTER_ZPM.asStack(), 'I', ITEM_FILTER.asStack(), 'S', BLACKLIGHT.asStack(), 'M', ELECTRIC_MOTOR_ZPM.asStack(), 'F', new UnificationEntry(frameGt, Tritanium), 'R', new UnificationEntry(rotor, NaquadahAlloy)); @@ -288,7 +288,7 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, "fluid_jetpack", GTItems.LIQUID_FUEL_JETPACK.asStack(), "xCw", "SUS", "RIR", 'C', CustomTags.LV_CIRCUITS, 'S', GTItems.FLUID_CELL_LARGE_STEEL.asStack(), 'U', GTItems.ELECTRIC_PUMP_LV.asStack(), 'R', new UnificationEntry(rotor, Lead), 'I', - new UnificationEntry(pipeSmallFluid, Potin)); + new UnificationEntry(pipeSmall, Potin)); VanillaRecipeHelper.addShapedRecipe(provider, "electric_jetpack", GTItems.ELECTRIC_JETPACK.asStack(), "xCd", "TBT", "I I", 'C', CustomTags.MV_CIRCUITS, 'T', GTItems.POWER_THRUSTER.asStack(), 'B', GTItems.BATTERY_MV_LITHIUM.asStack(), 'I', new UnificationEntry(wireGtDouble, AnnealedCopper)); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/GCyMRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/GCyMRecipes.java index 0ad9b66849..8f420f2f7a 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/GCyMRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/GCyMRecipes.java @@ -81,11 +81,11 @@ private static void registerMultiblockControllerRecipes(Consumer 'C', CustomTags.EV_CIRCUITS, 'P', new UnificationEntry(plate, HSLASteel), 'R', ROBOT_ARM_HV.asStack(), 'K', CONVEYOR_MODULE_HV.asStack(), 'X', PACKER[HV].asStack()); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_mixer", LARGE_MIXER.asStack(), "FCF", "RXR", "MKM", - 'C', CustomTags.IV_CIRCUITS, 'F', ChemicalHelper.get(pipeNormalFluid, Polybenzimidazole), 'R', + 'C', CustomTags.IV_CIRCUITS, 'F', ChemicalHelper.get(pipeNormal, Polybenzimidazole), 'R', ChemicalHelper.get(rotor, Osmiridium), 'M', ELECTRIC_MOTOR_IV.asStack(), 'X', MIXER[IV].asStack(), 'K', new UnificationEntry(TagPrefix.cableGtSingle, Platinum)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_centrifuge", LARGE_CENTRIFUGE.asStack(), "SFS", - "CXC", "MKM", 'C', CustomTags.IV_CIRCUITS, 'F', ChemicalHelper.get(pipeHugeFluid, StainlessSteel), 'S', + "CXC", "MKM", 'C', CustomTags.IV_CIRCUITS, 'F', ChemicalHelper.get(pipeHuge, StainlessSteel), 'S', ChemicalHelper.get(spring, MolybdenumDisilicide), 'M', ELECTRIC_MOTOR_IV.asStack(), 'X', CENTRIFUGE[IV].asStack(), 'K', new UnificationEntry(TagPrefix.cableGtSingle, Platinum)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_assembler", LARGE_ASSEMBLER.asStack(), "RKR", "CXC", @@ -113,7 +113,7 @@ private static void registerMultiblockControllerRecipes(Consumer new UnificationEntry(wireGtQuadruple, RutheniumTriniumAmericiumNeutronate)); VanillaRecipeHelper.addShapedRecipe(provider, true, "mega_vacuum_freezer", MEGA_VACUUM_FREEZER.asStack(), "PCP", "FSF", "DWD", 'C', ZPM_CIRCUITS, 'S', VACUUM_FREEZER.asStack(), 'F', FIELD_GENERATOR_ZPM.asStack(), 'P', - new UnificationEntry(pipeNormalFluid, NiobiumTitanium), 'D', + new UnificationEntry(pipeNormal, NiobiumTitanium), 'D', new UnificationEntry(plateDense, RhodiumPlatedPalladium), 'W', new UnificationEntry(wireGtQuadruple, RutheniumTriniumAmericiumNeutronate)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_autoclave", LARGE_AUTOCLAVE.asStack(), "PCP", "PAP", @@ -135,7 +135,7 @@ private static void registerMultiblockControllerRecipes(Consumer new UnificationEntry(cableGtSingle, Platinum)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_distillery", LARGE_DISTILLERY.asStack(), "PZP", "EDE", "PZP", 'Z', CustomTags.IV_CIRCUITS, 'D', DISTILLATION_TOWER.asStack(), 'E', - ELECTRIC_PUMP_IV.asStack(), 'P', ChemicalHelper.get(pipeLargeFluid, Iridium)); + ELECTRIC_PUMP_IV.asStack(), 'P', ChemicalHelper.get(pipeLarge, Iridium)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_extractor", LARGE_EXTRACTOR.asStack(), "PTP", "EZC", "BKB", 'Z', CustomTags.IV_CIRCUITS, 'B', ELECTRIC_PISTON_IV.asStack(), 'P', ELECTRIC_PUMP_IV.asStack(), 'E', EXTRACTOR[IV].asStack(), 'C', CANNER[IV].asStack(), 'T', CASING_TEMPERED_GLASS.asStack(), 'K', @@ -145,7 +145,7 @@ private static void registerMultiblockControllerRecipes(Consumer new UnificationEntry(spring, MolybdenumDisilicide), 'K', new UnificationEntry(cableGtSingle, Platinum)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_solidifier", LARGE_SOLIDIFIER.asStack(), "PZP", "ESE", "PKP", 'Z', CustomTags.IV_CIRCUITS, 'S', FLUID_SOLIDIFIER[IV].asStack(), 'E', - ELECTRIC_PUMP_IV.asStack(), 'P', ChemicalHelper.get(pipeNormalFluid, Polyethylene), 'K', + ELECTRIC_PUMP_IV.asStack(), 'P', ChemicalHelper.get(pipeNormal, Polyethylene), 'K', new UnificationEntry(cableGtSingle, Platinum)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_wiremill", LARGE_WIREMILL.asStack(), "PZP", "SWS", "MKM", 'Z', CustomTags.IV_CIRCUITS, 'W', WIREMILL[IV].asStack(), 'P', diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java index 66939e196d..557f4c9937 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java @@ -750,7 +750,7 @@ private static void registerAssemblerRecipes(Consumer provider) ASSEMBLER_RECIPES.recipeBuilder("fusion_coil").EUt(VA[ZPM]).inputItems(GTBlocks.SUPERCONDUCTING_COIL.asStack()) .inputItems(FIELD_GENERATOR_IV.asStack(2)).inputItems(ELECTRIC_PUMP_IV) .inputItems(NEUTRON_REFLECTOR.asStack(2)).inputItems(CustomTags.LuV_CIRCUITS, 4) - .inputItems(pipeSmallFluid, Naquadah, 4).inputItems(plate, Europium, 4) + .inputItems(pipeSmall, Naquadah, 4).inputItems(plate, Europium, 4) .inputFluids(VanadiumGallium.getFluid(GTValues.L * 4)).outputItems(GTBlocks.FUSION_COIL.asStack()) .duration(100).cleanroom(CleanroomType.CLEANROOM).save(provider); ASSEMBLER_RECIPES.recipeBuilder("fusion_glass").EUt(VA[LuV]) diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java index 93bcbf9ccd..75dd30b5d4 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java @@ -115,27 +115,27 @@ public static void init(Consumer provider) { GTBlocks.CASING_BRONZE_PIPE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "PIP", "IFI", "PIP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Bronze), 'F', new UnificationEntry(TagPrefix.frameGt, GTMaterials.Bronze), 'I', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Bronze)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Bronze)); VanillaRecipeHelper.addShapedRecipe(provider, true, "casing_steel_pipe", GTBlocks.CASING_STEEL_PIPE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "PIP", "IFI", "PIP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'F', new UnificationEntry(TagPrefix.frameGt, GTMaterials.Steel), 'I', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Steel)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Steel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "casing_titanium_pipe", GTBlocks.CASING_TITANIUM_PIPE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "PIP", "IFI", "PIP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Titanium), 'F', new UnificationEntry(TagPrefix.frameGt, GTMaterials.Titanium), 'I', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Titanium)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Titanium)); VanillaRecipeHelper.addShapedRecipe(provider, true, "casing_tungstensteel_pipe", GTBlocks.CASING_TUNGSTENSTEEL_PIPE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "PIP", "IFI", "PIP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.TungstenSteel), 'F', new UnificationEntry(TagPrefix.frameGt, GTMaterials.TungstenSteel), 'I', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.TungstenSteel)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.TungstenSteel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "casing_ptfe_pipe", GTBlocks.CASING_POLYTETRAFLUOROETHYLENE_PIPE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "PIP", "IFI", "PIP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Polytetrafluoroethylene), 'F', new UnificationEntry(TagPrefix.frameGt, GTMaterials.Polytetrafluoroethylene), 'I', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Polytetrafluoroethylene)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Polytetrafluoroethylene)); VanillaRecipeHelper.addShapedRecipe(provider, true, "casing_bronze_firebox", GTBlocks.FIREBOX_BRONZE.asStack(2), "PSP", "SFS", "PSP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Bronze), 'F', new UnificationEntry(TagPrefix.frameGt, GTMaterials.Bronze), 'S', @@ -343,22 +343,22 @@ public static void init(Consumer provider) { provider, true, "fluid_import_hatch_4x_" + tierName, importHatch4x.asStack(), "P", "M", 'M', importHatch.asStack(), - 'P', new UnificationEntry(TagPrefix.pipeQuadrupleFluid, material)); + 'P', new UnificationEntry(TagPrefix.pipeQuadruple, material)); VanillaRecipeHelper.addShapedRecipe( provider, true, "fluid_export_hatch_4x_" + tierName, exportHatch4x.asStack(), "M", "P", 'M', exportHatch.asStack(), - 'P', new UnificationEntry(TagPrefix.pipeQuadrupleFluid, material)); + 'P', new UnificationEntry(TagPrefix.pipeQuadruple, material)); VanillaRecipeHelper.addShapedRecipe( provider, true, "fluid_import_hatch_9x_" + tierName, importHatch9x.asStack(), "P", "M", 'M', importHatch.asStack(), - 'P', new UnificationEntry(TagPrefix.pipeNonupleFluid, material)); + 'P', new UnificationEntry(TagPrefix.pipeNonuple, material)); VanillaRecipeHelper.addShapedRecipe( provider, true, "fluid_export_hatch_9x_" + tierName, exportHatch9x.asStack(), "M", "P", 'M', exportHatch.asStack(), - 'P', new UnificationEntry(TagPrefix.pipeNonupleFluid, material)); + 'P', new UnificationEntry(TagPrefix.pipeNonuple, material)); } VanillaRecipeHelper.addShapedRecipe(provider, true, "rotor_holder_hv", GTMachines.ROTOR_HOLDER[HV].asStack(), @@ -414,7 +414,7 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "passthrough_hatch_fluid", GTMachines.FLUID_PASSTHROUGH_HATCH[HV].asStack(), " C ", "GHG", " S ", 'C', GTItems.ELECTRIC_PUMP_HV.asStack(), 'G', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Steel), 'H', GTMachines.HULL[HV].asStack(), + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Steel), 'H', GTMachines.HULL[HV].asStack(), 'S', GTBlocks.CASING_TEMPERED_GLASS); // TODO Charcoal pile igniter @@ -453,85 +453,85 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_boiler_solar_bronze", GTMachines.STEAM_SOLAR_BOILER.left().asStack(), "GGG", "SSS", "PMP", 'M', GTBlocks.BRONZE_BRICKS_HULL.asStack(), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), 'S', + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Silver), 'G', new ItemStack(Blocks.GLASS)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_boiler_solar_steel", GTMachines.STEAM_SOLAR_BOILER.right().asStack(), "GGG", "SSS", "PMP", 'M', GTBlocks.STEEL_BRICKS_HULL.asStack(), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Steel), 'S', + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Steel), 'S', new UnificationEntry(TagPrefix.plateDouble, GTMaterials.Silver), 'G', new ItemStack(Blocks.GLASS)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_furnace_bronze", GTMachines.STEAM_FURNACE.left().asStack(), "XXX", "XMX", "XFX", 'M', GTBlocks.BRONZE_BRICKS_HULL.asStack(), 'X', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), 'F', Blocks.FURNACE); + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'F', Blocks.FURNACE); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_furnace_steel", GTMachines.STEAM_FURNACE.right().asStack(), "XSX", "PMP", "XXX", 'M', GTMachines.STEAM_FURNACE.left().asStack(), 'X', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.TinAlloy), 'S', + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.TinAlloy), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.WroughtIron)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_macerator_bronze", GTMachines.STEAM_MACERATOR.left().asStack(), "DXD", "XMX", "PXP", 'M', GTBlocks.BRONZE_HULL.asStack(), - 'X', new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), 'P', CustomTags.PISTONS, + 'X', new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'P', CustomTags.PISTONS, 'D', new UnificationEntry(TagPrefix.gem, GTMaterials.Diamond)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_macerator_steel", GTMachines.STEAM_MACERATOR.right().asStack(), "WSW", "PMP", "WWW", 'M', GTMachines.STEAM_MACERATOR.left().asStack(), 'W', new UnificationEntry(TagPrefix.plate, GTMaterials.WroughtIron), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.TinAlloy)); + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.TinAlloy)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_extractor_bronze", GTMachines.STEAM_EXTRACTOR.left().asStack(), "XXX", "PMG", "XXX", 'M', GTBlocks.BRONZE_HULL.asStack(), - 'X', new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), 'P', CustomTags.PISTONS, + 'X', new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'P', CustomTags.PISTONS, 'G', new ItemStack(Blocks.GLASS)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_extractor_steel", GTMachines.STEAM_EXTRACTOR.right().asStack(), "PSP", "WMW", "PPP", 'M', GTMachines.STEAM_EXTRACTOR.left().asStack(), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.TinAlloy), 'S', + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.TinAlloy), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'W', new UnificationEntry(TagPrefix.plate, GTMaterials.WroughtIron)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_hammer_bronze", GTMachines.STEAM_HAMMER.left().asStack(), "XPX", "XMX", "XAX", 'M', GTBlocks.BRONZE_HULL.asStack(), 'X', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), 'P', CustomTags.PISTONS, 'A', + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'P', CustomTags.PISTONS, 'A', Blocks.ANVIL); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_hammer_steel", GTMachines.STEAM_HAMMER.right().asStack(), "WSW", "PMP", "WWW", 'M', GTMachines.STEAM_HAMMER.left().asStack(), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'W', new UnificationEntry(TagPrefix.plate, GTMaterials.WroughtIron), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.TinAlloy)); + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.TinAlloy)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_compressor_bronze", GTMachines.STEAM_COMPRESSOR.left().asStack(), "XXX", "PMP", "XXX", 'M', GTBlocks.BRONZE_HULL.asStack(), - 'X', new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), 'P', CustomTags.PISTONS); + 'X', new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'P', CustomTags.PISTONS); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_compressor_steel", GTMachines.STEAM_COMPRESSOR.right().asStack(), "PSP", "WMW", "PPP", 'M', GTMachines.STEAM_COMPRESSOR.left().asStack(), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'W', new UnificationEntry(TagPrefix.plate, GTMaterials.WroughtIron), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.TinAlloy)); + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.TinAlloy)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_alloy_smelter_bronze", GTMachines.STEAM_ALLOY_SMELTER.left().asStack(), "XXX", "FMF", "XXX", 'M', GTBlocks.BRONZE_BRICKS_HULL.asStack(), 'X', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), 'F', Blocks.FURNACE); + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'F', Blocks.FURNACE); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_alloy_smelter_steel", GTMachines.STEAM_ALLOY_SMELTER.right().asStack(), "WSW", "WMW", "WPW", 'M', GTMachines.STEAM_ALLOY_SMELTER.left().asStack(), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'W', new UnificationEntry(TagPrefix.plate, GTMaterials.WroughtIron), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.TinAlloy)); + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.TinAlloy)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_rock_breaker_bronze", GTMachines.STEAM_ROCK_CRUSHER.left().asStack(), "PXP", "XMX", "DXD", 'M', - GTBlocks.BRONZE_HULL.asStack(), 'X', new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.Bronze), + GTBlocks.BRONZE_HULL.asStack(), 'X', new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.Bronze), 'P', CustomTags.PISTONS, 'D', new UnificationEntry(TagPrefix.gem, GTMaterials.Diamond)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_rock_breaker_steel", GTMachines.STEAM_ROCK_CRUSHER.right().asStack(), "WSW", "PMP", "WWW", 'M', GTMachines.STEAM_ROCK_CRUSHER.left().asStack(), 'W', new UnificationEntry(TagPrefix.plate, GTMaterials.WroughtIron), 'S', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'P', - new UnificationEntry(TagPrefix.pipeSmallFluid, GTMaterials.TinAlloy)); + new UnificationEntry(TagPrefix.pipeSmall, GTMaterials.TinAlloy)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_miner", GTMachines.STEAM_MINER.asStack(), "DSD", "SMS", "GSG", 'M', GTBlocks.BRONZE_BRICKS_HULL.asStack(), 'S', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Bronze), 'D', + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Bronze), 'D', new UnificationEntry(TagPrefix.gem, GTMaterials.Diamond), 'G', new UnificationEntry(TagPrefix.gearSmall, GTMaterials.Bronze)); @@ -568,7 +568,7 @@ public static void init(Consumer provider) { 'C', CustomTags.HV_CIRCUITS, 'W', new UnificationEntry(TagPrefix.cableGtSingle, GTMaterials.Gold)); VanillaRecipeHelper.addShapedRecipe(provider, true, "distillation_tower", GTMachines.DISTILLATION_TOWER.asStack(), "CBC", "FMF", "CBC", 'M', GTMachines.HULL[HV].asStack(), 'B', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.StainlessSteel), 'C', CustomTags.EV_CIRCUITS, + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.StainlessSteel), 'C', CustomTags.EV_CIRCUITS, 'F', GTItems.ELECTRIC_PUMP_HV); VanillaRecipeHelper.addShapedRecipe(provider, true, "evaporation_plant", GTMachines.EVAPORATION_PLANT.asStack(), "CBC", "FMF", "CBC", 'M', GTMachines.HULL[HV].asStack(), @@ -598,12 +598,12 @@ public static void init(Consumer provider) { GTBlocks.CASING_ENGINE_INTAKE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "PhP", "RFR", "PwP", 'R', new UnificationEntry(TagPrefix.rotor, GTMaterials.Titanium), 'F', GTBlocks.CASING_TITANIUM_STABLE.asStack(), 'P', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Titanium)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Titanium)); VanillaRecipeHelper.addShapedRecipe(provider, true, "extreme_engine_intake_casing", GTBlocks.CASING_EXTREME_ENGINE_INTAKE.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "PhP", "RFR", "PwP", 'R', new UnificationEntry(TagPrefix.rotor, GTMaterials.TungstenSteel), 'F', GTBlocks.CASING_TUNGSTENSTEEL_ROBUST.asStack(), 'P', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.TungstenSteel)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.TungstenSteel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "multi_furnace", GTMachines.MULTI_SMELTER.asStack(), "PPP", "ASA", "CAC", 'P', Blocks.FURNACE, 'A', CustomTags.HV_CIRCUITS, 'S', GTBlocks.CASING_INVAR_HEATPROOF.asStack(), 'C', @@ -612,16 +612,16 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "large_steam_turbine", GTMachines.LARGE_STEAM_TURBINE.asStack(), "PSP", "SAS", "CSC", 'S', new UnificationEntry(TagPrefix.gear, GTMaterials.Steel), 'P', CustomTags.HV_CIRCUITS, 'A', - GTMachines.HULL[HV].asStack(), 'C', new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Steel)); + GTMachines.HULL[HV].asStack(), 'C', new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Steel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_gas_turbine", GTMachines.LARGE_GAS_TURBINE.asStack(), "PSP", "SAS", "CSC", 'S', new UnificationEntry(TagPrefix.gear, GTMaterials.StainlessSteel), 'P', CustomTags.EV_CIRCUITS, 'A', GTMachines.HULL[GTValues.EV].asStack(), 'C', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.StainlessSteel)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.StainlessSteel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_plasma_turbine", GTMachines.LARGE_PLASMA_TURBINE.asStack(), "PSP", "SAS", "CSC", 'S', new UnificationEntry(TagPrefix.gear, GTMaterials.TungstenSteel), 'P', CustomTags.LuV_CIRCUITS, 'A', GTMachines.HULL[GTValues.LuV].asStack(), 'C', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.TungstenSteel)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.TungstenSteel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "large_bronze_boiler", GTMachines.LARGE_BOILER_BRONZE.asStack(), "PSP", "SAS", "PSP", 'P', @@ -647,7 +647,7 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "large_chemical_reactor", GTMachines.LARGE_CHEMICAL_REACTOR.asStack(), "CRC", "PMP", "CHC", 'C', CustomTags.HV_CIRCUITS, 'R', ChemicalHelper.get(TagPrefix.rotor, GTMaterials.StainlessSteel), 'P', - ChemicalHelper.get(TagPrefix.pipeLargeFluid, GTMaterials.Polytetrafluoroethylene), 'M', + ChemicalHelper.get(TagPrefix.pipeLarge, GTMaterials.Polytetrafluoroethylene), 'M', GTItems.ELECTRIC_MOTOR_HV.asStack(), 'H', GTMachines.HULL[HV].asStack()); VanillaRecipeHelper.addShapedRecipe(provider, true, "power_substation", GTMachines.POWER_SUBSTATION.asStack(), @@ -688,17 +688,17 @@ public static void init(Consumer provider) { "PCP", "RMR", "EWE", 'M', GTMachines.HULL[GTValues.LV].asStack(), 'E', GTItems.ELECTRIC_MOTOR_LV, 'R', new UnificationEntry(TagPrefix.rotor, GTMaterials.Tin), 'C', CustomTags.LV_CIRCUITS, 'W', new UnificationEntry(TagPrefix.cableGtSingle, GTMaterials.Tin), 'P', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Bronze)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Bronze)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_turbine_mv", GTMachines.STEAM_TURBINE[MV].asStack(), "PCP", "RMR", "EWE", 'M', GTMachines.HULL[GTValues.MV].asStack(), 'E', GTItems.ELECTRIC_MOTOR_MV, 'R', new UnificationEntry(TagPrefix.rotor, GTMaterials.Bronze), 'C', CustomTags.MV_CIRCUITS, 'W', new UnificationEntry(TagPrefix.cableGtSingle, GTMaterials.Copper), 'P', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Steel)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Steel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "steam_turbine_hv", GTMachines.STEAM_TURBINE[HV].asStack(), "PCP", "RMR", "EWE", 'M', GTMachines.HULL[HV].asStack(), 'E', GTItems.ELECTRIC_MOTOR_HV, 'R', new UnificationEntry(TagPrefix.rotor, GTMaterials.Steel), 'C', CustomTags.HV_CIRCUITS, 'W', new UnificationEntry(TagPrefix.cableGtSingle, GTMaterials.Gold), 'P', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.StainlessSteel)); + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.StainlessSteel)); // TODO Crafting station // VanillaRecipeHelper.addShapedRecipe(provider, true, "workbench_bronze", GTMachines.WORKBENCH.getStackForm(), @@ -707,11 +707,11 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "primitive_pump", GTMachines.PRIMITIVE_PUMP.asStack(), "RGS", "OWd", "CLC", 'R', new UnificationEntry(TagPrefix.ring, GTMaterials.Iron), 'G', - new UnificationEntry(TagPrefix.pipeNormalFluid, GTMaterials.Wood), 'S', + new UnificationEntry(TagPrefix.pipeNormal, GTMaterials.Wood), 'S', new UnificationEntry(TagPrefix.screw, GTMaterials.Iron), 'O', new UnificationEntry(TagPrefix.rotor, GTMaterials.Iron), 'W', GTBlocks.TREATED_WOOD_PLANK.asStack(), 'C', new ItemStack(Items.COBBLESTONE_SLAB), 'L', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Wood)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Wood)); VanillaRecipeHelper.addShapedRecipe(provider, true, "pump_deck", GTBlocks.CASING_PUMP_DECK.asStack(ConfigHolder.INSTANCE.recipes.casingsPerCraft), "SWS", "dCh", 'S', new UnificationEntry(TagPrefix.screw, GTMaterials.Iron), 'W', GTBlocks.TREATED_WOOD_PLANK.asStack(), @@ -719,7 +719,7 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "pump_hatch", GTMachines.PUMP_HATCH.asStack(), "SRd", "PLP", "CRC", 'S', new UnificationEntry(TagPrefix.screw, GTMaterials.Iron), 'R', new UnificationEntry(TagPrefix.ring, GTMaterials.Iron), 'P', GTBlocks.TREATED_WOOD_PLANK.asStack(), 'L', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Wood), 'C', + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Wood), 'C', new ItemStack(Items.COBBLESTONE_SLAB)); VanillaRecipeHelper.addShapedRecipe(provider, true, "wood_multiblock_tank", @@ -1044,34 +1044,34 @@ public static void init(Consumer provider) { // Hermetic Casings VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_lv", GTBlocks.HERMETIC_CASING_LV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Steel), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Polyethylene)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Polyethylene)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_mv", GTBlocks.HERMETIC_CASING_MV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Aluminium), 'F', new UnificationEntry(TagPrefix.pipeLargeItem, GTMaterials.PolyvinylChloride)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_hv", GTBlocks.HERMETIC_CASING_HV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.StainlessSteel), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Polytetrafluoroethylene)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Polytetrafluoroethylene)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_ev", GTBlocks.HERMETIC_CASING_EV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Titanium), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.StainlessSteel)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.StainlessSteel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_iv", GTBlocks.HERMETIC_CASING_IV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.TungstenSteel), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Titanium)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Titanium)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_luv", GTBlocks.HERMETIC_CASING_LuV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.RhodiumPlatedPalladium), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.TungstenSteel)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.TungstenSteel)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_zpm", GTBlocks.HERMETIC_CASING_ZPM.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.NaquadahAlloy), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.NiobiumTitanium)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.NiobiumTitanium)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_uv", GTBlocks.HERMETIC_CASING_UV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Darmstadtium), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Naquadah)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Naquadah)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_max", GTBlocks.HERMETIC_CASING_UHV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Neutronium), 'F', - new UnificationEntry(TagPrefix.pipeLargeFluid, GTMaterials.Duranium)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Duranium)); // Super / Quantum Chests VanillaRecipeHelper.addShapedRecipe(provider, true, "super_chest_lv", GTMachines.SUPER_CHEST[LV].asStack(), diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java index 01850659c4..096c49db33 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java @@ -524,7 +524,7 @@ public static void init(Consumer provider) { .save(provider); ASSEMBLER_RECIPES.recipeBuilder("long_distance_fluid_endpoint") - .inputItems(pipeLargeFluid, Bronze, 2) + .inputItems(pipeLarge, Bronze, 2) .inputItems(plate, Steel, 8) .inputItems(gear, Steel, 2) .circuitMeta(1) @@ -543,7 +543,7 @@ public static void init(Consumer provider) { .save(provider); ASSEMBLER_RECIPES.recipeBuilder("long_distance_fluid_pipe") - .inputItems(pipeLargeFluid, Bronze, 2) + .inputItems(pipeLarge, Bronze, 2) .inputItems(plate, Steel, 8) .circuitMeta(2) .inputFluids(SolderingAlloy.getFluid(L / 2)) diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java index 046dd15b7a..bbfd1684e6 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.integration.jade; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.common.blockentity.FluidPipeBlockEntity; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.integration.jade.provider.*; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java index 3c9f4a6ad1..3ce8297bc4 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.integration.jade.provider; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.common.blockentity.FluidPipeBlockEntity; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; diff --git a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java index cae4a5f400..6abe28e807 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java @@ -13,6 +13,10 @@ import com.google.common.collect.Table; import it.unimi.dsi.fastutil.ints.Int2LongFunction; import lombok.Getter; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import org.jetbrains.annotations.NotNull; import java.util.List; @@ -45,4 +49,24 @@ public long getOffset() { public MultiManagedStorage getRootStorage() { return null; } + + @Override + public void onNeighborChanged(@NotNull Direction facing) { + + } + + @Override + public Level getLevel() { + return null; + } + + @Override + public BlockPos getBlockPos() { + return null; + } + + @Override + public void markAsDirty() { + + } } From 811a443f7ac55e0b2029ac3fec576b4b7c0e91d7 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 22 Aug 2024 22:09:36 +0300 Subject: [PATCH 07/70] fix conveyor cover build errors, spotless --- .../gtceu/api/capability/ICoverable.java | 4 +- .../data/IComputationDataAccess.java | 1 + .../api/capability/data/IDataAccess.java | 4 +- .../capability/data/IStandardDataAccess.java | 1 + .../data/query/DataAccessFormat.java | 3 +- .../data/query/DataQueryFormat.java | 1 + .../data/query/RecipeDataQuery.java | 1 + .../gtceu/api/cover/CoverBehavior.java | 15 +- .../gtceu/api/cover/filter/Filter.java | 20 +- .../api/cover/filter/SimpleItemFilter.java | 25 ++ .../gtceu/api/fluids/FluidState.java | 3 +- .../gtceu/api/graphnet/GraphNetBacker.java | 2 +- .../gtceu/api/graphnet/NetNode.java | 5 +- .../api/graphnet/edge/NetFlowSharedEdge.java | 3 +- .../graphnet/pipenet/IPipeNetNodeHandler.java | 1 - .../api/graphnet/pipenet/NodeLossCache.java | 5 +- .../graphnet/pipenet/WorldPipeNetNode.java | 2 +- .../logic/EdgeCoverReferenceLogic.java | 11 +- .../physical/PipeStructureRegistry.java | 1 + .../physical/block/MaterialPipeBlockItem.java | 3 +- .../physical/block/PipeActivableBlock.java | 1 + .../pipenet/physical/block/PipeBlock.java | 1 - .../tile/PipeActivableBlockEntity.java | 4 +- .../physical/tile/PipeCoverHolder.java | 5 +- .../pipenet/predicate/BlockedPredicate.java | 1 + .../pipenet/predicate/FilterPredicate.java | 6 +- .../pipenet/transfer/TransferControl.java | 1 + .../traverse/AbstractTileRoundRobinData.java | 6 +- .../predicate/EdgePredicateHandler.java | 2 +- .../predicate/test/FluidTestObject.java | 3 +- .../predicate/test/ItemTestObject.java | 2 +- .../api/graphnet/servernet/ServerNetNode.java | 3 +- .../traverse/TraverseDataProvider.java | 1 + .../graphnet/traverse/TraverseHelpers.java | 2 +- .../gtceu/api/graphnet/worldnet/WorldNet.java | 2 +- .../api/machine/MachineCoverContainer.java | 5 +- .../renderer/cover/ICoverableRenderer.java | 2 +- .../renderer/pipe/ActivablePipeModel.java | 12 +- .../client/renderer/pipe/CableModel.java | 4 +- .../gtceu/client/renderer/pipe/PipeModel.java | 12 +- .../renderer/pipe/cache/ActivableSQC.java | 2 + .../renderer/pipe/cache/BlockableSQC.java | 2 + .../renderer/pipe/cache/ExtraCappedSQC.java | 3 +- .../renderer/pipe/cache/RestrictiveSQC.java | 2 + .../pipe/cover/CoverRendererBuilder.java | 27 +- .../renderer/pipe/util/ActivableCacheKey.java | 1 + .../pipe/util/SpriteInformationWrapper.java | 2 +- .../renderer/pipe/util/WoodCacheKey.java | 1 + .../KineticMachineBlockEntity.java | 4 +- .../gtceu/common/cover/ConveyorCover.java | 311 ++++++++---------- .../cover/filter/BaseFilterContainer.java | 93 +++--- .../common/cover/filter/MatchResult.java | 1 + .../common/cover/filter/MergabilityInfo.java | 1 + .../gtceu/common/data/GTBlocks.java | 6 +- .../part/OpticalDataHatchMachine.java | 7 +- .../pipelike/block/cable/CableBlock.java | 16 +- .../pipelike/block/cable/CableStructure.java | 1 + .../pipelike/block/laser/LaserPipeBlock.java | 2 + .../pipelike/block/laser/LaserStructure.java | 2 + .../optical/IOpticalTransferController.java | 1 + .../block/optical/OpticalPipeBlock.java | 2 + .../block/optical/OpticalStructure.java | 2 + .../block/pipe/MaterialPipeBlock.java | 1 + .../block/pipe/MaterialPipeStructure.java | 1 + .../pipelike/handlers/LaserNetHandler.java | 6 +- .../pipelike/handlers/OpticalNetHandler.java | 6 +- .../common/pipelike/net/SlowActiveWalker.java | 4 +- .../net/energy/EnergyCapabilityObject.java | 5 +- .../pipelike/net/energy/EnergyFlowLogic.java | 6 +- .../pipelike/net/energy/EnergyGroupData.java | 1 + .../net/energy/EnergyTraverseData.java | 8 +- .../net/energy/IEnergyTransferController.java | 2 + .../net/energy/SuperconductorLogic.java | 1 + .../net/energy/VoltageLimitLogic.java | 1 + .../pipelike/net/energy/VoltageLossLogic.java | 1 + .../pipelike/net/energy/WorldEnergyNet.java | 2 + .../net/fluid/ContainmentFailure.java | 7 +- .../net/fluid/FluidCapabilityObject.java | 29 +- .../net/fluid/FluidContainmentLogic.java | 4 +- .../net/fluid/FluidEQTraverseData.java | 4 +- .../net/fluid/FluidRRTraverseData.java | 7 +- .../pipelike/net/fluid/FluidTraverseData.java | 5 +- .../net/fluid/IFluidTransferController.java | 11 +- .../fluid/IFluidTraverseGuideProvider.java | 3 +- .../pipelike/net/fluid/WorldFluidNet.java | 2 + .../net/item/IItemTransferController.java | 4 +- .../net/item/IItemTraverseGuideProvider.java | 3 +- .../net/item/ItemCapabilityObject.java | 18 +- .../pipelike/net/item/ItemEQTraverseData.java | 6 +- .../pipelike/net/item/ItemRRTraverseData.java | 7 +- .../pipelike/net/item/ItemTraverseData.java | 6 +- .../pipelike/net/item/WorldItemNet.java | 3 +- .../net/laser/ILaserTransferController.java | 1 + .../net/laser/LaserCapabilityObject.java | 14 +- .../pipelike/net/laser/WorldLaserNet.java | 2 + .../net/optical/DataCapabilityObject.java | 8 +- .../pipelike/net/optical/WorldOpticalNet.java | 2 + .../mixins/SpriteResourceLoaderMixin.java | 13 +- .../jade/provider/CableBlockProvider.java | 10 +- .../top/provider/CableInfoProvider.java | 46 +-- .../gtceu/utils/DimensionFacingPos.java | 3 +- .../gtceu/utils/DummyMachineBlockEntity.java | 15 +- .../gtceu/utils/TaskScheduler.java | 2 + 103 files changed, 550 insertions(+), 405 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java b/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java index 3813b7ac2d..568280cc3d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java @@ -92,7 +92,7 @@ public interface ICoverable extends ITickSubscription, IAppearance, ICapabilityP default boolean placeCoverOnSide(Direction side, ItemStack itemStack, CoverDefinition coverDefinition, ServerPlayer player) { CoverBehavior coverBehavior = coverDefinition.createCoverBehavior(this, side); - if (!canPlaceCoverOnSide(coverDefinition, side) || !coverBehavior.canAttach()) { + if (!canPlaceCoverOnSide(coverDefinition, side) || !coverBehavior.canAttach(this, side)) { return false; } if (getCoverAtSide(side) != null) { @@ -276,7 +276,7 @@ static boolean canPlaceCover(CoverDefinition coverDef, ICoverable coverable) { for (Direction facing : GTUtil.DIRECTIONS) { if (coverable.canPlaceCoverOnSide(coverDef, facing)) { var cover = coverDef.createCoverBehavior(coverable, facing); - if (cover.canAttach()) { + if (cover.canAttach(coverable, facing)) { return true; } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java index ae330c09f2..22b9233edc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IComputationDataAccess.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.capability.data; import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; + import org.jetbrains.annotations.NotNull; public interface IComputationDataAccess extends IHatchDataAccess { diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java index 9c29568da9..57ce3a31e5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; + import org.jetbrains.annotations.NotNull; public interface IDataAccess { @@ -10,7 +11,8 @@ public interface IDataAccess { * Queries this {@link IDataAccess} with the specified query. * * @param queryObject the object representing the query. Can be cached in a weak set created by - * {@link com.gregtechceu.gtceu.utils.GTUtil#createWeakHashSet()} in order to prevent endless recursion. + * {@link com.gregtechceu.gtceu.utils.GTUtil#createWeakHashSet()} in order to prevent endless + * recursion. * @return if the query has been cancelled */ boolean accessData(@NotNull DataQueryObject queryObject); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java index d8627d87ee..a44dd6b15c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IStandardDataAccess.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.capability.data; import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; + import org.jetbrains.annotations.NotNull; public interface IStandardDataAccess extends IHatchDataAccess { diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java index 5a56f42de2..069937c6a8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataAccessFormat.java @@ -1,7 +1,8 @@ package com.gregtechceu.gtceu.api.capability.data.query; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.util.StringRepresentable; + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java index 538f26a63c..23d8728cc5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryFormat.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.capability.data.query; import net.minecraft.util.StringRepresentable; + import org.jetbrains.annotations.NotNull; public final class DataQueryFormat implements StringRepresentable { diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java index 83c81e6493..edb450f3f9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/RecipeDataQuery.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.capability.data.query; import com.gregtechceu.gtceu.api.recipe.GTRecipe; + import lombok.Getter; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java index 67350b78ed..3eb0421a95 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverBehavior.java @@ -27,6 +27,8 @@ import net.minecraft.world.level.block.Block; 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.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; @@ -63,6 +65,9 @@ public abstract class CoverBehavior implements IEnhancedManaged, IToolGridHighLi @Persisted protected int redstoneSignalOutput = 0; + @OnlyIn(Dist.CLIENT) + protected @Nullable CoverRenderer renderer; + public CoverBehavior(CoverDefinition definition, ICoverable coverHolder, Direction attachedSide) { this.coverDefinition = definition; this.coverHolder = coverHolder; @@ -96,7 +101,7 @@ public void onChanged() { * * @return true if cover can be attached, false otherwise */ - public boolean canAttach() { + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { return true; } @@ -196,10 +201,14 @@ public boolean forcePipeRenderConnection() { return true; } - public CoverRenderer getRenderer() { - return coverDefinition.getCoverRenderer(); + @OnlyIn(Dist.CLIENT) + public @NotNull CoverRenderer getRenderer() { + if (renderer == null) renderer = buildRenderer(); + return renderer; } + protected abstract CoverRenderer buildRenderer(); + @Override public boolean shouldRenderGrid(Player player, BlockPos pos, BlockState state, ItemStack held, Set toolTypes) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java index 358c46f7da..fd5d16559c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java @@ -1,12 +1,16 @@ package com.gregtechceu.gtceu.api.cover.filter; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; + import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; -import lombok.RequiredArgsConstructor; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.StringRepresentable; +import lombok.RequiredArgsConstructor; + import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; @@ -15,7 +19,7 @@ * @date 2023/3/14 * @implNote Filter */ -public interface Filter> extends Predicate { +public interface Filter> extends Predicate, Function { WidgetGroup openConfigurator(int x, int y); @@ -35,13 +39,21 @@ default boolean testGeneric(Object test) { return this.test((T) test); } + default MatchResult match(T test) { + return this.apply(test); + } + + default MatchResult matchGeneric(Object test) { + return this.apply((T) test); + } + @RequiredArgsConstructor enum FilterType implements StringRepresentable { + ITEM("item", SimpleItemFilter::new), ITEM_TAG("item_tag", TagItemFilter::new), FLUID("fluid", SimpleFluidFilter::new), - FLUID_TAG("fluid_tag", TagFluidFilter::new) - ; + FLUID_TAG("fluid_tag", TagFluidFilter::new); private final String name; private final Supplier> constructor; diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java index d7d4995901..5c21b8f945 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.lowdragmc.lowdraglib.gui.widget.PhantomSlotWidget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; @@ -159,6 +160,12 @@ public int testItemCount(ItemStack itemStack) { return totalItemCount; } + @Override + public MatchResult apply(ItemStack stack) { + int matchedSlot = itemFilterMatch(this.ignoreNbt, stack); + return MatchResult.create(matchedSlot != -1 == !isBlackList(), matches[matchedSlot], matchedSlot); + } + public int getTotalConfiguredItemCount(ItemStack itemStack) { int totalCount = 0; @@ -180,4 +187,22 @@ public void setMaxStackSize(int maxStackSize) { match.setCount(Math.min(match.getCount(), maxStackSize)); } } + + public int itemFilterMatch(boolean ignoreNBTData, ItemStack itemStack) { + for (int i = 0; i < matches.length; i++) { + ItemStack filterStack = matches[i]; + if (!filterStack.isEmpty() && areItemsEqual(ignoreNBTData, filterStack, itemStack)) { + return i; + } + } + return -1; + } + + private static boolean areItemsEqual(boolean ignoreNBTData, + ItemStack filterStack, ItemStack itemStack) { + if (!ItemStack.isSameItem(filterStack, itemStack)) { + return false; + } + return ignoreNBTData || ItemStack.isSameItemSameTags(filterStack, itemStack); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java index 28dc19201f..44cdab131d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java +++ b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidState.java @@ -1,7 +1,8 @@ package com.gregtechceu.gtceu.api.fluids; -import lombok.Getter; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; + +import lombok.Getter; import org.jetbrains.annotations.NotNull; public enum FluidState { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java index 4f59b2be57..409518342b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java @@ -14,11 +14,11 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import net.minecraft.nbt.Tag; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java index 646c4cf22a..42a48fa7fc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java @@ -9,11 +9,12 @@ import com.lowdragmc.lowdraglib.syncdata.IContentChangeAware; import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; -import lombok.Getter; -import lombok.Setter; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; +import lombok.Getter; +import lombok.Setter; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java index 691aee9866..9cfc9a91b4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/NetFlowSharedEdge.java @@ -3,9 +3,10 @@ import com.gregtechceu.gtceu.api.graphnet.IGraphNet; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import net.minecraft.util.Mth; + import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.util.Mth; import org.jetbrains.annotations.Nullable; import java.util.List; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java index fc1f2d37a1..bdcc381006 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/IPipeNetNodeHandler.java @@ -8,7 +8,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelAccessor; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java index 0976efc8f7..b8714c0658 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/NodeLossCache.java @@ -3,11 +3,12 @@ import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseData; - import com.gregtechceu.gtceu.utils.TaskScheduler; import com.gregtechceu.gtceu.utils.function.Task; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; + import net.minecraft.world.level.Level; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.Nullable; import java.util.Map; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java index b25c99491f..47e2759854 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -5,10 +5,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.IWorldPipeNetTile; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNetNode; - import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTMaterials; + import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java index dccdeeb300..95d08bac3d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java @@ -3,19 +3,20 @@ import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; - import com.gregtechceu.gtceu.utils.DimensionFacingPos; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; + import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; - import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; + import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -124,10 +125,12 @@ public CompoundTag serializeNBT() { @Override public void deserializeNBT(CompoundTag nbt) { this.coverSourcePos = new DimensionFacingPos(BlockPos.of(nbt.getLong("SourcePos")), - GTUtil.DIRECTIONS[nbt.getByte("SourceFacing")], ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("SourceDim")))); + GTUtil.DIRECTIONS[nbt.getByte("SourceFacing")], + ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("SourceDim")))); this.coverSource = new WeakReference<>(null); this.coverTargetPos = new DimensionFacingPos(BlockPos.of(nbt.getLong("TargetPos")), - GTUtil.DIRECTIONS[nbt.getByte("TargetFacing")], ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("TargetDim")))); + GTUtil.DIRECTIONS[nbt.getByte("TargetFacing")], + ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("TargetDim")))); this.coverTarget = coverSource; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java index f37751a880..b8ea01338c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; import com.gregtechceu.gtceu.utils.GTUtil; + import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index 8b7cc3e235..2f26cc78a1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -22,6 +22,7 @@ public MaterialPipeBlockItem(Item.Properties properties, PipeMaterialBlock block @Override public Component getName(ItemStack stack) { Material material = getBlock().material; - return material == null ? Component.literal("unnamed") : getBlock().getStructure().getPrefix().getLocalizedName(material); + return material == null ? Component.literal("unnamed") : + getBlock().getStructure().getPrefix().getLocalizedName(material); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java index 5b15e1e005..15b229499e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java @@ -8,6 +8,7 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 660be46111..bba2531d58 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -23,7 +23,6 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; -import com.lowdragmc.lowdraglib.client.renderer.IBlockRendererProvider; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java index d7eaf9bda8..b719f8deee 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java @@ -1,11 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; -import lombok.Getter; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; - import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; + +import lombok.Getter; import org.jetbrains.annotations.NotNull; public class PipeActivableBlockEntity extends PipeBlockEntity implements IActivable { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java index 50c5c12b71..2a13c9aa4f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -8,6 +8,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; @@ -16,7 +17,7 @@ import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; -import lombok.Getter; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.entity.player.Player; @@ -26,6 +27,8 @@ import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java index 6252567ca5..00884edb88 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import net.minecraft.nbt.ByteTag; + import org.jetbrains.annotations.NotNull; public final class BlockedPredicate extends EdgePredicate { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java index 0ef29aae6a..49e36a9b7a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java @@ -3,12 +3,12 @@ import com.gregtechceu.gtceu.api.cover.filter.Filter; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; - import com.gregtechceu.gtceu.common.cover.filter.BaseFilterContainer; -import lombok.Setter; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; + +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java index 6531b7f172..e0f944574c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/transfer/TransferControl.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.transfer; import net.minecraft.util.StringRepresentable; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java index 5bb85a2b79..103bd01d46 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/traverse/AbstractTileRoundRobinData.java @@ -4,13 +4,13 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCapabilityWrapper; import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinData; - import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.common.capabilities.Capability; - import net.minecraftforge.common.util.LazyOptional; + import org.apache.commons.lang3.mutable.MutableByte; import org.jetbrains.annotations.MustBeInvokedByOverriders; import org.jetbrains.annotations.NotNull; @@ -58,7 +58,7 @@ public boolean hasCapabilityAtPointer(@NotNull Capability capability, WorldPi @Nullable public LazyOptional getCapabilityAtPointer(@NotNull Capability capability, WorldPipeNetNode node, - @Nullable SimulatorKey simulator) { + @Nullable SimulatorKey simulator) { if (pointerFinished(simulator)) return null; PipeCapabilityWrapper wrapper = node.getBlockEntity().getWrapperForNode(node); Direction pointer = getPointerFacing(simulator); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java index a97ace306d..d29adf3813 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java @@ -3,10 +3,10 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.util.StringRepresentable; -import net.minecraftforge.common.util.INBTSerializable; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java index 6bb88fa58b..0561b9c9b4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java @@ -1,8 +1,9 @@ package com.gregtechceu.gtceu.api.graphnet.predicate.test; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; + import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.material.Fluid; -import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java index c349d384d4..b20d910777 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java @@ -1,9 +1,9 @@ package com.gregtechceu.gtceu.api.graphnet.predicate.test; import net.minecraft.nbt.CompoundTag; - import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; + import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java index 356b4b094e..7a1277bb8b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNetNode.java @@ -30,7 +30,8 @@ public CompoundTag serializeNBT() { public void deserializeNBT(CompoundTag nbt) { super.deserializeNBT(nbt); BlockPos pos = BlockPos.of(nbt.getLong("Pos")); - this.pos = GlobalPos.of(ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("Dim"))), pos); + this.pos = GlobalPos.of(ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("Dim"))), + pos); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java index ef6a4f7865..af83c49f5a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseDataProvider.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.graphnet.IGraphNet; import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java index 8b6e9fa2f8..feebc15b2f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/TraverseHelpers.java @@ -5,8 +5,8 @@ import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; import com.gregtechceu.gtceu.api.graphnet.path.INetPath; import com.gregtechceu.gtceu.api.graphnet.traverse.util.FlowConsumptionStack; - import com.gregtechceu.gtceu.utils.GTUtil; + import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java index 598c394bbd..e43c69155e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -19,10 +19,10 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; +import net.minecraft.world.level.saveddata.SavedData; import lombok.Getter; import lombok.Setter; -import net.minecraft.world.level.saveddata.SavedData; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java index f5847db34e..1df7fcab96 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java @@ -25,10 +25,10 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.shapes.VoxelShape; - -import lombok.Getter; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -210,7 +210,6 @@ public void updateInputRedstoneSignals() { } } - @Override public void setCoverAtSide(@Nullable CoverBehavior coverBehavior, Direction side) { switch (side) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java index 31f7e26145..731fe39570 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java @@ -82,7 +82,7 @@ default void renderCovers(List quads, @Nullable Direction side, Rando .cube(cube).cubeUV().tintIndex(-1).bake()); } } - //cover.getCoverRenderer().renderCover(quads, side, rand, cover, modelFacing, pos, level, modelState); + // cover.getCoverRenderer().renderCover(quads, side, rand, cover, modelFacing, pos, level, modelState); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java index 0d08749393..448b3370b0 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -12,8 +12,10 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.utils.SupplierMemoizer; + import com.lowdragmc.lowdraglib.client.bakedpipeline.Quad; import com.lowdragmc.lowdraglib.client.model.ModelFactory; + import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.resources.model.BakedModel; @@ -25,6 +27,7 @@ import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.model.data.ModelProperty; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -40,7 +43,8 @@ public class ActivablePipeModel extends AbstractPipeModel { public static final ModelProperty ACTIVE_PROPERTY = new ModelProperty<>(); - public static final ActivablePipeModel OPTICAL = new ActivablePipeModel(() -> GTCEu.id("block/pipe/pipe_optical_in"), + public static final ActivablePipeModel OPTICAL = new ActivablePipeModel( + () -> GTCEu.id("block/pipe/pipe_optical_in"), () -> GTCEu.id("block/pipe/pipe_optical_side"), () -> GTCEu.id("block/pipe/pipe_optical_side_overlay"), () -> GTCEu.id("block/pipe/pipe_optical_side_overlay_active"), @@ -80,7 +84,8 @@ public ActivablePipeModel(@NotNull Supplier inTex, @NotNull Su byte blockedMask, ColorData data, @Nullable Material frameMaterial, byte frameMask, byte coverMask) { // don't render the main shape to the bloom layer - List quads = super.getQuads(key, connectionMask, closedMask, blockedMask, data, frameMaterial, frameMask, coverMask); + List quads = super.getQuads(key, connectionMask, closedMask, blockedMask, data, frameMaterial, + frameMask, coverMask); if (key.isActive() && allowActive()) { if (emissiveActive) { @@ -131,7 +136,8 @@ public boolean allowActive() { } @Override - protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity) { + protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, + LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; return new PipeItemModel<>(this, new ActivableCacheKey(block.getStructure().getRenderThickness(), false), diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java index f0c1126865..4b1af6f098 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java @@ -15,7 +15,9 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; import com.gregtechceu.gtceu.utils.SupplierMemoizer; + import com.lowdragmc.lowdraglib.client.model.ModelFactory; + import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelResourceLocation; @@ -25,6 +27,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.model.data.ModelData; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -40,7 +43,6 @@ public class CableModel extends AbstractPipeModel { public static final CableModel INSTANCE = new CableModel("wire"); public static final CableModel[] INSULATED_INSTANCES = new CableModel[5]; - @OnlyIn(Dist.CLIENT) public static final Supplier WIRE = () -> MaterialIconType.wire .getBlockTexturePath(MaterialIconSet.DULL, true).withSuffix("_side"); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java index 34cfe1bb46..93064cb586 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -15,7 +15,9 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.client.renderer.pipe.util.WoodCacheKey; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.client.model.ModelFactory; + import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.BakedModel; @@ -26,6 +28,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.model.data.ModelData; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -81,7 +84,8 @@ public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, @NotNull PipeSpriteWood } public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, boolean restrictive, String variant) { - this(inTex, wood -> wood ? GTCEu.id("block/pipe/pipe_side_wood") : GTCEu.id("block/pipe/pipe_side"), restrictive, variant); + this(inTex, wood -> wood ? GTCEu.id("block/pipe/pipe_side_wood") : GTCEu.id("block/pipe/pipe_side"), + restrictive, variant); } @Override @@ -112,7 +116,8 @@ protected StructureQuadCache constructForKey(WoodCacheKey key) { sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex.getTexture(key.isWood())), 0); } if (restrictiveSprite == null && restrictiveTex != null) { - restrictiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(restrictiveTex.getTexture(key.isWood())), -1); + restrictiveSprite = new SpriteInformation( + ModelFactory.getBlockSprite(restrictiveTex.getTexture(key.isWood())), -1); } if (blockedSprite == null) { blockedSprite = new SpriteInformation(ModelFactory.getBlockSprite(blockedTex.getTexture(key.isWood())), -1); @@ -129,7 +134,8 @@ protected StructureQuadCache constructForKey(WoodCacheKey key) { } @Override - protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity) { + protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, + LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; Material mater = null; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java index 024bd3b738..22da82c754 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java @@ -6,10 +6,12 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; import java.util.EnumMap; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java index 3ce564406e..0455b4ddf9 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java @@ -6,8 +6,10 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; import java.util.EnumMap; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java index a858846864..0bf4039158 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java @@ -1,16 +1,17 @@ package com.gregtechceu.gtceu.client.renderer.pipe.cache; -import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; import java.util.EnumMap; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java index 1e8b4ac3b0..6ee8dd73ce 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java @@ -6,8 +6,10 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; import java.util.EnumMap; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java index e2877423a8..f0ad5a65aa 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java @@ -11,10 +11,13 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.client.model.ModelFactory; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; @@ -97,17 +100,20 @@ protected static void addPlates(List quads, List plateQuad } } - protected final TextureAtlasSprite sprite; - protected final TextureAtlasSprite spriteEmissive; + protected final ResourceLocation texture; + protected final ResourceLocation textureEmissive; + + protected TextureAtlasSprite sprite; + protected TextureAtlasSprite spriteEmissive; protected UVMapper mapper = defaultMapper; protected UVMapper mapperEmissive = defaultMapper; protected ColorQuadCache plateQuads = PLATE_QUADS; - public CoverRendererBuilder(@NotNull TextureAtlasSprite sprite, @Nullable TextureAtlasSprite spriteEmissive) { - this.sprite = sprite; - this.spriteEmissive = spriteEmissive; + public CoverRendererBuilder(@NotNull ResourceLocation texture, @Nullable ResourceLocation textureEmissive) { + this.texture = texture; + this.textureEmissive = textureEmissive; } public CoverRendererBuilder setMapper(@NotNull UVMapper mapper) { @@ -130,14 +136,21 @@ protected static List getPlates(Direction facing, ColorData data, Col } public CoverRenderer build() { + if (sprite == null) { + sprite = ModelFactory.getBlockSprite(texture); + } + if (spriteEmissive == null && textureEmissive != null) { + spriteEmissive = ModelFactory.getBlockSprite(textureEmissive); + } + EnumMap> spriteQuads = new EnumMap<>(Direction.class); - EnumMap> spriteEmissiveQuads = spriteEmissive != null ? + EnumMap> spriteEmissiveQuads = textureEmissive != null ? new EnumMap<>(Direction.class) : null; for (Direction facing : GTUtil.DIRECTIONS) { spriteQuads.put(facing, ImmutablePair.of( QuadHelper.buildQuad(facing, OVERLAY_BOXES_1.get(facing), mapper, sprite), QuadHelper.buildQuad(facing.getOpposite(), OVERLAY_BOXES_1.get(facing), mapper, sprite))); - if (spriteEmissive != null) spriteEmissiveQuads.put(facing, ImmutablePair.of( + if (textureEmissive != null) spriteEmissiveQuads.put(facing, ImmutablePair.of( QuadHelper.buildQuad(facing, OVERLAY_BOXES_2.get(facing), mapperEmissive, spriteEmissive), QuadHelper.buildQuad(facing.getOpposite(), OVERLAY_BOXES_2.get(facing), mapperEmissive, spriteEmissive))); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java index d51d817024..e7c0ad4a65 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java @@ -2,6 +2,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.Nullable; @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java index 5efe903e13..2ad598de29 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java @@ -7,7 +7,7 @@ import java.util.function.Supplier; public class SpriteInformationWrapper implements Supplier, Consumer, - BiConsumer { + BiConsumer { private SpriteInformation sprite; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java index ea5ff3d9dc..fd39953ecf 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java index fdfbfd360e..376b4b9441 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java @@ -319,9 +319,7 @@ protected void read(CompoundTag compound, boolean clientPacket) { } @Override - public void onNeighborChanged(@NotNull Direction facing) { - - } + public void onNeighborChanged(@NotNull Direction facing) {} @Override public void markAsDirty() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java index 020282596e..6b217927dd 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java @@ -1,8 +1,10 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.capability.IControllable; import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.capability.recipe.IO; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; @@ -17,48 +19,56 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; +import com.gregtechceu.gtceu.api.gui.GuiTextures; +import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; +import com.gregtechceu.gtceu.api.gui.widget.IntInputWidget; import com.gregtechceu.gtceu.api.machine.ConditionalSubscriptionHandler; import com.gregtechceu.gtceu.api.transfer.item.ItemTransferDelegate; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.DistributionMode; -import com.gregtechceu.gtceu.common.cover.data.ItemFilterMode; import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.gregtechceu.gtceu.common.cover.filter.MergabilityInfo; import com.gregtechceu.gtceu.common.pipelike.net.item.*; import com.gregtechceu.gtceu.utils.ItemStackHashStrategy; +import com.lowdragmc.lowdraglib.gui.texture.GuiTextureGroup; +import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; +import com.lowdragmc.lowdraglib.gui.widget.SwitchWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; +import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.side.item.ItemTransferHelper; +import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; +import com.lowdragmc.lowdraglib.utils.LocalizationUtils; -import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import mezz.jei.api.gui.drawable.IDrawable; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; - -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; -import lombok.Getter; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraft.world.phys.BlockHitResult; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.IItemHandler; + +import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; +import lombok.Getter; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -78,7 +88,7 @@ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class ConveyorCover extends CoverBehavior implements IUICover, IControllable, - TransferControlProvider, IItemTransferController { + TransferControlProvider, IItemTransferController { public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(ConveyorCover.class, CoverBehavior.MANAGED_FIELD_HOLDER); @@ -101,10 +111,16 @@ public class ConveyorCover extends CoverBehavior implements IUICover, IControlla @Getter protected ManualIOMode manualIOMode = ManualIOMode.DISABLED; @Persisted + @Getter protected boolean isWorkingEnabled = true; protected int itemsLeftToTransferLastSecond; + private CoverableItemTransferWrapper itemHandlerWrapper; private Widget ioModeSwitch; + protected final Object2ObjectLinkedOpenHashMap> roundRobinCache = new Object2ObjectLinkedOpenHashMap<>(); + + protected @Nullable CoverRenderer rendererInverted; + @Persisted @DescSynced @Getter @@ -148,11 +164,6 @@ public ManagedFieldHolder getFieldHolder() { return MANAGED_FIELD_HOLDER; } - @Override - public boolean canAttach() { - return getOwnItemTransfer() != null; - } - public void setTransferRate(int transferRate) { if (transferRate <= maxItemTransferRate) { this.transferRate = transferRate; @@ -221,12 +232,15 @@ protected void update() { BlockEntity tileEntity = coverHolder.getNeighbor(side); IItemHandler itemHandler = tileEntity == null ? null : tileEntity.getCapability(ForgeCapabilities.ITEM_HANDLER, side.getOpposite()).resolve().orElse(null); - IItemHandler myItemHandler = coverHolder.getCapability(ForgeCapabilities.ITEM_HANDLER, side).resolve().orElse(null); + IItemHandler myItemHandler = coverHolder.getCapability(ForgeCapabilities.ITEM_HANDLER, side).resolve() + .orElse(null); if (itemHandler != null && myItemHandler != null) { + IItemTransfer itemTransfer = ItemTransferHelperImpl.toItemTransfer(itemHandler); + IItemTransfer myItemTransfer = ItemTransferHelperImpl.toItemTransfer(myItemHandler); if (io == IO.OUT) { - performTransferOnUpdate(myItemHandler, itemHandler); + performTransferOnUpdate(myItemTransfer, itemTransfer); } else { - performTransferOnUpdate(itemHandler, myItemHandler); + performTransferOnUpdate(itemTransfer, myItemTransfer); } } } @@ -247,7 +261,7 @@ protected void refreshBuffer(int transferRate) { this.itemsLeftToTransferLastSecond = transferRate; } - protected void performTransferOnUpdate(@NotNull IItemHandler sourceHandler, @NotNull IItemHandler destHandler) { + protected void performTransferOnUpdate(@NotNull IItemTransfer sourceHandler, @NotNull IItemTransfer destHandler) { reportItemsTransfer(performTransfer(sourceHandler, destHandler, false, i -> 0, i -> getItemsLeftToTransfer(), null)); } @@ -266,11 +280,12 @@ protected void performTransferOnUpdate(@NotNull IItemHandler sourceHandler, @Not * Each filter slot will report its transfer before the next slot is calculated. * @return how much was transferred in total. */ - protected int performTransfer(@NotNull IItemHandler sourceHandler, @NotNull IItemHandler destHandler, + protected int performTransfer(@NotNull IItemTransfer sourceHandler, @NotNull IItemTransfer destHandler, boolean byFilterSlot, @NotNull IntUnaryOperator minTransfer, - @NotNull IntUnaryOperator maxTransfer, @Nullable BiConsumer transferReport) { + @NotNull IntUnaryOperator maxTransfer, + @Nullable BiConsumer transferReport) { ItemFilter filter = filterHandler.getFilter(); - byFilterSlot = byFilterSlot && filter != null; // can't be by filter slot if there is no filter + byFilterSlot = byFilterSlot && filter != ItemFilter.EMPTY; // can't be by filter slot if there is no filter Int2IntArrayMap extractableByFilterSlot = new Int2IntArrayMap(); Int2ObjectArrayMap> filterSlotToMergability = new Int2ObjectArrayMap<>(); for (int i = 0; i < sourceHandler.getSlots(); i++) { @@ -278,7 +293,7 @@ protected int performTransfer(@NotNull IItemHandler sourceHandler, @NotNull IIte int extracted = stack.getCount(); if (extracted == 0) continue; MatchResult match = null; - if (filter == null || (match = filter.match(stack)).isMatched()) { + if (filter == ItemFilter.EMPTY || (match = filter.match(stack)).isMatched()) { int filterSlot = -1; if (byFilterSlot) { filterSlot = match.getFilterIndex(); @@ -341,7 +356,7 @@ protected int performTransfer(@NotNull IItemHandler sourceHandler, @NotNull IIte return totalTransfer; } - protected int insertToHandler(@NotNull IItemHandler destHandler, ItemTestObject testObject, int count, + protected int insertToHandler(@NotNull IItemTransfer destHandler, ItemTestObject testObject, int count, boolean simulate) { if (!(destHandler instanceof IItemTraverseGuideProvider provider)) { return simpleInsert(destHandler, testObject, count, simulate); @@ -402,7 +417,7 @@ protected Object2ObjectLinkedOpenHashMap countInventoryItemsByType(@NotNull IItemHandler inventory) { + protected Map countInventoryItemsByType(@NotNull IItemTransfer inventory) { Map result = new Object2ObjectOpenCustomHashMap<>( ItemStackHashStrategy.comparingAllButCount()); for (int srcIndex = 0; srcIndex < inventory.getSlots(); srcIndex++) { @@ -472,7 +487,7 @@ protected Map countInventoryItemsByType(@NotNull IItemH continue; } - var matchResult = itemFilterContainer.match(itemStack); + var matchResult = getFilterHandler().getFilter().match(itemStack); if (!matchResult.isMatched()) continue; if (!result.containsKey(itemStack)) { @@ -491,159 +506,96 @@ protected Map countInventoryItemsByType(@NotNull IItemH } @Override - public boolean canAttach(@NotNull CoverableView coverable, @NotNull Direction side) { - return coverable.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, getAttachedSide()); - } - - @Override - public boolean canInteractWithOutputSide() { - return true; + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(ForgeCapabilities.ITEM_HANDLER, attachedSide).isPresent(); } @Override - public void onRemoval() { - dropInventoryContents(itemFilterContainer); - } - - @Override - public void renderCover(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline, - Cuboid6 plateBox, BlockRenderLayer layer) { - if (conveyorMode == ConveyorMode.EXPORT) { - Textures.CONVEYOR_OVERLAY.renderSided(getAttachedSide(), plateBox, renderState, pipeline, translation); - } else { - Textures.CONVEYOR_OVERLAY_INVERTED.renderSided(getAttachedSide(), plateBox, renderState, pipeline, - translation); - } - } - - @Override - public @NotNull EnumActionResult onScrewdriverClick(@NotNull EntityPlayer playerIn, @NotNull EnumHand hand, - @NotNull RayTraceResult hitResult) { - if (!getCoverableView().getWorld().isRemote) { - openUI((EntityPlayerMP) playerIn); + public InteractionResult onScrewdriverClick(Player playerIn, InteractionHand hand, BlockHitResult hitResult) { + if (!coverHolder.getLevel().isClientSide) { + createUI(playerIn); } - return EnumActionResult.SUCCESS; + return InteractionResult.SUCCESS; } @Override public LazyOptional getCapability(@NotNull Capability capability, LazyOptional defaultValue) { if (capability == ForgeCapabilities.ITEM_HANDLER) { - if (defaultValue == null) { - return null; + if (!defaultValue.isPresent()) { + return LazyOptional.empty(); } - IItemHandler delegate = (IItemHandler) defaultValue; - if (itemHandlerWrapper == null || itemHandlerWrapper.delegate != defaultValue) { - this.itemHandlerWrapper = new CoverableItemTransferWrapper(defaultValue); + IItemHandler delegate = (IItemHandler) defaultValue.resolve().orElse(null); + if (itemHandlerWrapper == null || itemHandlerWrapper.delegate != delegate) { + this.itemHandlerWrapper = new CoverableItemTransferWrapper( + ItemTransferHelperImpl.toItemTransfer(delegate)); } - return itemHandlerWrapper; - return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(itemHandlerWrapper); + return ForgeCapabilities.ITEM_HANDLER.orEmpty(capability, + LazyOptional.of(() -> ItemTransferHelperImpl.toItemHandler(itemHandlerWrapper))); } - if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) { - return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this); + if (capability == GTCapability.CAPABILITY_CONTROLLABLE) { + return GTCapability.CAPABILITY_CONTROLLABLE.orEmpty(capability, LazyOptional.of(() -> this)); } return defaultValue; } - @Override - public boolean usesMui2() { - return true; + @NotNull + protected String getUITitle() { + return "cover.conveyor.title"; + } + + protected void buildAdditionalUI(WidgetGroup group) { + // Do nothing in the base implementation. This is intended to be overridden by subclasses. + } + + protected void configureFilter() { + // Do nothing in the base implementation. This is intended to be overridden by subclasses. } @Override - public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncManager) { - var panel = GTGuis.createPanel(this, 176, 192 + 18); - - getItemFilterContainer().setMaxTransferSize(getMaxStackSize()); - - return panel.child(CoverWithUI.createTitleRow(getPickItem())) - .child(createUI(panel, guiSyncManager)) - .bindPlayerInventory(); - } - - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager guiSyncManager) { - var column = new Column().top(24).margin(7, 0) - .widthRel(1f).coverChildrenHeight(); - - EnumSyncValue manualIOmode = new EnumSyncValue<>(ManualImportExportMode.class, - this::getManualImportExportMode, this::setManualImportExportMode); - - EnumSyncValue conveyorMode = new EnumSyncValue<>(ConveyorMode.class, - this::getConveyorMode, this::setConveyorMode); - - IntSyncValue throughput = new IntSyncValue(this::getTransferRate, this::setTransferRate); - throughput.updateCacheFromSource(true); - - StringSyncValue formattedThroughput = new StringSyncValue(throughput::getStringValue, - throughput::setStringValue); - - EnumSyncValue distributionMode = new EnumSyncValue<>(DistributionMode.class, - this::getDistributionMode, this::setDistributionMode); - - guiSyncManager.syncValue("manual_io", manualIOmode); - guiSyncManager.syncValue("conveyor_mode", conveyorMode); - guiSyncManager.syncValue("distribution_mode", distributionMode); - guiSyncManager.syncValue("throughput", throughput); - - if (createThroughputRow()) - column.child(new Row().coverChildrenHeight() - .marginBottom(2).widthRel(1f) - .child(new ButtonWidget<>() - .left(0).width(18) - .onMousePressed(mouseButton -> { - int val = throughput.getValue() - getIncrementValue(MouseData.create(mouseButton)); - throughput.setValue(val, true, true); - Interactable.playButtonClickSound(); - return true; - }) - .onUpdateListener(w -> w.overlay(createAdjustOverlay(false)))) - .child(new TextFieldWidget() - .left(18).right(18) - .setTextColor(Color.WHITE.darker(1)) - .setNumbers(1, maxItemTransferRate) - .value(formattedThroughput) - .background(GTGuiTextures.DISPLAY)) - .child(new ButtonWidget<>() - .right(0).width(18) - .onMousePressed(mouseButton -> { - int val = throughput.getValue() + getIncrementValue(MouseData.create(mouseButton)); - throughput.setValue(val, true, true); - Interactable.playButtonClickSound(); - return true; - }) - .onUpdateListener(w -> w.overlay(createAdjustOverlay(true))))); - - if (createFilterRow()) - column.child(getItemFilterContainer().initUI(mainPanel, guiSyncManager)); - - if (createManualIOModeRow()) - column.child(new EnumRowBuilder<>(ManualImportExportMode.class) - .value(manualIOmode) - .lang("cover.generic.manual_io") - .overlay(new IDrawable[] { - new DynamicDrawable(() -> conveyorMode.getValue().isImport() ? - GTGuiTextures.MANUAL_IO_OVERLAY_OUT[0] : GTGuiTextures.MANUAL_IO_OVERLAY_IN[0]), - new DynamicDrawable(() -> conveyorMode.getValue().isImport() ? - GTGuiTextures.MANUAL_IO_OVERLAY_OUT[1] : GTGuiTextures.MANUAL_IO_OVERLAY_IN[1]), - new DynamicDrawable(() -> conveyorMode.getValue().isImport() ? - GTGuiTextures.MANUAL_IO_OVERLAY_OUT[2] : GTGuiTextures.MANUAL_IO_OVERLAY_IN[2]) + public Widget createUIWidget() { + final var group = new WidgetGroup(0, 0, 176, 137); + group.addWidget(new LabelWidget(10, 5, LocalizationUtils.format(getUITitle(), GTValues.VN[tier]))); + + if (createThroughputRow()) { + group.addWidget(new IntInputWidget(10, 20, 156, 20, () -> this.transferRate, this::setTransferRate) + .setMin(1).setMax(maxItemTransferRate)); + } + + if (createConveyorModeRow()) { + ioModeSwitch = new SwitchWidget(10, 45, 20, 20, + (clickData, value) -> { + setIo(value ? IO.IN : IO.OUT); + ioModeSwitch.setHoverTooltips( + LocalizationUtils.format("cover.conveyor.mode", LocalizationUtils.format(io.tooltip))); }) - .build()); + .setTexture( + new GuiTextureGroup(GuiTextures.VANILLA_BUTTON, IO.OUT.icon), + new GuiTextureGroup(GuiTextures.VANILLA_BUTTON, IO.IN.icon)) + .setPressed(io == IO.IN) + .setHoverTooltips( + LocalizationUtils.format("cover.conveyor.mode", LocalizationUtils.format(io.tooltip))); + group.addWidget(ioModeSwitch); + } - if (createConveyorModeRow()) - column.child(new EnumRowBuilder<>(ConveyorMode.class) - .value(conveyorMode) - .lang("cover.generic.io") - .overlay(GTGuiTextures.CONVEYOR_MODE_OVERLAY) - .build()); + if (createDistributionModeRow()) { + group.addWidget(new EnumSelectorWidget<>(146, 67, 20, 20, + DistributionMode.VALUES, distributionMode, this::setDistributionMode)); + } - if (createDistributionModeRow()) - column.child(new EnumRowBuilder<>(DistributionMode.class) - .value(distributionMode) - .overlay(16, GTGuiTextures.DISTRIBUTION_MODE_OVERLAY) - .lang("cover.generic.distribution.name") - .build()); + if (createManualIOModeRow()) { + group.addWidget(new EnumSelectorWidget<>(146, 107, 20, 20, + ManualIOMode.VALUES, manualIOMode, this::setManualIOMode) + .setHoverTooltips("cover.universal.manual_import_export.mode.description")); + } - return column; + if (createFilterRow()) { + group.addWidget(filterHandler.createFilterSlotUI(125, 108)); + group.addWidget(filterHandler.createFilterConfigUI(10, 72, 156, 60)); + } + + buildAdditionalUI(group); + + return group; } protected boolean createThroughputRow() { @@ -668,7 +620,7 @@ protected boolean createDistributionModeRow() { protected int getMaxStackSize() { return 1; - }1 + } @Override public @NotNull CoverRenderer getRenderer() { @@ -683,16 +635,13 @@ protected int getMaxStackSize() { @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(Textures.CONVEYOR_OVERLAY).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_conveyor"), + GTCEu.id("block/cover/overlay_conveyor_emissive")).build(); } protected CoverRenderer buildRendererInverted() { - return new CoverRendererBuilder(Textures.CONVEYOR_OVERLAY_INVERTED).build(); - } - - @OnlyIn(Dist.CLIENT) - protected @NotNull ResourceLocation getPlateTexture() { - return Textures.VOLTAGE_CASINGS[this.tier].getSpriteOnSide(SimpleSidedCubeRenderer.RenderSide.SIDE); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_conveyor_inverted"), + GTCEu.id("block/cover/overlay_conveyor_inverted_emissive")).build(); } private class CoverableItemTransferWrapper extends ItemTransferDelegate { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java index 15a046f158..f928020e96 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java @@ -2,11 +2,14 @@ import com.gregtechceu.gtceu.api.blockentity.IDirtyNotifiable; import com.gregtechceu.gtceu.api.cover.filter.ItemFilter; + import com.lowdragmc.lowdraglib.misc.ItemStackTransfer; + import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -113,7 +116,7 @@ public int getMaxTransferSize() { public void setMaxTransferSize(int maxTransferSize) { this.maxTransferSize = Mth.clamp(maxTransferSize, 1, Integer.MAX_VALUE); this.transferSize = Mth.clamp(this.transferSize, 1, this.maxTransferSize); - //if (hasFilter()) currentFilter.setMaxTransferSize(this.maxTransferSize); + // if (hasFilter()) currentFilter.setMaxTransferSize(this.maxTransferSize); } public final boolean hasFilter() { @@ -128,7 +131,7 @@ public final void setItemFilter(@Nullable ItemFilter newFilter) { this.currentFilter = newFilter; if (hasFilter()) { this.currentFilter.setOnUpdated($ -> this.dirtyNotifiable.markAsDirty()); - //this.currentFilter.setMaxTransferSize(this.maxTransferSize); + // this.currentFilter.setMaxTransferSize(this.maxTransferSize); } if (onFilterInstanceChange != null) { this.onFilterInstanceChange.run(); @@ -136,7 +139,7 @@ public final void setItemFilter(@Nullable ItemFilter newFilter) { } public boolean showGlobalTransferLimitSlider() { - return this.maxTransferSize > 0 && (!hasFilter()/* || getFilter().showGlobalTransferLimitSlider()*/); + return this.maxTransferSize > 0 && (!hasFilter()/* || getFilter().showGlobalTransferLimitSlider() */); } public void setBlacklistFilter(boolean blacklistFilter) { @@ -195,48 +198,48 @@ public void handleLegacyNBT(CompoundTag nbt) { /** Uses Cleanroom MUI */ // TODO ui /* - public IWidget initUI(ModularPanel main, PanelSyncManager manager) { - PanelSyncHandler panel = manager.panel("filter_panel", main, (syncManager, syncHandler) -> { - var filter = hasFilter() ? getFilter() : BaseFilter.ERROR_FILTER; - filter.setMaxTransferSize(getMaxTransferSize()); - return filter.createPopupPanel(syncManager); - }); - - var filterButton = new ButtonWidget<>(); - filterButton.setEnabled(hasFilter()); - - return new Row().coverChildrenHeight() - .marginBottom(2).widthRel(1f) - .child(new ItemSlot() - .slot(SyncHandlers.itemSlot(this, 0) - .filter(this::isItemValid) - .singletonSlotGroup(101) - .changeListener((newItem, onlyAmountChanged, client, init) -> { - if (!isItemValid(newItem) && panel.isPanelOpen()) { - panel.closePanel(); - } - })) - .size(18).marginRight(2) - .background(GTGuiTextures.SLOT, GTGuiTextures.FILTER_SLOT_OVERLAY.asIcon().size(16))) - .child(filterButton - .background(GTGuiTextures.MC_BUTTON, GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) - .hoverBackground(GuiTextures.MC_BUTTON_HOVERED, - GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) - .setEnabledIf(w -> hasFilter()) - .onMousePressed(i -> { - if (!panel.isPanelOpen()) { - panel.openPanel(); - } else { - panel.closePanel(); - } - Interactable.playButtonClickSound(); - return true; - })) - .child(IKey.dynamic(this::getFilterName) - .alignment(Alignment.CenterRight).asWidget() - .left(36).right(0).height(18)); - } - */ + * public IWidget initUI(ModularPanel main, PanelSyncManager manager) { + * PanelSyncHandler panel = manager.panel("filter_panel", main, (syncManager, syncHandler) -> { + * var filter = hasFilter() ? getFilter() : BaseFilter.ERROR_FILTER; + * filter.setMaxTransferSize(getMaxTransferSize()); + * return filter.createPopupPanel(syncManager); + * }); + * + * var filterButton = new ButtonWidget<>(); + * filterButton.setEnabled(hasFilter()); + * + * return new Row().coverChildrenHeight() + * .marginBottom(2).widthRel(1f) + * .child(new ItemSlot() + * .slot(SyncHandlers.itemSlot(this, 0) + * .filter(this::isItemValid) + * .singletonSlotGroup(101) + * .changeListener((newItem, onlyAmountChanged, client, init) -> { + * if (!isItemValid(newItem) && panel.isPanelOpen()) { + * panel.closePanel(); + * } + * })) + * .size(18).marginRight(2) + * .background(GTGuiTextures.SLOT, GTGuiTextures.FILTER_SLOT_OVERLAY.asIcon().size(16))) + * .child(filterButton + * .background(GTGuiTextures.MC_BUTTON, GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) + * .hoverBackground(GuiTextures.MC_BUTTON_HOVERED, + * GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) + * .setEnabledIf(w -> hasFilter()) + * .onMousePressed(i -> { + * if (!panel.isPanelOpen()) { + * panel.openPanel(); + * } else { + * panel.closePanel(); + * } + * Interactable.playButtonClickSound(); + * return true; + * })) + * .child(IKey.dynamic(this::getFilterName) + * .alignment(Alignment.CenterRight).asWidget() + * .left(36).right(0).height(18)); + * } + */ public void writeInitialSyncData(FriendlyByteBuf packetBuffer) { packetBuffer.writeItem(this.getFilterStack()); diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java index 9024aac6e2..bdb9982393 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MatchResult.java @@ -2,6 +2,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraftforge.fluids.FluidStack; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java index 39fad01bd0..5ae7f2fdc3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/MergabilityInfo.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.cover.filter; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 00f57dbad1..dbb8ecd430 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -23,13 +23,13 @@ import com.gregtechceu.gtceu.api.registry.registrate.CompassSection; import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; import com.gregtechceu.gtceu.common.block.*; +import com.gregtechceu.gtceu.common.block.explosive.IndustrialTNTBlock; +import com.gregtechceu.gtceu.common.block.explosive.PowderbarrelBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserStructure; import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalPipeBlock; -import com.gregtechceu.gtceu.common.block.explosive.IndustrialTNTBlock; -import com.gregtechceu.gtceu.common.block.explosive.PowderbarrelBlock; import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; @@ -325,7 +325,7 @@ private static void registerCableBlock(Material material, CableStructure insulat .addLayer(() -> RenderType::cutoutMipped) .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) - //.color(() -> ::tintColor) + // .color(() -> ::tintColor) .onRegister(compassNodeExist(GTCompassSections.MATERIALS, "wire_and_cable")) .build() .register(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java index 4e51eafa8f..2a0475c6c6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java @@ -12,8 +12,8 @@ import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.machine.multiblock.part.MultiblockPartMachine; import com.gregtechceu.gtceu.api.recipe.GTRecipe; - import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; @@ -50,7 +50,8 @@ public boolean accessData(@NotNull DataQueryObject queryObject) { if (!getControllers().isEmpty()) { if (isTransmitter()) { IMultiController controller = getControllers().get(0); - if (!controller.isFormed() || (controller instanceof IWorkable workable && !workable.isActive())) return false; + if (!controller.isFormed() || (controller instanceof IWorkable workable && !workable.isActive())) + return false; List dataAccesses = new ArrayList<>(); List reception = new ArrayList<>(); @@ -97,7 +98,7 @@ public boolean canShared() { public GTRecipe modifyRecipe(GTRecipe recipe) { // creative hatches do not need to check, they always have the recipe // TODO creative data access hatch - //if (this.isCreative()) return recipe; + // if (this.isCreative()) return recipe; RecipeDataQuery query = new RecipeDataQuery(recipe); // hatches need to have the recipe available diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index 44bdae9210..0432ced2a1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -12,17 +12,19 @@ import com.gregtechceu.gtceu.common.pipelike.net.energy.SuperconductorLogic; import com.gregtechceu.gtceu.common.pipelike.net.energy.WorldEnergyNet; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; + import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; + import java.util.Map; public class CableBlock extends PipeMaterialBlock implements IBurnable { @@ -72,7 +74,9 @@ public void partialBurn(BlockState state, Level world, BlockPos pos) { @Override public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) { super.entityInside(state, level, pos, entity); - if (!(level instanceof ServerLevel serverLevel) || getStructure().isInsulated() || !(entity instanceof LivingEntity living)) return; + if (!(level instanceof ServerLevel serverLevel) || getStructure().isInsulated() || + !(entity instanceof LivingEntity living)) + return; PipeBlockEntity tile = getBlockEntity(level, pos); if (tile != null && tile.getFrameMaterial() == null && tile.getOffsetTimer() % 10 == 0) { WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(pos); @@ -88,9 +92,9 @@ public void entityInside(BlockState state, Level level, BlockPos pos, Entity ent if (cumulativeDamage != 0) { living.hurt(GTDamageTypes.ELECTRIC.source(serverLevel), cumulativeDamage); // TODO advancement - //if (living instanceof ServerPlayer serverPlayer) { - // AdvancementTriggers.ELECTROCUTION_DEATH.trigger(serverPlayer); - //} + // if (living instanceof ServerPlayer serverPlayer) { + // AdvancementTriggers.ELECTROCUTION_DEATH.trigger(serverPlayer); + // } } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index b0c4c88abc..9f252de3b1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -6,6 +6,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java index cb84df4abc..9b19e83b9e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java @@ -4,10 +4,12 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.LaserNetHandler; + import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.state.BlockBehaviour; + import org.jetbrains.annotations.NotNull; public class LaserPipeBlock extends PipeActivableBlock { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java index 25df66cd0f..b11c48e9e7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -5,7 +5,9 @@ import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java index 4d3c8ea171..e2959f7d83 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java index efdfe7ada0..dfd9373870 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java @@ -4,10 +4,12 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.OpticalNetHandler; + import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.state.BlockBehaviour; + import org.jetbrains.annotations.NotNull; public class OpticalPipeBlock extends PipeActivableBlock { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java index 3ffe41a23e..12c3d49b82 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -5,7 +5,9 @@ import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java index 79e4e0ac93..f451940b49 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; + import net.minecraft.world.level.block.state.BlockBehaviour; public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, IFreezable { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java index 507a5399a1..406fd83d9f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -6,6 +6,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModel; + import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java index cc05e66129..6951b6245e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/LaserNetHandler.java @@ -5,13 +5,14 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserStructure; import com.gregtechceu.gtceu.common.pipelike.net.laser.WorldLaserNet; + import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelAccessor; + import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -32,7 +33,8 @@ public final class LaserNetHandler implements IPipeNetNodeHandler { } @Override - public @NotNull Collection getFromNets(ServerLevel world, BlockPos pos, IPipeStructure structure) { + public @NotNull Collection getFromNets(ServerLevel world, BlockPos pos, + IPipeStructure structure) { if (structure instanceof LaserStructure) { WorldPipeNetNode node = WorldLaserNet.getWorldNet(world).getNode(pos); if (node != null) return Collections.singletonList(node); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java index aa8512194f..4ba40c6194 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java @@ -5,12 +5,14 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.net.optical.WorldOpticalNet; + import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; + import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -31,7 +33,8 @@ public final class OpticalNetHandler implements IPipeNetNodeHandler { } @Override - public @NotNull Collection getFromNets(ServerLevel world, BlockPos pos, IPipeStructure structure) { + public @NotNull Collection getFromNets(ServerLevel world, BlockPos pos, + IPipeStructure structure) { if (structure instanceof OpticalStructure) { WorldPipeNetNode node = WorldOpticalNet.getWorldNet(world).getNode(pos); if (node != null) return Collections.singletonList(node); @@ -52,6 +55,5 @@ public void removeFromNets(ServerLevel world, BlockPos pos, IPipeStructure struc public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, @NotNull TooltipFlag flagIn, IPipeStructure structure) { tooltip.add(Component.translatable("block.gtceu.normal_optical_pipe.tooltip")); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java index a6c3d6ddb2..385910cfdc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java @@ -5,9 +5,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeActivableBlockEntity; import com.gregtechceu.gtceu.utils.TaskScheduler; import com.gregtechceu.gtceu.utils.function.Task; + import com.lowdragmc.lowdraglib.Platform; + import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java index dde45bdf2c..65f3639710 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java @@ -18,11 +18,14 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; -import lombok.Setter; + import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java index 4732b2e532..bec8654ea2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java @@ -1,11 +1,13 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; + +import net.minecraft.nbt.ByteTag; +import net.minecraft.network.FriendlyByteBuf; + import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.nbt.ByteTag; -import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.NotNull; import java.util.Collections; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java index 72ab2dbbe9..672cc3cf30 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyGroupData.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; import com.gregtechceu.gtceu.api.graphnet.AbstractGroupData; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java index af2adaedbb..3aeef0f276 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java @@ -15,13 +15,14 @@ import com.gregtechceu.gtceu.api.graphnet.traverse.AbstractTraverseData; import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; import com.gregtechceu.gtceu.utils.GTUtil; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.NotNull; import java.util.function.LongSupplier; -import java.util.function.Supplier; public class EnergyTraverseData extends AbstractTraverseData { @@ -101,7 +102,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl continue; // anti insert-to-our-source logic IEnergyContainer container = capability.getValue() - .getCapability(GTCapability.CAPABILITY_ENERGY_CONTAINER, capability.getKey().getOpposite()).resolve().orElse(null); + .getCapability(GTCapability.CAPABILITY_ENERGY_CONTAINER, capability.getKey().getOpposite()) + .resolve().orElse(null); if (container != null) { availableFlow -= IEnergyTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(pathVoltage, availableFlow, container, diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java index d02bbe09eb..4d9b0637a3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/IEnergyTransferController.java @@ -3,7 +3,9 @@ import com.gregtechceu.gtceu.api.capability.IEnergyContainer; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; + import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java index d38ab8aced..561592916b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractIntLogicData; + import org.jetbrains.annotations.NotNull; public final class SuperconductorLogic extends AbstractIntLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java index e58300b4b0..66e392f416 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; + import org.jetbrains.annotations.NotNull; public final class VoltageLimitLogic extends AbstractLongLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java index 5bf1cbd2a2..4447aa5a36 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; + import org.jetbrains.annotations.NotNull; public final class VoltageLossLogic extends AbstractLongLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java index bbc0675f57..f585a91e5c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java @@ -10,8 +10,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + import net.minecraft.server.level.ServerLevel; import net.minecraftforge.common.capabilities.Capability; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java index 4fc822c5f1..ba6c87defc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/ContainmentFailure.java @@ -8,12 +8,15 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.IWorldPipeNetTile; import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; import com.gregtechceu.gtceu.utils.EntityDamageUtil; + import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; + import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.resources.ResourceLocation; -import com.lowdragmc.lowdraglib.side.fluid.FluidStack; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.NotNull; import java.util.EnumMap; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java index c57a53f8e4..f971dc56cc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java @@ -15,16 +15,19 @@ import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; -import lombok.Getter; -import lombok.Setter; + import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Getter; +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -36,7 +39,8 @@ public class FluidCapabilityObject implements IPipeCapabilityObject, IFluidTrans IFluidTraverseGuideProvider { private final WorldPipeNet net; - @Getter @Setter + @Getter + @Setter private @Nullable PipeBlockEntity tile; @Getter private final int tanks; @@ -99,7 +103,8 @@ public int fill(FluidStack resource, boolean simulate, Direction side) { if (this.transferring) return 0; this.transferring = true; - var guide = getGuide(FluidTraverseData::new, new FluidTestObject(resource), resource.getAmount(), simulate, side); + var guide = getGuide(FluidTraverseData::new, new FluidTestObject(resource), resource.getAmount(), simulate, + side); if (guide == null) return 0; int accepted = (int) TraverseHelpers.traverseFlood(guide.getData(), guide.getPaths(), guide.getFlow()); guide.reportConsumedFlow(accepted); @@ -166,9 +171,7 @@ public Object createSnapshot() { } @Override - public void restoreFromSnapshot(Object snapshot) { - - } + public void restoreFromSnapshot(Object snapshot) {} @NotNull @Override @@ -183,9 +186,7 @@ public FluidStack getFluidInTank(int tank) { } @Override - public void setFluidInTank(int tank, @NotNull FluidStack fluidStack) { - - } + public void setFluidInTank(int tank, @NotNull FluidStack fluidStack) {} @Override public long getTankCapacity(int tank) { @@ -265,9 +266,7 @@ public Object createSnapshot() { // Unused. @Override - public void restoreFromSnapshot(Object snapshot) { - - } + public void restoreFromSnapshot(Object snapshot) {} @NotNull @Override @@ -276,9 +275,7 @@ public FluidStack getFluidInTank(int tank) { } @Override - public void setFluidInTank(int tank, @NotNull FluidStack fluidStack) { - - } + public void setFluidInTank(int tank, @NotNull FluidStack fluidStack) {} @Override public long getTankCapacity(int tank) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java index 851b04a0d0..00475ad9cf 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java @@ -4,13 +4,15 @@ import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; import com.gregtechceu.gtceu.utils.GTUtil; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java index 4ed3e192f5..b331b8b4d3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java @@ -6,11 +6,13 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.IEqualizableTraverseData; + import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraftforge.fluids.capability.IFluidHandler; + import org.jetbrains.annotations.NotNull; public class FluidEQTraverseData extends FluidTraverseData diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java index bb035fce34..0c28cdb2e9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidRRTraverseData.java @@ -7,17 +7,20 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinTraverseData; + import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.fluids.capability.IFluidHandler; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import org.jetbrains.annotations.NotNull; public class FluidRRTraverseData extends FluidTraverseData implements - IRoundRobinTraverseData, WorldPipeNetNode, FlowWorldPipeNetPath> { + IRoundRobinTraverseData, WorldPipeNetNode, FlowWorldPipeNetPath> { private final Object2ObjectLinkedOpenHashMap> cache; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java index 460a100f73..9e6e3aa068 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java @@ -19,13 +19,16 @@ import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; import com.gregtechceu.gtceu.utils.EntityDamageUtil; + import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleTypes; -import com.lowdragmc.lowdraglib.side.fluid.FluidStack; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java index f835be0693..d2bcf13ce3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java @@ -3,8 +3,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; -import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; + import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -31,7 +33,7 @@ public interface IFluidTransferController { @Override public long insertToHandler(@NotNull FluidTestObject testObject, int amount, - @NotNull IFluidTransfer destHandler, boolean doFill) { + @NotNull IFluidTransfer destHandler, boolean doFill) { return 0; } @@ -46,7 +48,7 @@ public long insertToHandler(@NotNull FluidTestObject testObject, int amount, * @return the amount filled. */ default long insertToHandler(@NotNull FluidTestObject testObject, int amount, @NotNull IFluidTransfer destHandler, - boolean doFill) { + boolean doFill) { return destHandler.fill(testObject.recombine(amount), doFill); } @@ -54,7 +56,8 @@ default long insertToHandler(@NotNull FluidTestObject testObject, int amount, @N * @return the fluidstack drained. */ @Nullable - default FluidStack extractFromHandler(@Nullable FluidTestObject testObject, int amount, IFluidTransfer sourceHandler, + default FluidStack extractFromHandler(@Nullable FluidTestObject testObject, int amount, + IFluidTransfer sourceHandler, boolean doDrain) { if (testObject == null) return sourceHandler.drain(amount, doDrain); else { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java index a5b5756853..1725083529 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTraverseGuideProvider.java @@ -7,10 +7,11 @@ import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseGuideProvider; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseDataProvider; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; + import org.jetbrains.annotations.Nullable; public interface IFluidTraverseGuideProvider extends - ITraverseGuideProvider { + ITraverseGuideProvider { @Nullable @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java index 16a692a16f..e1423f6391 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java @@ -17,9 +17,11 @@ import com.gregtechceu.gtceu.common.cover.PumpCover; import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; import com.gregtechceu.gtceu.common.pipelike.net.item.WorldItemNet; + import net.minecraft.server.level.ServerLevel; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java index 17181b32b7..2b9296aad0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTransferController.java @@ -3,9 +3,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; + import com.lowdragmc.lowdraglib.side.item.IItemTransfer; + import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandler; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java index c9a437a4fa..d8cb3bd5a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/IItemTraverseGuideProvider.java @@ -7,10 +7,11 @@ import com.gregtechceu.gtceu.api.graphnet.traverse.ITraverseGuideProvider; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseDataProvider; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; + import org.jetbrains.annotations.Nullable; public interface IItemTraverseGuideProvider extends - ITraverseGuideProvider { + ITraverseGuideProvider { @Nullable @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java index f23a1a37a7..fef343be1b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemCapabilityObject.java @@ -14,16 +14,19 @@ import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseGuide; import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; -import lombok.Getter; -import lombok.Setter; + import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Getter; +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -84,7 +87,8 @@ public LazyOptional getCapabilityForSide(Capability capability, @Nulla return null; } - public @NotNull ItemStack insertItem(@NotNull ItemStack stack, boolean simulate, boolean notifyChanges, Direction side) { + public @NotNull ItemStack insertItem(@NotNull ItemStack stack, boolean simulate, boolean notifyChanges, + Direction side) { if (this.transferring) return stack; this.transferring = true; @@ -178,9 +182,7 @@ public Object createSnapshot() { // Unused @Override - public void restoreFromSnapshot(Object snapshot) { - - } + public void restoreFromSnapshot(Object snapshot) {} protected class Wrapper implements IItemTransfer, IItemTraverseGuideProvider { @@ -244,8 +246,6 @@ public Object createSnapshot() { // Unused @Override - public void restoreFromSnapshot(Object snapshot) { - - } + public void restoreFromSnapshot(Object snapshot) {} } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java index 64d0dc9527..c3a68e3c03 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java @@ -6,12 +6,15 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.IEqualizableTraverseData; + import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.IItemHandler; + import org.jetbrains.annotations.NotNull; public class ItemEQTraverseData extends ItemTraverseData @@ -34,7 +37,8 @@ protected void compute(@NotNull WorldPipeNetNode destination) { continue; // anti insert-to-our-source logic IItemHandler cap = capability.getValue() - .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve() + .orElse(null); if (cap != null) { IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(cap); if (destCount == 0) maxMinFlow = Integer.MAX_VALUE; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java index 13fc0ec9ab..5ee97fa781 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemRRTraverseData.java @@ -7,17 +7,20 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.IRoundRobinTraverseData; + import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.IItemHandler; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import org.jetbrains.annotations.NotNull; public class ItemRRTraverseData extends ItemTraverseData implements - IRoundRobinTraverseData, WorldPipeNetNode, FlowWorldPipeNetPath> { + IRoundRobinTraverseData, WorldPipeNetNode, FlowWorldPipeNetPath> { private final Object2ObjectLinkedOpenHashMap> cache; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java index 91c5f33ef3..0a8b3251e8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java @@ -7,12 +7,15 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; import com.gregtechceu.gtceu.api.graphnet.traverse.AbstractTraverseData; import com.gregtechceu.gtceu.api.graphnet.traverse.util.ReversibleLossOperator; + import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.side.item.forge.ItemTransferHelperImpl; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.IItemHandler; + import org.jetbrains.annotations.NotNull; public class ItemTraverseData extends AbstractTraverseData { @@ -51,7 +54,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl continue; // anti insert-to-our-source logic IItemHandler cap = capability.getValue() - .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve() + .orElse(null); if (cap != null) { IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(cap); availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java index af188c5d8d..5bf88ef33a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java @@ -15,12 +15,13 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.FilterPredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.gregtechceu.gtceu.common.cover.ConveyorCover; -import com.gregtechceu.gtceu.common.cover.data.ItemFilterMode; import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; import com.gregtechceu.gtceu.common.pipelike.net.fluid.WorldFluidNet; + import net.minecraft.server.level.ServerLevel; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java index eb142ff3f0..ffeeed3600 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/ILaserTransferController.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.capability.ILaserRelay; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControl; import com.gregtechceu.gtceu.api.graphnet.pipenet.transfer.TransferControlProvider; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java index f3153683f9..1ad12f7ae7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/LaserCapabilityObject.java @@ -9,11 +9,14 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.gregtechceu.gtceu.common.pipelike.net.SlowActiveWalker; + import com.lowdragmc.lowdraglib.Platform; -import lombok.Setter; + import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -52,10 +55,13 @@ public long receiveLaser(long laserVoltage, long laserAmperage) { WorldPipeNetNode destination = path.getTargetNode(); for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { ILaserRelay laser = capability.getValue() - .getCapability(GTCapability.CAPABILITY_LASER, capability.getKey().getOpposite()).resolve().orElse(null); + .getCapability(GTCapability.CAPABILITY_LASER, capability.getKey().getOpposite()).resolve() + .orElse(null); if (laser != null) { - long transmitted = ILaserTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() - .getCoverAtSide(capability.getKey())).insertToHandler(laserVoltage, laserAmperage, laser); + long transmitted = ILaserTransferController.CONTROL + .get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())) + .insertToHandler(laserVoltage, laserAmperage, laser); if (transmitted > 0) { SlowActiveWalker.dispatch(tile.getLevel(), path, 1, 2, 2); available -= transmitted; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java index 5fa7623337..b08e473c57 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java @@ -8,8 +8,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + import net.minecraft.server.level.ServerLevel; import net.minecraftforge.common.capabilities.Capability; + import org.jetbrains.annotations.Nullable; import java.util.Iterator; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java index 507812f2c3..5fa9ebf7e1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java @@ -13,11 +13,14 @@ import com.gregtechceu.gtceu.common.pipelike.block.optical.IOpticalTransferController; import com.gregtechceu.gtceu.common.pipelike.net.SlowActiveWalker; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.Platform; -import lombok.Setter; + import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -53,7 +56,8 @@ public boolean accessData(@NotNull DataQueryObject queryObject) { for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { IDataAccess access = capability.getValue() .getCapability(GTCapability.CAPABILITY_DATA_ACCESS, - capability.getKey().getOpposite()).resolve().orElse(null); + capability.getKey().getOpposite()) + .resolve().orElse(null); if (access != null) { queryObject.setShouldTriggerWalker(false); boolean cancelled = IOpticalTransferController.CONTROL diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java index b1fe7c0e83..f0f8abe8f7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java @@ -8,8 +8,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + import net.minecraft.server.level.ServerLevel; import net.minecraftforge.common.capabilities.Capability; + import org.jetbrains.annotations.Nullable; import java.util.Iterator; diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java index 2380df0c14..ca8528c862 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java @@ -1,12 +1,13 @@ package com.gregtechceu.gtceu.core.mixins; import com.gregtechceu.gtceu.core.MixinHelpers; -import com.lowdragmc.lowdraglib.client.renderer.IRenderer; + import net.minecraft.client.renderer.texture.atlas.SpriteResourceLoader; import net.minecraft.client.renderer.texture.atlas.SpriteSource; import net.minecraft.client.renderer.texture.atlas.sources.SingleFile; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; + import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -22,10 +23,14 @@ public class SpriteResourceLoaderMixin { // try to load all renderer textures - @Inject(method = "load", at = @At(value = "RETURN"), + @Inject(method = "load", + at = @At(value = "RETURN"), locals = LocalCapture.CAPTURE_FAILHARD) - private static void injectLoad(ResourceManager resourceManager, ResourceLocation location, CallbackInfoReturnable cir, ResourceLocation resourceLocation, List list) { - ResourceLocation atlas = new ResourceLocation(location.getNamespace(), "textures/atlas/%s.png".formatted(location.getPath())); + private static void injectLoad(ResourceManager resourceManager, ResourceLocation location, + CallbackInfoReturnable cir, ResourceLocation resourceLocation, + List list) { + ResourceLocation atlas = new ResourceLocation(location.getNamespace(), + "textures/atlas/%s.png".formatted(location.getPath())); Set sprites = new HashSet<>(); MixinHelpers.loadBakedModelTextures(atlas, sprites::add); for (ResourceLocation sprite : sprites) { diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java index 487b45591f..1867173ff7 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java @@ -57,11 +57,11 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso var cableData = new CompoundTag(); // TODO fix /* - cableData.putLong("maxVoltage", cable.getMaxVoltage()); - cableData.putLong("currentVoltage", cable.getCurrentMaxVoltage()); - cableData.putDouble("maxAmperage", cable.getMaxAmperage()); - cableData.putDouble("currentAmperage", cable.getAverageAmperage()); - */ + * cableData.putLong("maxVoltage", cable.getMaxVoltage()); + * cableData.putLong("currentVoltage", cable.getCurrentMaxVoltage()); + * cableData.putDouble("maxAmperage", cable.getMaxAmperage()); + * cableData.putDouble("currentAmperage", cable.getAverageAmperage()); + */ data.put("cableData", cableData); } } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java index b5aacd2a13..373425ec23 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java @@ -21,28 +21,28 @@ public void addProbeInfo(ProbeMode probeMode, IProbeInfo iProbeInfo, Player play BlockState blockState, IProbeHitData iProbeHitData) { // TODO fix /* - if (blockState.getBlock() instanceof CableBlock cableBlock) { - CableBlockEntity cable = (CableBlockEntity) cableBlock.getPipeTile(level, iProbeHitData.getPos()); - if (cable != null) { - long voltage = cable.getCurrentMaxVoltage(); - double amperage = cable.getAverageAmperage(); - IProbeInfo horizontalPane = iProbeInfo - .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); - horizontalPane.text(Component.translatable("gtceu.top.cable_voltage")); - if (voltage != 0) { - horizontalPane.text(GTValues.VNF[GTUtil.getTierByVoltage(voltage)]).text(" / "); - } - horizontalPane.text(GTValues.VNF[GTUtil.getTierByVoltage(cable.getMaxVoltage())]); - - horizontalPane = iProbeInfo - .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); - horizontalPane.text(Component.translatable("gtceu.top.cable_amperage")); - if (amperage != 0) { - horizontalPane.text(DECIMAL_FORMAT_1F.format(cable.getAverageAmperage()) + "A / "); - } - horizontalPane.text(DECIMAL_FORMAT_1F.format(cable.getMaxAmperage()) + "A"); - } - } - */ + * if (blockState.getBlock() instanceof CableBlock cableBlock) { + * CableBlockEntity cable = (CableBlockEntity) cableBlock.getPipeTile(level, iProbeHitData.getPos()); + * if (cable != null) { + * long voltage = cable.getCurrentMaxVoltage(); + * double amperage = cable.getAverageAmperage(); + * IProbeInfo horizontalPane = iProbeInfo + * .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); + * horizontalPane.text(Component.translatable("gtceu.top.cable_voltage")); + * if (voltage != 0) { + * horizontalPane.text(GTValues.VNF[GTUtil.getTierByVoltage(voltage)]).text(" / "); + * } + * horizontalPane.text(GTValues.VNF[GTUtil.getTierByVoltage(cable.getMaxVoltage())]); + * + * horizontalPane = iProbeInfo + * .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); + * horizontalPane.text(Component.translatable("gtceu.top.cable_amperage")); + * if (amperage != 0) { + * horizontalPane.text(DECIMAL_FORMAT_1F.format(cable.getAverageAmperage()) + "A / "); + * } + * horizontalPane.text(DECIMAL_FORMAT_1F.format(cable.getMaxAmperage()) + "A"); + * } + * } + */ } } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java b/src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java index 193a93ec3d..118f82d0d3 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/DimensionFacingPos.java @@ -1,11 +1,12 @@ package com.gregtechceu.gtceu.utils; -import lombok.Getter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.Level; +import lombok.Getter; + import java.util.Objects; public class DimensionFacingPos { diff --git a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java index 6abe28e807..1860d05120 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java @@ -10,12 +10,13 @@ import com.lowdragmc.lowdraglib.syncdata.managed.MultiManagedStorage; -import com.google.common.collect.Table; -import it.unimi.dsi.fastutil.ints.Int2LongFunction; -import lombok.Getter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; + +import com.google.common.collect.Table; +import it.unimi.dsi.fastutil.ints.Int2LongFunction; +import lombok.Getter; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -51,9 +52,7 @@ public MultiManagedStorage getRootStorage() { } @Override - public void onNeighborChanged(@NotNull Direction facing) { - - } + public void onNeighborChanged(@NotNull Direction facing) {} @Override public Level getLevel() { @@ -66,7 +65,5 @@ public BlockPos getBlockPos() { } @Override - public void markAsDirty() { - - } + public void markAsDirty() {} } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java b/src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java index 589848c5dc..ee32a53310 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/TaskScheduler.java @@ -2,11 +2,13 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.utils.function.Task; + import net.minecraft.world.level.Level; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.level.LevelEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; + import org.jetbrains.annotations.Nullable; import java.lang.ref.WeakReference; From d9a2495ed090557ce67e786d8a0917c0d9a98f3e Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Fri, 23 Aug 2024 09:15:01 +0300 Subject: [PATCH 08/70] duct pipes --- .../gtceu/api/block/MaterialBlock.java | 1 - .../api/blockentity/PipeBlockEntity.java | 438 ---------------- .../graphnet/pipenet/WorldPipeNetNode.java | 2 +- .../physical/block/MaterialPipeBlockItem.java | 2 +- .../pipenet/physical/block/PipeBlock.java | 3 +- .../physical/tile/PipeBlockEntity.java | 4 +- .../gtceu/api/item/DuctPipeBlockItem.java | 30 -- .../gtceu/api/item/MetaMachineItem.java | 1 - .../gtceu/api/pattern/Predicates.java | 1 - .../gtceu/api/pipenet/IAttachData.java | 23 - .../gtceu/api/pipenet/IMaterialPipeType.java | 14 - .../gtceu/api/pipenet/IPipeNode.java | 178 ------- .../gtceu/api/pipenet/IPipeType.java | 26 - .../gtceu/api/pipenet/IRoutePath.java | 36 -- .../gtceu/api/pipenet/ITickablePipeNet.java | 11 - .../gtceu/api/pipenet/LevelPipeNet.java | 150 ------ .../gregtechceu/gtceu/api/pipenet/Node.java | 40 -- .../gtceu/api/pipenet/PipeNet.java | 495 ------------------ .../gtceu/api/pipenet/PipeNetWalker.java | 250 --------- .../api/pipenet/TickableLevelPipeNet.java | 143 ----- .../gtceu/client/model/PipeModel.java | 356 ------------- .../renderer/BlockHighLightRenderer.java | 2 - .../renderer/block/PipeBlockRenderer.java | 2 - .../client/renderer/pipe/DuctPipeModel.java | 65 +++ .../gtceu/common/block/DuctPipeBlock.java | 110 ---- .../blockentity/DuctPipeBlockEntity.java | 1 - .../gtceu/common/data/GTBlockEntities.java | 32 +- .../gtceu/common/data/GTBlocks.java | 25 +- .../common/item/ColorSprayBehaviour.java | 1 - .../common/item/PortableScannerBehavior.java | 1 - .../electric/WorldAcceleratorMachine.java | 1 - .../pipelike/block/duct/DuctPipeBlock.java | 39 ++ .../pipelike/block/duct/DuctStructure.java | 63 +++ .../block/optical/OpticalPipeBlock.java | 6 +- .../common/pipelike/duct/DuctNetHandler.java | 181 ------- .../common/pipelike/duct/DuctNetWalker.java | 95 ---- .../common/pipelike/duct/DuctPipeNet.java | 61 --- .../pipelike/duct/DuctPipeProperties.java | 47 -- .../common/pipelike/duct/DuctPipeType.java | 63 --- .../common/pipelike/duct/DuctRoutePath.java | 51 -- .../pipelike/duct/LevelDuctPipeNet.java | 29 - .../pipelike/handlers/DuctNetHandler.java | 59 +++ .../pipelike/handlers/OpticalNetHandler.java | 2 +- .../net/duct/DuctCapabilityObject.java | 177 +++++++ .../pipelike/net/duct/WorldDuctNet.java | 55 ++ .../recipe/generated/PipeRecipeHandler.java | 9 +- .../jade/provider/StainedColorProvider.java | 1 - .../top/provider/StainedColorProvider.java | 1 - 48 files changed, 490 insertions(+), 2893 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/item/DuctPipeBlockItem.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/IAttachData.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/IMaterialPipeType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/IRoutePath.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/ITickablePipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/LevelPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/Node.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNetWalker.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/pipenet/TickableLevelPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/model/PipeModel.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetHandler.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetWalker.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeNet.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeProperties.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctRoutePath.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/LevelDuctPipeNet.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java index a27c8a3688..83aed64836 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.api.block; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.item.tool.GTToolType; diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java deleted file mode 100644 index 23c4f238d3..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/PipeBlockEntity.java +++ /dev/null @@ -1,438 +0,0 @@ -package com.gregtechceu.gtceu.api.blockentity; - -import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.block.BlockProperties; -import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.api.capability.IToolable; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.api.item.tool.GTToolType; -import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; -import com.gregtechceu.gtceu.api.machine.TickableSubscription; -import com.gregtechceu.gtceu.api.pipenet.*; -import com.gregtechceu.gtceu.common.data.GTBlocks; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; -import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; -import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; -import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; -import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; -import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; -import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; -import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; -import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.server.TickTask; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -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.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; - -import com.mojang.datafixers.util.Pair; -import lombok.Getter; -import lombok.Setter; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * @author KilaBash - * @date 2023/2/28 - * @implNote PipeBlockEntity - */ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public abstract class PipeBlockEntity & IPipeType, NodeDataType> - extends BlockEntity implements IPipeNode, IEnhancedManaged, - IAsyncAutoSyncBlockEntity, IAutoPersistBlockEntity, IToolGridHighLight, IToolable { - - public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(PipeBlockEntity.class); - @Getter - private final FieldManagedStorage syncStorage = new FieldManagedStorage(this); - private final long offset = GTValues.RNG.nextInt(20); - - @Getter - @Setter - @DescSynced - @Persisted - @RequireRerender - protected int connections = Node.ALL_CLOSED; - @Setter - @DescSynced - @Persisted - @RequireRerender - private int blockedConnections = Node.ALL_CLOSED; - private NodeDataType cachedNodeData; - - @Persisted - @DescSynced - @RequireRerender - @Getter - @Setter - private int paintingColor = -1; - - @RequireRerender - @DescSynced - @Persisted - @Getter - @Setter - @Nullable - private Material frameMaterial = null; - private final List serverTicks; - private final List waitingToAdd; - - public PipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - this.serverTicks = new ArrayList<>(); - this.waitingToAdd = new ArrayList<>(); - } - - ////////////////////////////////////// - // ***** Initialization ******// - ////////////////////////////////////// - public void scheduleRenderUpdate() { - IPipeNode.super.scheduleRenderUpdate(); - } - - @Override - public IManagedStorage getRootStorage() { - return syncStorage; - } - - @Override - public ManagedFieldHolder getFieldHolder() { - return MANAGED_FIELD_HOLDER; - } - - @Override - public void onChanged() { - var level = getLevel(); - if (level != null && !level.isClientSide && level.getServer() != null) { - level.getServer().execute(this::setChanged); - } - } - - @Override - public long getOffsetTimer() { - return level == null ? offset : (level.getGameTime() + offset); - } - - @Override - public void setRemoved() { - super.setRemoved(); - } - - @Override - public void clearRemoved() { - super.clearRemoved(); - } - - @Override - public int getNumConnections() { - int count = 0; - int connections = getConnections(); - while (connections > 0) { - count++; - connections = connections & (connections - 1); - } - return count; - } - - @Override - public int getBlockedConnections() { - return canHaveBlockedFaces() ? blockedConnections : 0; - } - - @Override - public NodeDataType getNodeData() { - if (cachedNodeData == null) { - this.cachedNodeData = getPipeBlock().createProperties(this); - } - return cachedNodeData; - } - - @Nullable - public TickableSubscription subscribeServerTick(Runnable runnable) { - if (!isRemote()) { - var subscription = new TickableSubscription(runnable); - waitingToAdd.add(subscription); - var blockState = getBlockState(); - if (!blockState.getValue(BlockProperties.SERVER_TICK)) { - if (getLevel() instanceof ServerLevel serverLevel) { - blockState = blockState.setValue(BlockProperties.SERVER_TICK, true); - setBlockState(blockState); - serverLevel.getServer().tell(new TickTask(0, () -> serverLevel.setBlockAndUpdate(getBlockPos(), - getBlockState().setValue(BlockProperties.SERVER_TICK, true)))); - } - } - return subscription; - } - return null; - } - - public void unsubscribe(@Nullable TickableSubscription current) { - if (current != null) { - current.unsubscribe(); - } - } - - public final void serverTick() { - if (!waitingToAdd.isEmpty()) { - serverTicks.addAll(waitingToAdd); - waitingToAdd.clear(); - } - var iter = serverTicks.iterator(); - while (iter.hasNext()) { - var tickable = iter.next(); - if (tickable.isStillSubscribed()) { - tickable.run(); - } - if (!tickable.isStillSubscribed()) { - iter.remove(); - } - } - if (serverTicks.isEmpty() && waitingToAdd.isEmpty() && !this.isRemoved()) { - getLevel().setBlockAndUpdate(getBlockPos(), getBlockState().setValue(BlockProperties.SERVER_TICK, false)); - } - } - - ////////////////////////////////////// - // ******* Pipe Status *******// - ////////////////////////////////////// - - @Override - public void setBlocked(Direction side, boolean isBlocked) { - if (level instanceof ServerLevel serverLevel && canHaveBlockedFaces()) { - blockedConnections = withSideConnection(blockedConnections, side, isBlocked); - setChanged(); - LevelPipeNet worldPipeNet = getPipeBlock().getWorldPipeNet(serverLevel); - PipeNet net = worldPipeNet.getNetFromPos(getBlockPos()); - if (net != null) { - net.onPipeConnectionsUpdate(); - } - } - } - - @Override - public int getVisualConnections() { - var visualConnections = connections; - for (var side : GTUtil.DIRECTIONS) { - var cover = getCoverContainer().getCoverAtSide(side); - if (cover != null && cover.canPipePassThrough()) { - visualConnections = visualConnections | (1 << side.ordinal()); - } - } - return visualConnections; - } - - @Override - public void setConnection(Direction side, boolean connected, boolean fromNeighbor) { - // fix desync between two connections. Can happen if a pipe side is blocked, and a new pipe is placed next to - // it. - if (!getLevel().isClientSide) { - if (isConnected(side) == connected) { - return; - } - BlockEntity tile = getNeighbor(side); - // block connections if Pipe Types do not match - if (connected && - tile instanceof IPipeNode pipeTile && - pipeTile.getPipeType().getClass() != this.getPipeType().getClass()) { - return; - } - connections = withSideConnection(connections, side, connected); - - updateNetworkConnection(side, connected); - setChanged(); - - if (!fromNeighbor && tile instanceof IPipeNode pipeTile) { - syncPipeConnections(side, pipeTile); - } - } - } - - private void syncPipeConnections(Direction side, IPipeNode pipe) { - Direction oppositeSide = side.getOpposite(); - boolean neighbourOpen = pipe.isConnected(oppositeSide); - if (isConnected(side) == neighbourOpen) { - return; - } - if (!neighbourOpen || pipe.getCoverContainer().getCoverAtSide(oppositeSide) == null) { - pipe.setConnection(oppositeSide, !neighbourOpen, true); - } - } - - private void updateNetworkConnection(Direction side, boolean connected) { - LevelPipeNet worldPipeNet = getPipeBlock().getWorldPipeNet((ServerLevel) getLevel()); - worldPipeNet.updateBlockedConnections(getPipePos(), side, !connected); - } - - protected int withSideConnection(int blockedConnections, Direction side, boolean connected) { - int index = 1 << side.ordinal(); - if (connected) { - return blockedConnections | index; - } else { - return blockedConnections & ~index; - } - } - - @Override - public void notifyBlockUpdate() { - getLevel().updateNeighborsAt(getBlockPos(), getPipeBlock()); - getPipeBlock().updateActiveNodeStatus(getLevel(), getBlockPos(), this); - } - - @Override - public boolean triggerEvent(int id, int para) { - if (id == 1) { // chunk re render - if (level != null && level.isClientSide) { - scheduleRenderUpdate(); - } - return true; - } - return false; - } - - @Override - public void setChanged() { - if (getLevel() != null) { - getLevel().blockEntityChanged(getBlockPos()); - } - } - - ////////////////////////////////////// - // ******* Interaction *******// - ////////////////////////////////////// - @Override - public boolean shouldRenderGrid(Player player, BlockPos pos, BlockState state, ItemStack held, - Set toolTypes) { - if (toolTypes.contains(getPipeTuneTool())) return true; - for (CoverBehavior cover : coverContainer.getCovers()) { - if (cover.shouldRenderGrid(player, pos, state, held, toolTypes)) return true; - } - return false; - } - - public ResourceTexture getPipeTexture(boolean isBlock) { - return isBlock ? GuiTextures.TOOL_PIPE_CONNECT : GuiTextures.TOOL_PIPE_BLOCK; - } - - @Override - public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, Set toolTypes, - Direction side) { - if (toolTypes.contains(getPipeTuneTool())) { - if (player.isShiftKeyDown() && this.canHaveBlockedFaces()) { - return getPipeTexture(isBlocked(side)); - } else { - return getPipeTexture(isConnected(side)); - } - } - var cover = coverContainer.getCoverAtSide(side); - if (cover != null) { - return cover.sideTips(player, pos, state, toolTypes, side); - } - return null; - } - - @Override - public Pair onToolClick(Set toolTypes, ItemStack itemStack, - UseOnContext context) { - // the side hit from the machine grid - var playerIn = context.getPlayer(); - if (playerIn == null) return Pair.of(null, InteractionResult.PASS); - - var hand = context.getHand(); - var hitResult = new BlockHitResult(context.getClickLocation(), context.getClickedFace(), - context.getClickedPos(), false); - Direction gridSide = ICoverable.determineGridSideHit(hitResult); - CoverBehavior coverBehavior = null; - if (gridSide == null) gridSide = hitResult.getDirection(); - - // Prioritize covers where they apply (Screwdriver, Soft Mallet) - if (toolTypes.contains(GTToolType.SCREWDRIVER)) { - if (coverBehavior != null) { - return Pair.of(GTToolType.SCREWDRIVER, coverBehavior.onScrewdriverClick(playerIn, hand, hitResult)); - } - } else if (toolTypes.contains(GTToolType.SOFT_MALLET)) { - if (coverBehavior != null) { - return Pair.of(GTToolType.SOFT_MALLET, coverBehavior.onSoftMalletClick(playerIn, hand, hitResult)); - } - } else if (toolTypes.contains(getPipeTuneTool())) { - if (playerIn.isShiftKeyDown() && this.canHaveBlockedFaces()) { - boolean isBlocked = this.isBlocked(gridSide); - this.setBlocked(gridSide, !isBlocked); - } else { - boolean isOpen = this.isConnected(gridSide); - this.setConnection(gridSide, !isOpen, false); - } - playerIn.swing(hand); - return Pair.of(getPipeTuneTool(), InteractionResult.CONSUME); - } else if (toolTypes.contains(GTToolType.CROWBAR)) { - if (coverBehavior != null) { - if (!isRemote()) { - getCoverContainer().removeCover(gridSide, playerIn); - playerIn.swing(hand); - return Pair.of(GTToolType.CROWBAR, InteractionResult.CONSUME); - } - } else { - if (frameMaterial != null) { - Block.popResource(getLevel(), getPipePos(), - GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, frameMaterial).asStack()); - frameMaterial = null; - playerIn.swing(hand); - return Pair.of(GTToolType.CROWBAR, InteractionResult.CONSUME); - } - } - } - - return Pair.of(null, InteractionResult.PASS); - } - - public GTToolType getPipeTuneTool() { - return GTToolType.WRENCH; - } - - @Override - public int getDefaultPaintingColor() { - return this.getPipeBlock() instanceof MaterialPipeBlock materialPipeBlock ? - materialPipeBlock.material.getMaterialRGB() : IPipeNode.super.getDefaultPaintingColor(); - } - - public void doExplosion(float explosionPower) { - getLevel().removeBlock(getPipePos(), false); - if (!getLevel().isClientSide) { - ((ServerLevel) getLevel()).sendParticles(ParticleTypes.LARGE_SMOKE, getPipePos().getX() + 0.5, - getPipePos().getY() + 0.5, getPipePos().getZ() + 0.5, - 10, 0.2, 0.2, 0.2, 0.0); - } - getLevel().explode(null, getPipePos().getX() + 0.5, getPipePos().getY() + 0.5, getPipePos().getZ() + 0.5, - explosionPower, Level.ExplosionInteraction.NONE); - } - - public static boolean isFaceBlocked(int blockedConnections, Direction side) { - return (blockedConnections & (1 << side.ordinal())) > 0; - } - - public static boolean isConnected(int connections, Direction side) { - return (connections & (1 << side.ordinal())) > 0; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java index 47e2759854..5c47d38833 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -21,7 +21,7 @@ public final class WorldPipeNetNode extends WorldNetNode { private static final PipeBlockEntity FALLBACK = new PipeBlockEntity(GTBlockEntities.NEW_PIPE.get(), BlockPos.ZERO, - GTBlocks.ITEM_PIPE_BLOCKS.get(TagPrefix.pipeNormalItem, GTMaterials.Aluminium).getDefaultState()); + GTBlocks.MATERIAL_PIPE_BLOCKS.get(TagPrefix.pipeNormal, GTMaterials.Aluminium).getDefaultState()); @Nullable MultiNodeHelper overlapHelper; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index 2f26cc78a1..f863606663 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -10,7 +10,7 @@ public class MaterialPipeBlockItem extends PipeBlockItem { - public MaterialPipeBlockItem(Item.Properties properties, PipeMaterialBlock block) { + public MaterialPipeBlockItem(PipeMaterialBlock block, Item.Properties properties) { super(block, properties); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index bba2531d58..8c02c8e15e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -14,7 +14,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCoverHolder; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.item.CoverPlaceBehavior; import com.gregtechceu.gtceu.config.ConfigHolder; @@ -516,7 +515,7 @@ public BlockEntityTicker getTicker(Level level, Block BlockEntityType blockEntityType) { if (!level.isClientSide && state.getValue(BlockProperties.SERVER_TICK)) { return (pLevel, pPos, pState, pTile) -> { - if (pTile instanceof IPipeNode pipeNode) { + if (pTile instanceof PipeBlockEntity pipeNode) { pipeNode.serverTick(); } }; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 089478c5e1..431833d3a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -212,8 +212,8 @@ public void setDisconnected(Direction facing) { updateActiveStatus(facing, false); } - public boolean isConnected(Direction facing) { - return (this.connectionMask & 1 << facing.ordinal()) > 0; + public boolean isConnected(Direction side) { + return (this.connectionMask & 1 << side.ordinal()) > 0; } public boolean isConnectedCoverAdjusted(Direction facing) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/DuctPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/DuctPipeBlockItem.java deleted file mode 100644 index 5563d6a409..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/item/DuctPipeBlockItem.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gregtechceu.gtceu.api.item; - -import com.gregtechceu.gtceu.common.block.DuctPipeBlock; - -import com.lowdragmc.lowdraglib.client.renderer.IItemRendererProvider; -import com.lowdragmc.lowdraglib.client.renderer.IRenderer; - -import net.minecraft.world.item.ItemStack; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class DuctPipeBlockItem extends PipeBlockItem implements IItemRendererProvider { - - public DuctPipeBlockItem(DuctPipeBlock block, Properties properties) { - super(block, properties); - } - - @Override - @NotNull - public DuctPipeBlock getBlock() { - return (DuctPipeBlock) super.getBlock(); - } - - @Nullable - @Override - public IRenderer getRenderer(ItemStack stack) { - return getBlock().getRenderer(getBlock().defaultBlockState()); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java index db78d1ce56..c2d4ad8dec 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.block.IMachineBlock; import com.gregtechceu.gtceu.api.machine.MachineDefinition; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; import com.lowdragmc.lowdraglib.client.renderer.IItemRendererProvider; import com.lowdragmc.lowdraglib.client.renderer.IRenderer; diff --git a/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java b/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java index cc3e8f3f52..05734bc807 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java @@ -13,7 +13,6 @@ import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.pattern.error.PatternStringError; import com.gregtechceu.gtceu.api.pattern.predicates.*; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; import com.gregtechceu.gtceu.api.recipe.GTRecipeType; import com.gregtechceu.gtceu.common.block.BatteryBlock; import com.gregtechceu.gtceu.common.block.CoilBlock; diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IAttachData.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/IAttachData.java deleted file mode 100644 index 59ca6377ae..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IAttachData.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import net.minecraft.core.Direction; - -/** - * @author KilaBash - * @date 2023/3/1 - * @implNote IAttachData - */ -public interface IAttachData { - - /** - * is the node can attach to the side. - */ - boolean canAttachTo(Direction side); - - /** - * set it attach to a side. - * - * @return whether the status is changed. - */ - boolean setAttached(Direction side, boolean attach); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IMaterialPipeType.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/IMaterialPipeType.java deleted file mode 100644 index c1a4ab1747..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IMaterialPipeType.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; - -public interface IMaterialPipeType extends IPipeType { - - /** - * Determines ore prefix used for this pipe type, which gives pipe ore dictionary key - * when combined with pipe's material - * - * @return ore prefix used for this pipe type - */ - TagPrefix getTagPrefix(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java deleted file mode 100644 index f83e058fb5..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeNode.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import com.gregtechceu.gtceu.api.blockentity.IPaintable; -import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; - -import com.lowdragmc.lowdraglib.LDLib; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; - -import org.jetbrains.annotations.Nullable; - -public interface IPipeNode & IPipeType, NodeDataType> - extends ITickSubscription, IPaintable { - - long getOffsetTimer(); - - /** - * Get Cover Container. - */ - ICoverable getCoverContainer(); - - /** - * If tube is set to block connection from the specific side - * - * @param side face - */ - default boolean isBlocked(Direction side) { - return PipeBlockEntity.isFaceBlocked(getBlockedConnections(), side); - } - - /** - * Unsafe!!! to set internal connections. - * In general, you shouldn't call it yourself. - */ - void setConnections(int connections); - - int getConnections(); - - int getNumConnections(); - - /** - * set to block connection from the specific side - * - * @param side face - * @param isBlocked is blocked - */ - void setBlocked(Direction side, boolean isBlocked); - - /** - * Whether pipe can attach to specific side. - * e.g. check if there is an energyContainer nearby. - */ - boolean canAttachTo(Direction side); - - /** - * get connections for rendering and collision. - */ - int getVisualConnections(); - - /** - * If node is connected to the specific side - * - * @param side face - */ - default boolean isConnected(Direction side) { - return PipeBlockEntity.isConnected(getConnections(), side); - } - - void setConnection(Direction side, boolean connected, boolean fromNeighbor); - - // if a face is blocked it will still render as connected, but it won't be able to receive stuff from that direction - default boolean canHaveBlockedFaces() { - return true; - } - - int getBlockedConnections(); - - default BlockEntity self() { - return (BlockEntity) this; - } - - default Level getPipeLevel() { - return self().getLevel(); - } - - default BlockPos getPipePos() { - return self().getBlockPos(); - } - - default void markAsDirty() { - self().setChanged(); - } - - default boolean isInValid() { - return self().isRemoved(); - } - - default boolean isRemote() { - var level = getPipeLevel(); - if (level == null) { - return LDLib.isRemote(); - } - return level.isClientSide; - } - - @SuppressWarnings("unchecked") - default PipeBlock getPipeBlock() { - return (PipeBlock) self().getBlockState().getBlock(); - } - - @Nullable - default PipeNet getPipeNet() { - if (getPipeLevel() instanceof ServerLevel serverLevel) { - return getPipeBlock().getWorldPipeNet(serverLevel).getNetFromPos(getPipePos()); - } - return null; - } - - default PipeType getPipeType() { - return getPipeBlock().pipeType; - } - - @Nullable - default NodeDataType getNodeData() { - var net = getPipeNet(); - if (net != null) { - return net.getNodeAt(getPipePos()).data; - } - return null; - } - - void notifyBlockUpdate(); - - default void scheduleRenderUpdate() { - var pos = getPipePos(); - var level = getPipeLevel(); - if (level != null) { - var state = level.getBlockState(pos); - if (level.isClientSide) { - level.sendBlockUpdated(pos, state, state, Block.UPDATE_IMMEDIATE); - } else { - level.blockEvent(pos, state.getBlock(), 1, 0); - } - } - } - - default void serverTick() {} - - default void scheduleNeighborShapeUpdate() { - Level level = getPipeLevel(); - BlockPos pos = getPipePos(); - - if (level == null || pos == null) - return; - - level.getBlockState(pos).updateNeighbourShapes(level, pos, Block.UPDATE_ALL); - } - - default BlockEntity getNeighbor(Direction direction) { - return getPipeLevel().getBlockEntity(getPipePos().relative(direction)); - } - - @Override - default int getDefaultPaintingColor() { - return 0xFFFFFF; - } - - @Nullable - Material getFrameMaterial(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeType.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeType.java deleted file mode 100644 index 1ae39649c1..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IPipeType.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import net.minecraft.resources.ResourceLocation; - -public interface IPipeType { - - /** - * the thickness of the pipe. - */ - float getThickness(); - - /** - * modify the node data by the pipe type. - */ - NodeDataType modifyProperties(NodeDataType baseProperties); - - /** - * can the pipe be painted as other color. - */ - boolean isPaintable(); - - /** - * indicate a unique type id. - */ - ResourceLocation type(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IRoutePath.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/IRoutePath.java deleted file mode 100644 index 030c5c456c..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/IRoutePath.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.Capability; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface IRoutePath { - - @NotNull - BlockPos getTargetPipePos(); - - @NotNull - Direction getTargetFacing(); - - int getDistance(); - - @Nullable - T getHandler(Level world); - - @Nullable - default BlockEntity getTargetBlockEntity(Level level) { - return level.getBlockEntity(getTargetPipePos().relative(getTargetFacing())); - } - - @Nullable - default I getTargetCapability(Capability capability, Level level) { - BlockEntity blockEntity = getTargetBlockEntity(level); - return blockEntity == null ? null : - blockEntity.getCapability(capability, getTargetFacing().getOpposite()).resolve().orElse(null); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/ITickablePipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/ITickablePipeNet.java deleted file mode 100644 index c84dedb39e..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/ITickablePipeNet.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -/** - * @author KilaBash - * @date 2023/2/28 - * @implNote ITickablePipeNet - */ -public interface ITickablePipeNet { - - void update(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/LevelPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/LevelPipeNet.java deleted file mode 100644 index 32e78bf31a..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/LevelPipeNet.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import com.gregtechceu.gtceu.utils.GTUtil; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.saveddata.SavedData; - -import java.util.*; - -public abstract class LevelPipeNet> extends SavedData { - - private final ServerLevel serverLevel; - protected List pipeNets = new ArrayList<>(); - protected final Map> pipeNetsByChunk = new HashMap<>(); - - public LevelPipeNet(ServerLevel serverLevel) { - this.serverLevel = serverLevel; - } - - public LevelPipeNet(ServerLevel serverLevel, CompoundTag tag) { - this(serverLevel); - this.pipeNets = new ArrayList<>(); - ListTag allEnergyNets = tag.getList("PipeNets", Tag.TAG_COMPOUND); - for (int i = 0; i < allEnergyNets.size(); i++) { - CompoundTag pNetTag = allEnergyNets.getCompound(i); - T pipeNet = createNetInstance(); - pipeNet.deserializeNBT(pNetTag); - addPipeNetSilently(pipeNet); - } - init(); - } - - public ServerLevel getWorld() { - return serverLevel; - } - - protected void init() { - this.pipeNets.forEach(PipeNet::onNodeConnectionsUpdate); - } - - public void addNode(BlockPos nodePos, NodeDataType nodeData, int mark, int openConnections, boolean isActive) { - T myPipeNet = null; - Node node = new Node<>(nodeData, openConnections, mark, isActive); - for (Direction facing : GTUtil.DIRECTIONS) { - BlockPos offsetPos = nodePos.relative(facing); - T pipeNet = getNetFromPos(offsetPos); - Node secondNode = pipeNet == null ? null : pipeNet.getAllNodes().get(offsetPos); - if (pipeNet != null && pipeNet.canAttachNode(nodeData) && - pipeNet.canNodesConnect(secondNode, facing.getOpposite(), node, null)) { - if (myPipeNet == null) { - myPipeNet = pipeNet; - myPipeNet.addNode(nodePos, node); - } else if (myPipeNet != pipeNet) { - myPipeNet.uniteNetworks(pipeNet); - } - } - - } - if (myPipeNet == null) { - myPipeNet = createNetInstance(); - myPipeNet.addNode(nodePos, node); - addPipeNet(myPipeNet); - setDirty(); - } - } - - protected void addPipeNetToChunk(ChunkPos chunkPos, T pipeNet) { - this.pipeNetsByChunk.computeIfAbsent(chunkPos, any -> new ArrayList<>()).add(pipeNet); - } - - protected void removePipeNetFromChunk(ChunkPos chunkPos, T pipeNet) { - List list = this.pipeNetsByChunk.get(chunkPos); - if (list != null) list.remove(pipeNet); - if (list.isEmpty()) this.pipeNetsByChunk.remove(chunkPos); - } - - public void removeNode(BlockPos nodePos) { - T pipeNet = getNetFromPos(nodePos); - if (pipeNet != null) { - pipeNet.removeNode(nodePos); - } - } - - public void updateBlockedConnections(BlockPos nodePos, Direction side, boolean isBlocked) { - T pipeNet = getNetFromPos(nodePos); - if (pipeNet != null) { - pipeNet.updateBlockedConnections(nodePos, side, isBlocked); - pipeNet.onPipeConnectionsUpdate(); - } - } - - public void updateData(BlockPos nodePos, NodeDataType data) { - T pipeNet = getNetFromPos(nodePos); - if (pipeNet != null) { - pipeNet.updateNodeData(nodePos, data); - } - } - - public void updateMark(BlockPos nodePos, int newMark) { - T pipeNet = getNetFromPos(nodePos); - if (pipeNet != null) { - pipeNet.updateMark(nodePos, newMark); - } - } - - public T getNetFromPos(BlockPos blockPos) { - List pipeNetsInChunk = pipeNetsByChunk.getOrDefault(new ChunkPos(blockPos), Collections.emptyList()); - for (T pipeNet : pipeNetsInChunk) { - if (pipeNet.containsNode(blockPos)) - return pipeNet; - } - return null; - } - - protected void addPipeNet(T pipeNet) { - addPipeNetSilently(pipeNet); - } - - protected void addPipeNetSilently(T pipeNet) { - this.pipeNets.add(pipeNet); - pipeNet.getContainedChunks().forEach(chunkPos -> addPipeNetToChunk(chunkPos, pipeNet)); - pipeNet.isValid = true; - } - - protected void removePipeNet(T pipeNet) { - this.pipeNets.remove(pipeNet); - pipeNet.getContainedChunks().forEach(chunkPos -> removePipeNetFromChunk(chunkPos, pipeNet)); - pipeNet.isValid = false; - setDirty(); - } - - protected abstract T createNetInstance(); - - @Override - public CompoundTag save(CompoundTag compound) { - ListTag allPipeNets = new ListTag(); - for (T pipeNet : pipeNets) { - CompoundTag pNetTag = pipeNet.serializeNBT(); - allPipeNets.add(pNetTag); - } - compound.put("PipeNets", allPipeNets); - return compound; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/Node.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/Node.java deleted file mode 100644 index 23e251d85c..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/Node.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import net.minecraft.core.Direction; - -/** - * Represents a single node in network of pipes - * It can have blocked connections and be active or not - */ -public final class Node { - - public static final int DEFAULT_MARK = 0; - public static final int ALL_OPENED = 0b111111; - public static final int ALL_CLOSED = 0b000000; - - public NodeDataType data; - /** - * Specifies bitmask of blocked connections - * Node will not connect in blocked direction in any case, - * even if neighbour node mark matches - */ - public int openConnections; - /** - * Specifies mark of this node - * Nodes can connect only if their marks are equal, or if - * one of marks is default one - */ - public int mark; - public boolean isActive; - - public Node(NodeDataType data, int openConnections, int mark, boolean isActive) { - this.data = data; - this.openConnections = openConnections; - this.mark = mark; - this.isActive = isActive; - } - - public boolean isBlocked(Direction facing) { - return (openConnections & 1 << facing.ordinal()) == 0; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNet.java deleted file mode 100644 index 1f6bee43ba..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNet.java +++ /dev/null @@ -1,495 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.ChunkPos; - -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; - -import java.util.*; -import java.util.Map.Entry; - -public abstract class PipeNet implements ITagSerializable { - - protected final LevelPipeNet> worldData; - private final Map> nodeByBlockPos = new HashMap<>(); - private final Map> unmodifiableNodeByBlockPos = Collections - .unmodifiableMap(nodeByBlockPos); - private final Map ownedChunks = new HashMap<>(); - private long lastUpdate; - boolean isValid = false; - - public PipeNet(LevelPipeNet> Level) { - // noinspection unchecked - this.worldData = (LevelPipeNet>) Level; - } - - public Set getContainedChunks() { - return Collections.unmodifiableSet(ownedChunks.keySet()); - } - - public LevelPipeNet> getWorldData() { - return worldData; - } - - public ServerLevel getLevel() { - return worldData.getWorld(); - } - - public long getLastUpdate() { - return lastUpdate; - } - - public boolean isValid() { - return isValid; - } - - /** - * Is only called when connections changed of nodes. Nodes can ONLY connect to other nodes. - */ - protected void onNodeConnectionsUpdate() { - this.lastUpdate = System.currentTimeMillis(); - } - - /** - * Is only called when Data changed of nodes. - */ - protected void onNodeDataUpdate() {} - - /** - * Is called when any connection of any pipe in the net changes - */ - public void onPipeConnectionsUpdate() {} - - public void onNeighbourUpdate(BlockPos fromPos) {} - - public Map> getAllNodes() { - return unmodifiableNodeByBlockPos; - } - - public Node getNodeAt(BlockPos blockPos) { - return nodeByBlockPos.get(blockPos); - } - - public boolean containsNode(BlockPos blockPos) { - return nodeByBlockPos.containsKey(blockPos); - } - - public boolean isNodeConnectedTo(BlockPos pos, Direction side) { - var nodeFirst = getNodeAt(pos); - if (nodeFirst == null) return false; - var nodeSecond = getNodeAt(pos.relative(side)); - if (nodeSecond == null) return false; - return canNodesConnect(nodeFirst, side, nodeSecond, this); - } - - protected void addNodeSilently(BlockPos nodePos, Node node) { - this.nodeByBlockPos.put(nodePos, node); - checkAddedInChunk(nodePos); - } - - protected void addNode(BlockPos nodePos, Node node) { - addNodeSilently(nodePos, node); - onNodeConnectionsUpdate(); - worldData.setDirty(); - } - - protected Node removeNodeWithoutRebuilding(BlockPos nodePos) { - Node removedNode = this.nodeByBlockPos.remove(nodePos); - ensureRemovedFromChunk(nodePos); - worldData.setDirty(); - return removedNode; - } - - public void removeNode(BlockPos nodePos) { - if (nodeByBlockPos.containsKey(nodePos)) { - Node selfNode = removeNodeWithoutRebuilding(nodePos); - rebuildNetworkOnNodeRemoval(nodePos, selfNode); - } - } - - protected void checkAddedInChunk(BlockPos nodePos) { - ChunkPos chunkPos = new ChunkPos(nodePos); - int newValue = this.ownedChunks.compute(chunkPos, (pos, old) -> (old == null ? 0 : old) + 1); - if (newValue == 1 && isValid()) { - this.worldData.addPipeNetToChunk(chunkPos, this); - } - } - - protected void ensureRemovedFromChunk(BlockPos nodePos) { - ChunkPos chunkPos = new ChunkPos(nodePos); - int newValue = this.ownedChunks.compute(chunkPos, (pos, old) -> old == null ? 0 : old - 1); - if (newValue == 0) { - this.ownedChunks.remove(chunkPos); - if (isValid()) { - this.worldData.removePipeNetFromChunk(chunkPos, this); - } - } - } - - public void updateBlockedConnections(BlockPos nodePos, Direction facing, boolean isBlocked) { - if (!containsNode(nodePos)) { - return; - } - Node selfNode = getNodeAt(nodePos); - if (selfNode.isBlocked(facing) == isBlocked) { - return; - } - - setBlocked(selfNode, facing, isBlocked); - BlockPos offsetPos = nodePos.relative(facing); - PipeNet pipeNetAtOffset = worldData.getNetFromPos(offsetPos); - if (pipeNetAtOffset == null) { - return; - } - // if we are on that side of node too - // and it is blocked now - if (pipeNetAtOffset == this) { - // if side was unblocked, well, there is really nothing changed in this e-net - // if it is blocked now, but was able to connect with neighbour node before, try split networks - if (isBlocked) { - // need to unblock node before doing canNodesConnectCheck - setBlocked(selfNode, facing, false); - if (canNodesConnect(selfNode, facing, getNodeAt(offsetPos), this)) { - // now block again to call findAllConnectedBlocks - setBlocked(selfNode, facing, true); - HashMap> thisENet = findAllConnectedBlocks(nodePos); - if (!getAllNodes().equals(thisENet)) { - // node visibility has changed, split network into 2 - // node that code below is similar to removeNodeInternal, but only for 2 networks, and without - // node removal - PipeNet newPipeNet = worldData.createNetInstance(); - thisENet.keySet().forEach(this::removeNodeWithoutRebuilding); - newPipeNet.transferNodeData(thisENet, this); - worldData.addPipeNet(newPipeNet); - } - } - } - // there is another network on that side - // if this is an unblock, and we can connect with their node, merge them - - } else if (!isBlocked) { - Node neighbourNode = pipeNetAtOffset.getNodeAt(offsetPos); - // check connection availability from both networks - if (canNodesConnect(selfNode, facing, neighbourNode, pipeNetAtOffset) && - pipeNetAtOffset.canNodesConnect(neighbourNode, facing.getOpposite(), selfNode, this)) { - // so, side is unblocked now, and nodes can connect, merge two networks - // our network consumes other one - uniteNetworks(pipeNetAtOffset); - } - } - onNodeConnectionsUpdate(); - worldData.setDirty(); - } - - public void updateNodeData(BlockPos nodePos, NodeDataType data) { - if (containsNode(nodePos)) { - Node selfNode = getNodeAt(nodePos); - selfNode.data = data; - onNodeDataUpdate(); - worldData.setDirty(); - } - } - - public void updateMark(BlockPos nodePos, int newMark) { - if (!containsNode(nodePos)) { - return; - } - HashMap> selfConnectedBlocks = null; - Node selfNode = getNodeAt(nodePos); - int oldMark = selfNode.mark; - selfNode.mark = newMark; - for (Direction facing : GTUtil.DIRECTIONS) { - BlockPos offsetPos = nodePos.relative(facing); - PipeNet otherPipeNet = worldData.getNetFromPos(offsetPos); - Node secondNode = otherPipeNet == null ? null : otherPipeNet.getNodeAt(offsetPos); - if (secondNode == null) - continue; // there is noting here - if (!areNodeBlockedConnectionsCompatible(selfNode, facing, secondNode) || - !areNodesCustomContactable(selfNode.data, secondNode.data, otherPipeNet)) - continue; // if connections aren't compatible, skip them - if (areMarksCompatible(oldMark, secondNode.mark) == areMarksCompatible(newMark, secondNode.mark)) - continue; // if compatibility didn't change, skip it - if (areMarksCompatible(newMark, secondNode.mark)) { - // if marks are compatible now, and offset network is different network, merge them - // if it is same network, just update mask and paths - if (otherPipeNet != this) { - uniteNetworks(otherPipeNet); - } - // marks are incompatible now, and this net is connected with it - } else if (otherPipeNet == this) { - // search connected nodes from newly marked node - // populate self connected blocks lazily only once - if (selfConnectedBlocks == null) { - selfConnectedBlocks = findAllConnectedBlocks(nodePos); - } - if (getAllNodes().equals(selfConnectedBlocks)) { - continue; // if this node is still connected to this network, just continue - } - // otherwise, it is not connected - HashMap> offsetConnectedBlocks = findAllConnectedBlocks(offsetPos); - // if in the result of remarking offset node has separated from main network, - // and it is also separated from current cable too, form new network for it - if (!offsetConnectedBlocks.equals(selfConnectedBlocks)) { - offsetConnectedBlocks.keySet().forEach(this::removeNodeWithoutRebuilding); - PipeNet offsetPipeNet = worldData.createNetInstance(); - offsetPipeNet.transferNodeData(offsetConnectedBlocks, this); - worldData.addPipeNet(offsetPipeNet); - } - } - } - onNodeConnectionsUpdate(); - worldData.setDirty(); - } - - private void setBlocked(Node selfNode, Direction facing, boolean isBlocked) { - if (!isBlocked) { - selfNode.openConnections |= 1 << facing.ordinal(); - } else { - selfNode.openConnections &= ~(1 << facing.ordinal()); - } - } - - public boolean markNodeAsActive(BlockPos nodePos, boolean isActive) { - if (containsNode(nodePos) && getNodeAt(nodePos).isActive != isActive) { - getNodeAt(nodePos).isActive = isActive; - worldData.setDirty(); - onNodeConnectionsUpdate(); - return true; - } - return false; - } - - protected final void uniteNetworks(PipeNet unitedPipeNet) { - Map> allNodes = new HashMap<>(unitedPipeNet.getAllNodes()); - worldData.removePipeNet(unitedPipeNet); - allNodes.keySet().forEach(unitedPipeNet::removeNodeWithoutRebuilding); - transferNodeData(allNodes, unitedPipeNet); - } - - private boolean areNodeBlockedConnectionsCompatible(Node first, Direction firstFacing, - Node second) { - return !first.isBlocked(firstFacing) && !second.isBlocked(firstFacing.getOpposite()); - } - - private boolean areMarksCompatible(int mark1, int mark2) { - return mark1 == mark2 || mark1 == Node.DEFAULT_MARK || mark2 == Node.DEFAULT_MARK; - } - - /** - * Checks if given nodes can connect - * Note that this logic should equal with block connection logic - * for proper work of network - */ - protected final boolean canNodesConnect(Node first, Direction firstFacing, Node second, - PipeNet secondPipeNet) { - return areNodeBlockedConnectionsCompatible(first, firstFacing, second) && - areMarksCompatible(first.mark, second.mark) && - areNodesCustomContactable(first.data, second.data, secondPipeNet); - } - - // we need to search only this network - protected HashMap> findAllConnectedBlocks(BlockPos startPos) { - HashMap> observedSet = new HashMap<>(); - observedSet.put(startPos, getNodeAt(startPos)); - Node firstNode = getNodeAt(startPos); - BlockPos.MutableBlockPos currentPos = startPos.mutable(); - Deque moveStack = new ArrayDeque<>(); - main: - while (true) { - for (Direction facing : GTUtil.DIRECTIONS) { - currentPos.move(facing); - Node secondNode = getNodeAt(currentPos); - // if there is node, and it can connect with previous node, add it to list, and set previous node as - // current - if (secondNode != null && canNodesConnect(firstNode, facing, secondNode, this) && - !observedSet.containsKey(currentPos)) { - observedSet.put(currentPos.immutable(), getNodeAt(currentPos)); - firstNode = secondNode; - moveStack.push(facing.getOpposite()); - continue main; - } else currentPos.move(facing.getOpposite()); - } - if (!moveStack.isEmpty()) { - currentPos.move(moveStack.pop()); - firstNode = getNodeAt(currentPos); - } else break; - } - return observedSet; - } - - // called when node is removed to rebuild network - protected void rebuildNetworkOnNodeRemoval(BlockPos nodePos, Node selfNode) { - int amountOfConnectedSides = 0; - for (Direction facing : GTUtil.DIRECTIONS) { - BlockPos offsetPos = nodePos.relative(facing); - if (containsNode(offsetPos)) - amountOfConnectedSides++; - } - // if we are connected only on one side or not connected at all, we don't need to find connected blocks - // because they are only on on side or doesn't exist at all - // this saves a lot of performance in big networks, which are quite big to depth-first them fastly - if (amountOfConnectedSides >= 2) { - for (Direction facing : GTUtil.DIRECTIONS) { - BlockPos offsetPos = nodePos.relative(facing); - Node secondNode = getNodeAt(offsetPos); - if (secondNode == null || !canNodesConnect(selfNode, facing, secondNode, this)) { - // if there isn't any neighbour node, or it wasn't connected with us, just skip it - continue; - } - HashMap> thisENet = findAllConnectedBlocks(offsetPos); - if (getAllNodes().equals(thisENet)) { - // if cable on some direction contains all nodes of this network - // the network didn't change so keep it as is - break; - } else { - // and use them to create new network with caching active nodes set - PipeNet energyNet = worldData.createNetInstance(); - // remove blocks that aren't connected with this network - thisENet.keySet().forEach(this::removeNodeWithoutRebuilding); - energyNet.transferNodeData(thisENet, this); - worldData.addPipeNet(energyNet); - } - } - } - if (getAllNodes().isEmpty()) { - // if this energy net is empty now, remove it - worldData.removePipeNet(this); - } - onNodeConnectionsUpdate(); - worldData.setDirty(); - } - - protected boolean areNodesCustomContactable(NodeDataType first, NodeDataType second, - PipeNet secondNodePipeNet) { - return true; - } - - protected boolean canAttachNode(NodeDataType nodeData) { - return true; - } - - /** - * Called during network split when one net needs to transfer some of it's nodes to another one - * Use this for diving old net contents according to node amount of new network - * For example, for fluid pipes it would remove amount of fluid contained in old nodes - * from parent network and add it to it's own tank, keeping network contents when old network is split - * Note that it should be called when parent net doesn't have transferredNodes in allNodes already - */ - protected void transferNodeData(Map> transferredNodes, - PipeNet parentNet) { - transferredNodes.forEach(this::addNodeSilently); - onNodeConnectionsUpdate(); - worldData.setDirty(); - } - - /** - * Serializes node data into specified tag compound - * Used for writing persistent node data - */ - protected abstract void writeNodeData(NodeDataType nodeData, CompoundTag tagCompound); - - /** - * Deserializes node data from specified tag compound - * Used for reading persistent node data - */ - protected abstract NodeDataType readNodeData(CompoundTag tagCompound); - - @Override - public CompoundTag serializeNBT() { - CompoundTag compound = new CompoundTag(); - compound.put("Nodes", serializeAllNodeList(nodeByBlockPos)); - return compound; - } - - @Override - public void deserializeNBT(CompoundTag nbt) { - this.nodeByBlockPos.clear(); - this.ownedChunks.clear(); - deserializeAllNodeList(nbt.getCompound("Nodes")); - } - - protected void deserializeAllNodeList(CompoundTag compound) { - ListTag allNodesList = compound.getList("NodeIndexes", Tag.TAG_COMPOUND); - ListTag wirePropertiesList = compound.getList("WireProperties", Tag.TAG_COMPOUND); - Int2ObjectMap readProperties = new Int2ObjectOpenHashMap<>(); - - for (int i = 0; i < wirePropertiesList.size(); i++) { - CompoundTag propertiesTag = wirePropertiesList.getCompound(i); - int wirePropertiesIndex = propertiesTag.getInt("index"); - NodeDataType nodeData = readNodeData(propertiesTag); - readProperties.put(wirePropertiesIndex, nodeData); - } - - for (int i = 0; i < allNodesList.size(); i++) { - CompoundTag nodeTag = allNodesList.getCompound(i); - int x = nodeTag.getInt("x"); - int y = nodeTag.getInt("y"); - int z = nodeTag.getInt("z"); - int wirePropertiesIndex = nodeTag.getInt("index"); - BlockPos blockPos = new BlockPos(x, y, z); - NodeDataType nodeData = readProperties.get(wirePropertiesIndex); - int openConnections = nodeTag.getInt("open"); - int mark = nodeTag.getInt("mark"); - boolean isNodeActive = nodeTag.getBoolean("active"); - addNodeSilently(blockPos, new Node<>(nodeData, openConnections, mark, isNodeActive)); - } - } - - protected CompoundTag serializeAllNodeList(Map> allNodes) { - CompoundTag compound = new CompoundTag(); - ListTag allNodesList = new ListTag(); - ListTag wirePropertiesList = new ListTag(); - Object2IntMap alreadyWritten = new Object2IntOpenHashMap<>(); - int currentIndex = 0; - - for (Entry> entry : allNodes.entrySet()) { - BlockPos nodePos = entry.getKey(); - Node node = entry.getValue(); - CompoundTag nodeTag = new CompoundTag(); - nodeTag.putInt("x", nodePos.getX()); - nodeTag.putInt("y", nodePos.getY()); - nodeTag.putInt("z", nodePos.getZ()); - int wirePropertiesIndex = alreadyWritten.getOrDefault(node.data, -1); - if (wirePropertiesIndex == -1) { - wirePropertiesIndex = currentIndex; - alreadyWritten.put(node.data, wirePropertiesIndex); - currentIndex++; - } - nodeTag.putInt("index", wirePropertiesIndex); - if (node.mark != Node.DEFAULT_MARK) { - nodeTag.putInt("mark", node.mark); - } - if (node.openConnections > 0) { - nodeTag.putInt("open", node.openConnections); - } - if (node.isActive) { - nodeTag.putBoolean("active", true); - } - allNodesList.add(nodeTag); - } - - for (NodeDataType nodeData : alreadyWritten.keySet()) { - int wirePropertiesIndex = alreadyWritten.getInt(nodeData); - CompoundTag propertiesTag = new CompoundTag(); - propertiesTag.putInt("index", wirePropertiesIndex); - writeNodeData(nodeData, propertiesTag); - wirePropertiesList.add(propertiesTag); - } - - compound.put("NodeIndexes", allNodesList); - compound.put("WireProperties", wirePropertiesList); - return compound; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNetWalker.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNetWalker.java deleted file mode 100644 index 64d904b00e..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/PipeNetWalker.java +++ /dev/null @@ -1,250 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.LDLib; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.block.entity.BlockEntity; - -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.*; - -/** - * This is a helper class to get information about a pipe net - *

- * The walker is written that it will always find the shortest path to any destination - *

- * On the way it can collect information about the pipes and it's neighbours - *

- * After creating a walker simply call {@link #traversePipeNet()} to start walking, then you can just collect the data - *

- * Do not walk a walker more than once - */ -@SuppressWarnings("unused") -public abstract class PipeNetWalker, NodeDataType, Net extends PipeNet> { - - protected PipeNetWalker root; - protected final Net pipeNet; - private Set walked; - protected List> walkers; - protected final BlockPos.MutableBlockPos currentPos; - protected final List nextPipeFacings = new ArrayList<>(5); - protected final List nextPipes = new ArrayList<>(5); - protected T currentPipe; - private Direction from = null; - @Getter - protected int walkedBlocks; - @Getter - protected boolean invalid; - protected boolean running; - @Getter - private boolean failed = false; - - protected PipeNetWalker(Net pipeNet, BlockPos sourcePipe, int walkedBlocks) { - this.pipeNet = pipeNet; - this.walkedBlocks = walkedBlocks; - this.currentPos = sourcePipe.mutable(); - this.root = this; - } - - /** - * Creates a sub walker - * Will be called when a pipe has multiple valid pipes - * - * @param pipeNet pipe net - * @param nextPos next pos to check - * @param walkedBlocks distance from source in blocks - * @return new sub walker - */ - @NotNull - protected abstract PipeNetWalker createSubWalker(Net pipeNet, Direction facingToNextPos, - BlockPos nextPos, int walkedBlocks); - - /** - * Checks the neighbour of the current pos - * - * @param pipePos current pos. Note!! its a mutable pos. - * @param faceToNeighbour face to neighbour - * @param pipeNode pipeNode - * @param neighbourTile the neighboring BlockEntity. Might not be a pipe. - */ - protected void checkNeighbour(T pipeNode, BlockPos pipePos, Direction faceToNeighbour, - @Nullable BlockEntity neighbourTile) {} - - /** - * If the pipe is valid to perform a walk on - * - * @param currentPipe current pipe - * @param neighbourPipe neighbour pipe to check - * @param pipePos current pos (tile.getPipePos() != pipePos) - * @param faceToNeighbour face to pipeTile - * @return if the pipe is valid - */ - protected boolean isValidPipe(T currentPipe, T neighbourPipe, BlockPos pipePos, Direction faceToNeighbour) { - return true; - } - - protected abstract Class getBasePipeClass(); - - /** - * You can increase walking stats here. for example - * - * @param pipeTile current checking pipe - * @param pos current pipe pos - */ - protected abstract void checkPipe(T pipeTile, BlockPos pos); - - /** - * The directions that this net can traverse from this pipe - * - * @return the array of valid Directions - */ - protected Direction[] getSurroundingPipeSides() { - return GTUtil.DIRECTIONS; - } - - /** - * Called when a sub walker is done walking - * - * @param subWalker the finished sub walker - */ - protected void onRemoveSubWalker(PipeNetWalker subWalker) {} - - public void traversePipeNet() { - traversePipeNet(32768); - } - - /** - * Starts walking the pipe net and gathers information. - * - * @param maxWalks max walks to prevent possible stack overflow - * @throws IllegalStateException if the walker already walked - */ - public void traversePipeNet(int maxWalks) { - if (invalid) - throw new IllegalStateException("This walker already walked. Create a new one if you want to walk again"); - root = this; - walked = new ObjectOpenHashSet<>(); - int i = 0; - running = true; - while (running && !walk() && i++ < maxWalks); - running = false; - root.walked.clear(); - if (i >= maxWalks) - LDLib.LOGGER.warn("The walker reached the maximum amount of walks {}", i); - invalid = true; - } - - private boolean walk() { - if (walkers == null) { - if (!checkPos()) { - this.root.failed = true; - return true; - } - - if (nextPipeFacings.isEmpty()) - return true; - if (nextPipeFacings.size() == 1) { - currentPos.set(nextPipes.get(0).getPipePos()); - currentPipe = nextPipes.get(0); - from = nextPipeFacings.get(0).getOpposite(); - walkedBlocks++; - return !isRunning(); - } - - walkers = new ArrayList<>(); - for (int i = 0; i < nextPipeFacings.size(); i++) { - Direction side = nextPipeFacings.get(i); - PipeNetWalker walker = Objects.requireNonNull( - createSubWalker(pipeNet, side, currentPos.relative(side), walkedBlocks + 1), - "Walker can't be null"); - walker.root = root; - walker.currentPipe = nextPipes.get(i); - walker.from = side.getOpposite(); - walkers.add(walker); - } - } - Iterator> iterator = walkers.iterator(); - while (iterator.hasNext()) { - PipeNetWalker walker = iterator.next(); - if (walker.walk()) { - onRemoveSubWalker(walker); - iterator.remove(); - } - } - - return !isRunning() || walkers.isEmpty(); - } - - private boolean checkPos() { - nextPipeFacings.clear(); - nextPipes.clear(); - if (currentPipe == null) { - BlockEntity thisPipe = getLevel().getBlockEntity(currentPos); - if (!(thisPipe instanceof IPipeNode)) { - GTCEu.LOGGER.error("PipeWalker expected a pipe, but found {} at {}", thisPipe, currentPos); - return false; - } - if (!getBasePipeClass().isAssignableFrom(thisPipe.getClass())) { - return false; - } - currentPipe = (T) thisPipe; - } - T pipeTile = currentPipe; - checkPipe(pipeTile, currentPos); - root.walked.add(pipeTile); - - // check for surrounding pipes and item handlers - for (Direction accessSide : getSurroundingPipeSides()) { - // skip sides reported as blocked by pipe network - if (accessSide == from || !pipeTile.isConnected(accessSide)) - continue; - - BlockEntity tile = pipeTile.getNeighbor(accessSide); - if (tile != null && getBasePipeClass().isAssignableFrom(tile.getClass())) { - T otherPipe = (T) tile; - if (!otherPipe.isConnected(accessSide.getOpposite()) || - otherPipe.isBlocked(accessSide.getOpposite()) || isWalked(otherPipe)) - continue; - if (isValidPipe(pipeTile, otherPipe, currentPos, accessSide)) { - nextPipeFacings.add(accessSide); - nextPipes.add(otherPipe); - continue; - } - } - checkNeighbour(pipeTile, currentPos, accessSide, tile); - } - return true; - } - - protected boolean isWalked(T pipe) { - return root.walked.contains(pipe); - } - - /** - * Will cause the root walker to stop after the next walk - */ - public void stop() { - root.running = false; - } - - public boolean isRunning() { - return root.running; - } - - public ServerLevel getLevel() { - return pipeNet.getLevel(); - } - - public BlockPos getCurrentPos() { - return currentPos.immutable(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/pipenet/TickableLevelPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/pipenet/TickableLevelPipeNet.java deleted file mode 100644 index d06fb258b8..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/pipenet/TickableLevelPipeNet.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.gregtechceu.gtceu.api.pipenet; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.ChunkAccess; - -import org.apache.commons.lang3.tuple.Pair; - -import java.util.*; -import java.util.stream.Collectors; - -public abstract class TickableLevelPipeNet & ITickablePipeNet> - extends LevelPipeNet { - - private final Map> loadedChunksByPipeNet = new HashMap<>(); - private final Set tickingPipeNets = new HashSet<>(); - private final Set removeLater = new HashSet<>(); - - public TickableLevelPipeNet(ServerLevel serverLevel) { - super(serverLevel); - } - - public TickableLevelPipeNet(ServerLevel serverLevel, CompoundTag tag) { - super(serverLevel, tag); - } - - private boolean isChunkLoaded(ChunkPos chunkPos) { - var worldServer = getWorld(); - if (worldServer == null) return false; - return worldServer.getChunkSource().hasChunk(chunkPos.x, chunkPos.z); - } - - protected abstract int getUpdateRate(); - - public void update() { - if (getWorld().getGameTime() % getUpdateRate() == 0L) { - tickingPipeNets.forEach(ITickablePipeNet::update); - } - if (removeLater.size() > 0) { - removeLater.forEach(tickingPipeNets::remove); - removeLater.clear(); - } - } - - public void onChunkLoaded(ChunkAccess chunk) { - ChunkPos chunkPos = chunk.getPos(); - List pipeNetsInThisChunk = this.pipeNetsByChunk.get(chunkPos); - if (pipeNetsInThisChunk == null) return; - for (T pipeNet : pipeNetsInThisChunk) { - List loadedChunks = getOrCreateChunkListForPipeNet(pipeNet); - if (loadedChunks.isEmpty()) { - this.tickingPipeNets.add(pipeNet); - } - loadedChunks.add(chunkPos); - } - } - - public void onChunkUnloaded(ChunkAccess chunk) { - ChunkPos chunkPos = chunk.getPos(); - List pipeNetsInThisChunk = this.pipeNetsByChunk.get(chunkPos); - if (pipeNetsInThisChunk == null) return; - for (T pipeNet : pipeNetsInThisChunk) { - List loadedChunks = this.loadedChunksByPipeNet.get(pipeNet); - if (loadedChunks != null && loadedChunks.contains(chunkPos)) { - loadedChunks.remove(chunkPos); - if (loadedChunks.isEmpty()) { - removeFromTicking(pipeNet); - } - } - } - } - - @Override - protected void init() { - super.init(); - Map> pipeNetByLoadedChunks = pipeNets.stream() - .map(pipeNet -> Pair.of(pipeNet, getPipeNetLoadedChunks(pipeNet))) - .filter(pair -> !pair.getRight().isEmpty()) - .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); - if (!pipeNetByLoadedChunks.isEmpty()) { - this.tickingPipeNets.addAll(pipeNetByLoadedChunks.keySet()); - this.loadedChunksByPipeNet.putAll(pipeNetByLoadedChunks); - } - } - - @Override - protected void addPipeNet(T pipeNet) { - super.addPipeNet(pipeNet); - List loadedChunks = getPipeNetLoadedChunks(pipeNet); - if (!loadedChunks.isEmpty()) { - this.loadedChunksByPipeNet.put(pipeNet, loadedChunks); - this.tickingPipeNets.add(pipeNet); - } - } - - private List getPipeNetLoadedChunks(T pipeNet) { - return pipeNet.getContainedChunks().stream() - .filter(this::isChunkLoaded) - .collect(Collectors.toList()); - } - - @Override - protected void removePipeNet(T pipeNet) { - super.removePipeNet(pipeNet); - if (loadedChunksByPipeNet.containsKey(pipeNet)) { - removeFromTicking(pipeNet); - } - } - - private void removeFromTicking(T pipeNet) { - this.loadedChunksByPipeNet.remove(pipeNet); - this.removeLater.add(pipeNet); - } - - private List getOrCreateChunkListForPipeNet(T pipeNet) { - return this.loadedChunksByPipeNet.computeIfAbsent(pipeNet, k -> new ArrayList<>()); - } - - @Override - protected void addPipeNetToChunk(ChunkPos chunkPos, T pipeNet) { - super.addPipeNetToChunk(chunkPos, pipeNet); - if (isChunkLoaded(chunkPos)) { - List loadedChunks = getOrCreateChunkListForPipeNet(pipeNet); - if (loadedChunks.isEmpty()) { - this.tickingPipeNets.add(pipeNet); - } - loadedChunks.add(chunkPos); - } - } - - @Override - protected void removePipeNetFromChunk(ChunkPos chunkPos, T pipeNet) { - super.removePipeNetFromChunk(chunkPos, pipeNet); - List loadedChunks = this.loadedChunksByPipeNet.get(pipeNet); - if (loadedChunks != null && loadedChunks.contains(chunkPos)) { - loadedChunks.remove(chunkPos); - if (loadedChunks.isEmpty()) { - removeFromTicking(pipeNet); - } - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/model/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/model/PipeModel.java deleted file mode 100644 index 51b44a9cea..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/model/PipeModel.java +++ /dev/null @@ -1,356 +0,0 @@ -package com.gregtechceu.gtceu.client.model; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.utils.GTUtil; -import com.gregtechceu.gtceu.utils.SupplierMemoizer; - -import com.lowdragmc.lowdraglib.client.bakedpipeline.FaceQuad; -import com.lowdragmc.lowdraglib.client.model.ModelFactory; -import com.lowdragmc.lowdraglib.client.renderer.IItemRendererProvider; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.shapes.Shapes; -import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import com.mojang.blaze3d.vertex.PoseStack; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import lombok.Setter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * @author KilaBash - * @date 2023/3/1 - * @implNote PipeModel - */ -public class PipeModel { - - public static final ResourceLocation PIPE_BLOCKED_OVERLAY = GTCEu.id("block/pipe/blocked/pipe_blocked"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_UP = GTCEu.id("block/pipe/blocked/pipe_blocked_up"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_DOWN = GTCEu.id("block/pipe/blocked/pipe_blocked_down"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_LEFT = GTCEu.id("block/pipe/blocked/pipe_blocked_left"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_RIGHT = GTCEu.id("block/pipe/blocked/pipe_blocked_right"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_NU = GTCEu.id("block/pipe/blocked/pipe_blocked_nu"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_ND = GTCEu.id("block/pipe/blocked/pipe_blocked_nd"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_NL = GTCEu.id("block/pipe/blocked/pipe_blocked_nl"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_NR = GTCEu.id("block/pipe/blocked/pipe_blocked_nr"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_UD = GTCEu.id("block/pipe/blocked/pipe_blocked_ud"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_UL = GTCEu.id("block/pipe/blocked/pipe_blocked_ul"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_UR = GTCEu.id("block/pipe/blocked/pipe_blocked_ur"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_DL = GTCEu.id("block/pipe/blocked/pipe_blocked_dl"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_DR = GTCEu.id("block/pipe/blocked/pipe_blocked_dr"); - public static final ResourceLocation PIPE_BLOCKED_OVERLAY_LR = GTCEu.id("block/pipe/blocked/pipe_blocked_lr"); - private static final EnumMap> FACE_BORDER_MAP = new EnumMap<>( - Direction.class); - private static final Int2ObjectMap RESTRICTOR_MAP = new Int2ObjectOpenHashMap<>(); - private static boolean isRestrictorInitialized; - - public static void initializeRestrictor(Function atlas) { - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_UP), Border.TOP); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_DOWN), Border.BOTTOM); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_UD), Border.TOP, Border.BOTTOM); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_LEFT), Border.LEFT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_UL), Border.TOP, Border.LEFT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_DL), Border.BOTTOM, Border.LEFT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_NR), Border.TOP, Border.BOTTOM, Border.LEFT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_RIGHT), Border.RIGHT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_UR), Border.TOP, Border.RIGHT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_DR), Border.BOTTOM, Border.RIGHT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_NL), Border.TOP, Border.BOTTOM, Border.RIGHT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_LR), Border.LEFT, Border.RIGHT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_ND), Border.TOP, Border.LEFT, Border.RIGHT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY_NU), Border.BOTTOM, Border.LEFT, Border.RIGHT); - addRestrictor(atlas.apply(PIPE_BLOCKED_OVERLAY), Border.TOP, Border.BOTTOM, Border.LEFT, Border.RIGHT); - } - - static { - FACE_BORDER_MAP.put(Direction.DOWN, - borderMap(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST)); - FACE_BORDER_MAP.put(Direction.UP, - borderMap(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST)); - FACE_BORDER_MAP.put(Direction.NORTH, - borderMap(Direction.DOWN, Direction.UP, Direction.WEST, Direction.EAST)); - FACE_BORDER_MAP.put(Direction.SOUTH, - borderMap(Direction.DOWN, Direction.UP, Direction.WEST, Direction.EAST)); - FACE_BORDER_MAP.put(Direction.WEST, - borderMap(Direction.DOWN, Direction.UP, Direction.NORTH, Direction.SOUTH)); - FACE_BORDER_MAP.put(Direction.EAST, - borderMap(Direction.DOWN, Direction.UP, Direction.NORTH, Direction.SOUTH)); - } - - public final static int ITEM_CONNECTIONS = 0b001100; - public final float thickness; - public final AABB coreCube; - public final Map sideCubes; - - public SupplierMemoizer.MemoizedSupplier sideTexture, endTexture; - @Nullable - public SupplierMemoizer.MemoizedSupplier<@Nullable ResourceLocation> secondarySideTexture, secondaryEndTexture; - @Setter - public ResourceLocation sideOverlayTexture, endOverlayTexture; - - @OnlyIn(Dist.CLIENT) - TextureAtlasSprite sideSprite, endSprite, secondarySideSprite, secondaryEndSprite, sideOverlaySprite, - endOverlaySprite; - - public PipeModel(float thickness, Supplier sideTexture, Supplier endTexture, - @Nullable Supplier<@Nullable ResourceLocation> secondarySideTexture, - @Nullable Supplier<@Nullable ResourceLocation> secondaryEndTexture) { - this.sideTexture = SupplierMemoizer.memoize(sideTexture); - this.endTexture = SupplierMemoizer.memoize(endTexture); - this.secondarySideTexture = secondarySideTexture != null ? SupplierMemoizer.memoize(secondarySideTexture) : - null; - this.secondaryEndTexture = secondaryEndTexture != null ? SupplierMemoizer.memoize(secondaryEndTexture) : null; - this.thickness = thickness; - double min = (1d - thickness) / 2; - double max = min + thickness; - this.coreCube = new AABB(min, min, min, max, max, max); - this.sideCubes = new EnumMap<>(Direction.class); - for (Direction side : GTUtil.DIRECTIONS) { - var normal = side.getNormal(); - sideCubes.put(side, new AABB( - normal.getX() == 0 ? min : normal.getX() > 0 ? max : 0, - normal.getY() == 0 ? min : normal.getY() > 0 ? max : 0, - normal.getZ() == 0 ? min : normal.getZ() > 0 ? max : 0, - normal.getX() == 0 ? max : normal.getX() > 0 ? 1 : min, - normal.getY() == 0 ? max : normal.getY() > 0 ? 1 : min, - normal.getZ() == 0 ? max : normal.getZ() > 0 ? 1 : min)); - } - } - - public VoxelShape getShapes(int connections) { - var shapes = new ArrayList(7); - shapes.add(Shapes.create(coreCube)); - for (Direction side : GTUtil.DIRECTIONS) { - if (PipeBlockEntity.isConnected(connections, side)) { - shapes.add(Shapes.create(sideCubes.get(side))); - } - } - return shapes.stream().reduce(Shapes.empty(), Shapes::or); - } - - @OnlyIn(Dist.CLIENT) - public List bakeQuads(@Nullable Direction side, int connections, int blockedConnections) { - if (!isRestrictorInitialized) { - initializeRestrictor(ModelFactory::getBlockSprite); - isRestrictorInitialized = true; - } - if (sideSprite == null) { - sideSprite = ModelFactory.getBlockSprite(sideTexture.get()); - } - if (endSprite == null) { - endSprite = ModelFactory.getBlockSprite(endTexture.get()); - } - if (secondarySideTexture != null && secondarySideTexture.get() != null && secondarySideSprite == null) { - secondarySideSprite = ModelFactory.getBlockSprite(secondarySideTexture.get()); - } - if (secondaryEndTexture != null && secondaryEndTexture.get() != null && secondaryEndSprite == null) { - secondaryEndSprite = ModelFactory.getBlockSprite(secondaryEndTexture.get()); - } - if (sideOverlayTexture != null && sideOverlaySprite == null) { - sideOverlaySprite = ModelFactory.getBlockSprite(sideOverlayTexture); - } - if (endOverlayTexture != null && endOverlaySprite == null) { - endOverlaySprite = ModelFactory.getBlockSprite(endOverlayTexture); - } - - if (side != null) { - if (thickness == 1) { // full block - List quads = new ArrayList<>(); - quads.add(FaceQuad.builder(side, sideSprite).cube(coreCube).cubeUV().tintIndex(0).bake()); - if (secondarySideSprite != null) { - quads.add(FaceQuad.builder(side, secondarySideSprite).cube(coreCube).cubeUV().tintIndex(0).bake()); - } - return quads; - } - - if (PipeBlockEntity.isConnected(connections, side)) { // side connected - List quads = new ArrayList<>(); - quads.add(FaceQuad.builder(side, endSprite).cube(sideCubes.get(side).inflate(-0.001)).cubeUV() - .tintIndex(1).bake()); - if (secondaryEndSprite != null) { - quads.add(FaceQuad.builder(side, secondaryEndSprite).cube(sideCubes.get(side)).cubeUV().tintIndex(1) - .bake()); - } - if (endOverlaySprite != null) { - quads.add(FaceQuad.builder(side, endOverlaySprite).cube(sideCubes.get(side)).cubeUV().tintIndex(0) - .bake()); - } - if (sideOverlaySprite != null) { - for (Direction face : GTUtil.DIRECTIONS) { - if (face.getAxis() != side.getAxis()) { - quads.add(FaceQuad.builder(face, sideOverlaySprite).cube(sideCubes.get(side)).cubeUV() - .tintIndex(2).bake()); - } - } - } - int borderMask = computeBorderMask(blockedConnections, connections, side); - if (borderMask != 0) { - quads.add(FaceQuad.builder(side, RESTRICTOR_MAP.get(borderMask)).cube(sideCubes.get(side)).cubeUV() - .bake()); - } - return quads; - } - - return Collections.emptyList(); - } - - List quads = new LinkedList<>(); - if (thickness < 1) { // non full block - // render core cube - for (Direction face : GTUtil.DIRECTIONS) { - if (!PipeBlockEntity.isConnected(connections, face)) { - quads.add(FaceQuad.builder(face, sideSprite).cube(coreCube).cubeUV().tintIndex(0).bake()); - if (secondarySideSprite != null) { - quads.add(FaceQuad.builder(face, secondarySideSprite).cube(coreCube).cubeUV().tintIndex(0) - .bake()); - } - } - // render each connected side - for (Direction facing : GTUtil.DIRECTIONS) { - if (facing.getAxis() != face.getAxis()) { - if (PipeBlockEntity.isConnected(connections, facing)) { - quads.add(FaceQuad.builder(face, sideSprite).cube(sideCubes.get(facing)).cubeUV() - .tintIndex(0).bake()); - if (secondarySideSprite != null) { - quads.add(FaceQuad.builder(face, secondarySideSprite).cube(sideCubes.get(facing)) - .cubeUV().tintIndex(0).bake()); - } - if (sideOverlaySprite != null) { - quads.add(FaceQuad.builder(face, sideOverlaySprite) - .cube(sideCubes.get(facing).inflate(0.001)).cubeUV().tintIndex(2).bake()); - } - int borderMask = computeBorderMask(blockedConnections, connections, face); - if (borderMask != 0) { - quads.add(FaceQuad.builder(face, RESTRICTOR_MAP.get(borderMask)) - .cube(sideCubes.get(facing)).cubeUV().bake()); - } - } - } - } - } - } - return quads; - } - - @NotNull - @OnlyIn(Dist.CLIENT) - public TextureAtlasSprite getParticleTexture() { - if (sideSprite == null) { - sideSprite = ModelFactory.getBlockSprite(sideTexture.get()); - } - return sideSprite; - } - - private final Map, List> itemModelCache = new ConcurrentHashMap<>(); - - @OnlyIn(Dist.CLIENT) - public void renderItem(ItemStack stack, ItemDisplayContext transformType, boolean leftHand, PoseStack matrixStack, - MultiBufferSource buffer, int combinedLight, int combinedOverlay, BakedModel model) { - IItemRendererProvider.disabled.set(true); - Minecraft.getInstance().getItemRenderer().render(stack, transformType, leftHand, matrixStack, buffer, - combinedLight, combinedOverlay, - (ItemBakedModel) (state, direction, random) -> itemModelCache.computeIfAbsent( - Optional.ofNullable(direction), - direction1 -> bakeQuads(direction1.orElse(null), ITEM_CONNECTIONS, 0))); - IItemRendererProvider.disabled.set(false); - } - - @OnlyIn(Dist.CLIENT) - public void registerTextureAtlas(Consumer register) { - itemModelCache.clear(); - sideTexture.forget(); - register.accept(sideTexture.get()); - endTexture.forget(); - register.accept(endTexture.get()); - if (secondarySideTexture != null) { - secondarySideTexture.forget(); - if (secondarySideTexture.get() != null) { - register.accept(secondarySideTexture.get()); - } - } - if (secondaryEndTexture != null) { - secondaryEndTexture.forget(); - if (secondaryEndTexture.get() != null) { - register.accept(secondaryEndTexture.get()); - } - } - if (sideOverlayTexture != null) register.accept(sideOverlayTexture); - if (endOverlayTexture != null) register.accept(endOverlayTexture); - sideSprite = null; - endSprite = null; - endOverlaySprite = null; - } - - private static EnumMap borderMap(Direction topSide, Direction bottomSide, Direction leftSide, - Direction rightSide) { - EnumMap sideMap = new EnumMap<>(Border.class); - sideMap.put(Border.TOP, topSide); - sideMap.put(Border.BOTTOM, bottomSide); - sideMap.put(Border.LEFT, leftSide); - sideMap.put(Border.RIGHT, rightSide); - return sideMap; - } - - private static void addRestrictor(TextureAtlasSprite sprite, Border... borders) { - int mask = 0; - for (Border border : borders) { - mask |= border.mask; - } - RESTRICTOR_MAP.put(mask, sprite); - } - - protected static Direction getSideAtBorder(Direction side, Border border) { - return FACE_BORDER_MAP.get(side).get(border); - } - - protected static int computeBorderMask(int blockedConnections, int connections, Direction side) { - int borderMask = 0; - if (blockedConnections != 0) { - for (Border border : Border.VALUES) { - Direction borderSide = getSideAtBorder(side, border); - if (PipeBlockEntity.isFaceBlocked(blockedConnections, borderSide) && - PipeBlockEntity.isConnected(connections, borderSide)) { - // only render when the side is blocked *and* connected - borderMask |= border.mask; - } - } - } - return borderMask; - } - - public enum Border { - - TOP, - BOTTOM, - LEFT, - RIGHT; - - public static final Border[] VALUES = values(); - - public final int mask; - - Border() { - mask = 1 << this.ordinal(); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java index da0351f097..e75cedfb56 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java @@ -1,13 +1,11 @@ package com.gregtechceu.gtceu.client.renderer; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; -import com.gregtechceu.gtceu.api.pipenet.IPipeType; import com.gregtechceu.gtceu.common.item.CoverPlaceBehavior; import com.gregtechceu.gtceu.common.item.tool.rotation.CustomBlockRotations; import com.gregtechceu.gtceu.core.mixins.GuiGraphicsAccessor; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java index 9ba20b25de..0bc22005f7 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java @@ -2,8 +2,6 @@ import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.client.model.PipeModel; import com.gregtechceu.gtceu.client.renderer.cover.ICoverableRenderer; import com.gregtechceu.gtceu.common.data.GTBlocks; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java new file mode 100644 index 0000000000..4b45471fbe --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java @@ -0,0 +1,65 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.lowdragmc.lowdraglib.client.model.ModelFactory; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.client.model.data.ModelData; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class DuctPipeModel extends AbstractPipeModel { + + private static final ResourceLocation loc = GTCEu.id("block/duct_pipe"); + + public static final DuctPipeModel INSTANCE = new DuctPipeModel(); + + private static final ResourceLocation SIDE_TEXTURE = GTCEu.id("block/pipe/pipe_duct_side"); + private static final ResourceLocation END_TEXTURE = GTCEu.id("block/pipe/pipe_duct_in"); + + private SpriteInformation sideSprite; + private SpriteInformation endSprite; + + public DuctPipeModel() { + super(new ModelResourceLocation(loc, "")); + } + + @Override + protected @NotNull CacheKey toKey(@NotNull ModelData state) { + return defaultKey(state); + } + + @Override + protected StructureQuadCache constructForKey(CacheKey key) { + if (sideSprite == null) { + sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(SIDE_TEXTURE), -1); + } + if (endSprite == null) { + endSprite = new SpriteInformation(ModelFactory.getBlockSprite(END_TEXTURE), -1); + } + + return StructureQuadCache.create(PipeQuadHelper.create(key.getThickness()), endSprite, sideSprite); + } + + @Override + public SpriteInformation getParticleSprite(@Nullable Material material) { + return sideSprite; + } + + @Override + protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity) { + PipeBlock block = PipeBlock.getBlockFromItem(stack); + if (block == null) return null; + return new PipeItemModel<>(this, new CacheKey(block.getStructure().getRenderThickness()), new ColorData()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java deleted file mode 100644 index 73bb668fe5..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/block/DuctPipeBlock.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.gregtechceu.gtceu.common.block; - -import com.gregtechceu.gtceu.api.blockentity.MetaMachineBlockEntity; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardCleaner; -import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardEmitter; -import com.gregtechceu.gtceu.api.pipenet.IPipeNode; -import com.gregtechceu.gtceu.client.model.PipeModel; -import com.gregtechceu.gtceu.client.renderer.block.PipeBlockRenderer; -import com.gregtechceu.gtceu.common.blockentity.DuctPipeBlockEntity; -import com.gregtechceu.gtceu.common.data.GTBlockEntities; -import com.gregtechceu.gtceu.common.pipelike.duct.DuctPipeProperties; -import com.gregtechceu.gtceu.common.pipelike.duct.DuctPipeType; -import com.gregtechceu.gtceu.common.pipelike.duct.LevelDuctPipeNet; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.Direction; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; - -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -import javax.annotation.ParametersAreNonnullByDefault; - -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -public class DuctPipeBlock extends PipeBlock { - - public final PipeBlockRenderer renderer; - public final PipeModel model; - private final DuctPipeProperties properties; - - public DuctPipeBlock(BlockBehaviour.Properties properties, DuctPipeType type) { - super(properties, type); - this.properties = new DuctPipeProperties(type.getRateMultiplier()); - this.model = type.createPipeModel(); - this.renderer = new PipeBlockRenderer(this.model); - } - - @Override - public LevelDuctPipeNet getWorldPipeNet(ServerLevel world) { - return LevelDuctPipeNet.getOrCreate(world); - } - - @Override - public BlockEntityType> getBlockEntityType() { - return GTBlockEntities.DUCT_PIPE.get(); - } - - @Override - public DuctPipeProperties createRawData(BlockState pState, @Nullable ItemStack pStack) { - return properties; - } - - @Override - public DuctPipeProperties createProperties(IPipeNode pipeTile) { - DuctPipeType pipeType = pipeTile.getPipeType(); - if (pipeType == null) return getFallbackType(); - return this.pipeType.modifyProperties(properties); - } - - @Override - public DuctPipeProperties getFallbackType() { - return properties; - } - - @Override - public @Nullable PipeBlockRenderer getRenderer(BlockState state) { - return renderer; - } - - @Override - protected PipeModel getPipeModel() { - return model; - } - - @Override - public boolean canPipesConnect(IPipeNode selfTile, Direction side, - IPipeNode sideTile) { - return selfTile instanceof DuctPipeBlockEntity && sideTile instanceof DuctPipeBlockEntity; - } - - @Override - public boolean canPipeConnectToBlock(IPipeNode selfTile, Direction side, - @Nullable BlockEntity tile) { - return tile != null && - (tile.getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, side.getOpposite()).isPresent() || - tile instanceof MetaMachineBlockEntity metaMachine && - (metaMachine.getMetaMachine() instanceof IEnvironmentalHazardCleaner || - metaMachine.getMetaMachine() instanceof IEnvironmentalHazardEmitter)); - } - - @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, - TooltipFlag flag) { - super.appendHoverText(stack, level, tooltip, flag); - tooltip.add(Component.translatable("gtceu.duct_pipe.transfer_rate", - this.pipeType.modifyProperties(this.properties).getTransferRate())); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java index d2e27a6984..0905ec738c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.common.blockentity; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.IHazardParticleContainer; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index 5b6f2affec..dbbbc4e9a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.blockentity.*; +import com.simibubi.create.content.fluids.pipes.FluidPipeBlockEntity; import net.minecraft.world.level.block.entity.SignBlockEntity; import com.tterrag.registrate.util.entry.BlockEntityEntry; @@ -24,39 +25,14 @@ public class GTBlockEntities { public static final BlockEntityEntry NEW_PIPE = REGISTRATE .blockEntity("pipe", PipeBlockEntity::new) - .validBlocks(Stream.concat(Arrays.stream(GTBlocks.DUCT_PIPES), + .validBlocks(Stream.concat(GTBlocks.DUCT_PIPE_BLOCKS.values().stream(), Stream.concat(Stream.of(GTBlocks.OPTICAL_PIPE), Stream.concat(Stream.of(GTBlocks.LASER_PIPE), - Stream.concat(GTBlocks.ITEM_PIPE_BLOCKS.values().stream(), - Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), - GTBlocks.MATERIAL_PIPE_BLOCKS.values().stream()))))) + Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), + GTBlocks.MATERIAL_PIPE_BLOCKS.values().stream())))) .toArray(NonNullSupplier[]::new)) .register(); - public static final BlockEntityEntry FLUID_PIPE = REGISTRATE - .blockEntity("fluid_pipe", FluidPipeBlockEntity::new) - .onRegister(FluidPipeBlockEntity::onBlockEntityRegister) - .validBlocks(GTBlocks.MATERIAL_PIPE_BLOCKS.values().toArray(BlockEntry[]::new)) - .register(); - - public static final BlockEntityEntry ITEM_PIPE = REGISTRATE - .blockEntity("item_pipe", ItemPipeBlockEntity::create) - .onRegister(ItemPipeBlockEntity::onBlockEntityRegister) - .validBlocks(GTBlocks.ITEM_PIPE_BLOCKS.values().toArray(BlockEntry[]::new)) - .register(); - - public static final BlockEntityEntry LASER_PIPE = REGISTRATE - .blockEntity("laser_pipe", LaserPipeBlockEntity::create) - .onRegister(LaserPipeBlockEntity::onBlockEntityRegister) - .validBlocks(GTBlocks.LASER_PIPE) - .register(); - - public static final BlockEntityEntry DUCT_PIPE = REGISTRATE - .blockEntity("duct_pipe", DuctPipeBlockEntity::create) - .onRegister(DuctPipeBlockEntity::onBlockEntityRegister) - .validBlocks(GTBlocks.DUCT_PIPES) - .register(); - public static final BlockEntityEntry GT_SIGN = REGISTRATE .blockEntity("sign", SignBlockEntity::new) .validBlocks(GTBlocks.RUBBER_SIGN, diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index dbb8ecd430..77b9ff22cc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -14,6 +14,7 @@ import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.data.tag.TagUtil; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlockItem; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem; import com.gregtechceu.gtceu.api.item.*; import com.gregtechceu.gtceu.api.item.tool.GTToolType; @@ -27,13 +28,14 @@ import com.gregtechceu.gtceu.common.block.explosive.PowderbarrelBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; +import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctPipeBlock; +import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctStructure; import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserStructure; import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; -import com.gregtechceu.gtceu.common.pipelike.duct.DuctPipeType; import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidPipeType; import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemPipeType; import com.gregtechceu.gtceu.core.mixins.BlockPropertiesAccessor; @@ -122,7 +124,7 @@ public class GTBlocks { .builder(); private static ImmutableTable.Builder> MATERIAL_PIPE_BLOCKS_BUILDER = ImmutableTable .builder(); - private static ImmutableTable.Builder> ITEM_PIPE_BLOCKS_BUILDER = ImmutableTable + private static ImmutableMap.Builder> DUCT_PIPE_BLOCKS_BUILDER = ImmutableMap .builder(); ////////////////////////////////////// @@ -132,7 +134,7 @@ public class GTBlocks { public static Map> SURFACE_ROCK_BLOCKS; public static Table> CABLE_BLOCKS; public static Table> MATERIAL_PIPE_BLOCKS; - public static final BlockEntry[] DUCT_PIPES = new BlockEntry[DuctPipeType.VALUES.length]; + public static Map> DUCT_PIPE_BLOCKS; public static final BlockEntry LASER_PIPE = REGISTRATE .block("normal_laser_pipe", (p) -> new LaserPipeBlock(p, LaserStructure.NORMAL)) .initialProperties(() -> Blocks.IRON_BLOCK) @@ -370,7 +372,7 @@ private static void registerFluidPipeBlock(Material material, MaterialPipeStruct .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) - .item(PipeBlockItem::new) + .item(MaterialPipeBlockItem::new) .model(NonNullBiConsumer.noop()) .build() .register(); @@ -380,27 +382,27 @@ private static void registerFluidPipeBlock(Material material, MaterialPipeStruct // Optical Pipe Blocks private static void generateDuctPipeBlocks() { GTCEu.LOGGER.debug("Generating GTCEu Duct Pipe Blocks..."); - for (int i = 0; i < DuctPipeType.VALUES.length; ++i) { - registerDuctPipeBlock(i); + for (var structure : PipeStructureRegistry.getStructures(DuctStructure.class)) { + registerDuctPipeBlock(structure); } + DUCT_PIPE_BLOCKS = DUCT_PIPE_BLOCKS_BUILDER.build(); GTCEu.LOGGER.debug("Generating GTCEu Duct Pipe Blocks... Complete!"); } - private static void registerDuctPipeBlock(int index) { - var type = DuctPipeType.VALUES[index]; + private static void registerDuctPipeBlock(DuctStructure structure) { var entry = REGISTRATE - .block("%s_duct_pipe".formatted(type.getSerializedName()), (p) -> new DuctPipeBlock(p, type)) + .block("%s_duct_pipe".formatted(structure.getSerializedName()), (p) -> new DuctPipeBlock(p, structure)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) .blockstate(NonNullBiConsumer.noop()) .defaultLoot() .tag(GTToolType.WRENCH.harvestTags.get(0)) .addLayer(() -> RenderType::cutoutMipped) - .item(DuctPipeBlockItem::new) + .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) .build() .register(); - DUCT_PIPES[index] = entry; + DUCT_PIPE_BLOCKS_BUILDER.put(structure, entry); } ////////////////////////////////////// @@ -1636,6 +1638,7 @@ public static void init() { SURFACE_ROCK_BLOCKS_BUILDER = null; CABLE_BLOCKS_BUILDER = null; MATERIAL_PIPE_BLOCKS_BUILDER = null; + DUCT_PIPE_BLOCKS_BUILDER = null; // GCyM GCyMBlocks.init(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java b/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java index e9951d4a7c..1b0cc7ee33 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.component.IAddInformation; import com.gregtechceu.gtceu.api.item.component.IDurabilityBar; import com.gregtechceu.gtceu.api.item.component.IInteractionItem; diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index 4681dad360..4b9f2adc2f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.block.IMachineBlock; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.IElectricItem; import com.gregtechceu.gtceu.api.capability.IEnergyContainer; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java index 113b39fd44..ae71c861ea 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.IControllable; import com.gregtechceu.gtceu.api.gui.GuiTextures; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java new file mode 100644 index 0000000000..8e19254044 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java @@ -0,0 +1,39 @@ +package com.gregtechceu.gtceu.common.pipelike.block.duct; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.item.tool.GTToolType; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; +import com.gregtechceu.gtceu.common.pipelike.handlers.DuctNetHandler; +import net.minecraft.core.BlockPos; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockGetter; +import org.jetbrains.annotations.NotNull; + +public class DuctPipeBlock extends PipeBlock { + + public DuctPipeBlock(Properties properties, DuctStructure structure) { + super(properties, structure); + } + + @Override + protected String getConnectLangKey() { + return "gregtech.tool_action.wrench.connect"; + } + + @Override + protected boolean allowsBlocking() { + return false; + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + return DuctNetHandler.INSTANCE; + } + + @Override + protected @NotNull IPipeNetNodeHandler getHandler(@NotNull ItemStack stack) { + return DuctNetHandler.INSTANCE; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java new file mode 100644 index 0000000000..c5b5972551 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -0,0 +1,63 @@ +package com.gregtechceu.gtceu.common.pipelike.block.duct; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.DuctPipeModel; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +public record DuctStructure(String name, float renderThickness, float rateMultiplier) implements IPipeStructure { + + public static final DuctStructure SMALL = new DuctStructure("small", 0.375f, 2f); + public static final DuctStructure NORMAL = new DuctStructure("normal", 0.5f, 4f); + public static final DuctStructure LARGE = new DuctStructure("large", 0.75f, 8f); + public static final DuctStructure HUGE = new DuctStructure("huge", 0.75f, 16f); + + public DuctStructure { + PipeStructureRegistry.register(this); + } + + @Override + public boolean canConnectTo(Direction side, byte connectionMask) { + byte connectionCount = 0; + for (Direction facing : GTUtil.DIRECTIONS) { + if (facing == side) continue; + if (GTUtil.evalMask(facing, connectionMask)) { + connectionCount++; + } + if (connectionCount > 1) return false; + } + return true; + } + + @Override + public @NotNull String getSerializedName() { + return name; + } + + @Override + public float getRenderThickness() { + return renderThickness; + } + + @Override + public boolean isPaintable() { + return true; + } + + @Override + public AbstractPipeModel getModel() { + return DuctPipeModel.INSTANCE; + } + + public static void registerDefaultStructures(Consumer register) { + register.accept(SMALL); + register.accept(NORMAL); + register.accept(LARGE); + register.accept(HUGE); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java index dfd9373870..61f53d6cb9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java @@ -3,7 +3,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; import com.gregtechceu.gtceu.api.item.tool.GTToolType; -import com.gregtechceu.gtceu.common.pipelike.handlers.OpticalNetHandler; +import com.gregtechceu.gtceu.common.pipelike.handlers.DuctNetHandler; import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; @@ -35,11 +35,11 @@ protected boolean allowsBlocking() { @Override protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { - return OpticalNetHandler.INSTANCE; + return DuctNetHandler.INSTANCE; } @Override protected @NotNull IPipeNetNodeHandler getHandler(@NotNull ItemStack stack) { - return OpticalNetHandler.INSTANCE; + return DuctNetHandler.INSTANCE; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetHandler.java deleted file mode 100644 index 611446b545..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetHandler.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.duct; - -import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.capability.IHazardParticleContainer; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.HazardProperty; -import com.gregtechceu.gtceu.api.data.medicalcondition.MedicalCondition; -import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; -import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardCleaner; -import com.gregtechceu.gtceu.common.blockentity.DuctPipeBlockEntity; -import com.gregtechceu.gtceu.common.capability.EnvironmentalHazardSavedData; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.server.level.ServerLevel; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Objects; - -public class DuctNetHandler implements IHazardParticleContainer { - - @Getter - private DuctPipeNet net; - private final DuctPipeBlockEntity pipe; - private final Direction facing; - - public DuctNetHandler(DuctPipeNet net, @NotNull DuctPipeBlockEntity pipe, @Nullable Direction facing) { - this.net = net; - this.pipe = pipe; - this.facing = facing; - } - - public void updateNetwork(DuctPipeNet net) { - this.net = net; - } - - @Nullable - private IHazardParticleContainer getInnerContainer() { - if (net == null || pipe.isInValid() || facing == null || pipe.isBlocked(facing)) { - return null; - } - - final List data = net.getNetData(pipe.getPipePos(), facing); - if (data == null) { - return null; - } - - return new IHazardParticleContainer() { - - @Override - public boolean inputsHazard(Direction side, MedicalCondition condition) { - return data.stream() - .map(path -> path.getHandler(net.getLevel())) - .filter(Objects::nonNull) - .anyMatch(handler -> handler.inputsHazard(side, condition)); - } - - @Override - public float changeHazard(MedicalCondition condition, float differenceAmount) { - float total = 0; - for (DuctRoutePath path : data) { - IHazardParticleContainer handler = path.getHandler(net.getLevel()); - if (handler == null && path.getTargetPipe().isConnected(path.getTargetFacing())) { - if (net.getLevel().getBlockEntity(path.getTargetPipePos() - .relative(path.getTargetFacing())) instanceof IMachineBlockEntity machineBE && - machineBE.getMetaMachine() instanceof IEnvironmentalHazardCleaner cleaner) { - cleaner.cleanHazard(condition, differenceAmount); - break; - } - - var savedData = EnvironmentalHazardSavedData.getOrCreate(net.getLevel()); - savedData.addZone(path.getTargetPipePos().relative(path.getTargetFacing()), - differenceAmount, true, HazardProperty.HazardTrigger.INHALATION, condition); - total += differenceAmount; - emitPollutionParticles(net.getLevel(), path.getTargetPipePos(), path.getTargetFacing()); - break; - } else if (handler == null) { - continue; - } - float change = handler.changeHazard(condition, differenceAmount); - differenceAmount -= change; - total += change; - if (differenceAmount <= 0) { - break; - } - } - return total; - } - - @Override - public float getHazardStored(MedicalCondition condition) { - float total = 0; - for (DuctRoutePath path : data) { - IHazardParticleContainer handler = path.getHandler(net.getLevel()); - if (handler != null) { - total += handler.getHazardStored(condition); - } - } - return total; - } - - @Override - public float getHazardCapacity(MedicalCondition condition) { - float total = 0; - for (DuctRoutePath path : data) { - IHazardParticleContainer handler = path.getHandler(net.getLevel()); - if (handler != null) { - total += handler.getHazardCapacity(condition); - } else if (path.getTargetPipe().isConnected(path.getTargetFacing())) { - total += Integer.MAX_VALUE; - break; - } - } - return total; - } - }; - } - - @Override - public boolean inputsHazard(Direction side, MedicalCondition condition) { - IHazardParticleContainer handler = getInnerContainer(); - if (handler == null) return false; - return handler.inputsHazard(side, condition); - } - - @Override - public boolean outputsHazard(Direction side, MedicalCondition condition) { - return true; - } - - @Override - public float changeHazard(MedicalCondition condition, float differenceAmount) { - IHazardParticleContainer handler = getInnerContainer(); - if (handler == null) return 0; - return handler.changeHazard(condition, differenceAmount); - } - - @Override - public float getHazardStored(MedicalCondition condition) { - IHazardParticleContainer handler = getInnerContainer(); - if (handler == null) return 0; - return handler.getHazardStored(condition); - } - - @Override - public float getHazardCapacity(MedicalCondition condition) { - IHazardParticleContainer handler = getInnerContainer(); - if (handler == null) return 0; - return handler.getHazardCapacity(condition); - } - - public static void emitPollutionParticles(ServerLevel level, BlockPos pos, Direction frontFacing) { - float xPos = frontFacing.getStepX() * 0.76F + pos.getX() + 0.25F; - float yPos = frontFacing.getStepY() * 0.76F + pos.getY() + 0.25F; - float zPos = frontFacing.getStepZ() * 0.76F + pos.getZ() + 0.25F; - - float ySpd = frontFacing.getStepY() * 0.1F + 0.2F + 0.1F * GTValues.RNG.nextFloat(); - float xSpd; - float zSpd; - - if (frontFacing.getStepY() == -1) { - float temp = GTValues.RNG.nextFloat() * 2 * (float) Math.PI; - xSpd = (float) Math.sin(temp) * 0.1F; - zSpd = (float) Math.cos(temp) * 0.1F; - } else { - xSpd = frontFacing.getStepX() * (0.1F + 0.2F * GTValues.RNG.nextFloat()); - zSpd = frontFacing.getStepZ() * (0.1F + 0.2F * GTValues.RNG.nextFloat()); - } - level.sendParticles(ParticleTypes.LARGE_SMOKE, - xPos + GTValues.RNG.nextFloat() * 0.5F, - yPos + GTValues.RNG.nextFloat() * 0.5F, - zPos + GTValues.RNG.nextFloat() * 0.5F, - 1, - xSpd, ySpd, zSpd, - 0.1); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetWalker.java deleted file mode 100644 index 46878c5012..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctNetWalker.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.duct; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.IHazardParticleContainer; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.pipenet.PipeNetWalker; -import com.gregtechceu.gtceu.common.blockentity.DuctPipeBlockEntity; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.util.LazyOptional; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; - -public class DuctNetWalker extends PipeNetWalker { - - public static List createNetData(DuctPipeNet pipeNet, BlockPos sourcePipe, Direction sourceFacing) { - if (!(pipeNet.getLevel().getBlockEntity(sourcePipe) instanceof DuctPipeBlockEntity)) { - return null; - } - try { - DuctNetWalker walker = new DuctNetWalker(pipeNet, sourcePipe, 1, new ArrayList<>(), null); - walker.sourcePipe = sourcePipe; - walker.facingToHandler = sourceFacing; - walker.traversePipeNet(); - return walker.inventories; - } catch (Exception e) { - GTCEu.LOGGER.error("error while create net data for DuctPipeNet", e); - } - return null; - } - - private DuctPipeProperties minProperties; - private final List inventories; - private BlockPos sourcePipe; - private Direction facingToHandler; - - protected DuctNetWalker(DuctPipeNet world, BlockPos sourcePipe, int distance, List inventories, - DuctPipeProperties properties) { - super(world, sourcePipe, distance); - this.inventories = inventories; - this.minProperties = properties; - } - - @NotNull - @Override - protected PipeNetWalker createSubWalker(DuctPipeNet pipeNet, - Direction facingToNextPos, - BlockPos nextPos, - int walkedBlocks) { - DuctNetWalker walker = new DuctNetWalker(pipeNet, nextPos, walkedBlocks, inventories, minProperties); - walker.facingToHandler = facingToHandler; - walker.sourcePipe = sourcePipe; - return walker; - } - - @Override - protected Class getBasePipeClass() { - return DuctPipeBlockEntity.class; - } - - @Override - protected void checkPipe(DuctPipeBlockEntity pipeTile, BlockPos pos) { - DuctPipeProperties pipeProperties = pipeTile.getNodeData(); - if (minProperties == null) { - minProperties = pipeProperties; - } else { - minProperties = new DuctPipeProperties( - Math.min(minProperties.getTransferRate(), pipeProperties.getTransferRate())); - } - } - - @Override - protected void checkNeighbour(DuctPipeBlockEntity pipeTile, BlockPos pipePos, Direction faceToNeighbour, - @Nullable BlockEntity neighbourTile) { - if ((pipePos.equals(sourcePipe) && faceToNeighbour == facingToHandler)) { - return; - } - if (neighbourTile != null) { - LazyOptional handler = neighbourTile.getCapability( - GTCapability.CAPABILITY_HAZARD_CONTAINER, - faceToNeighbour.getOpposite()); - if (handler.isPresent()) { - inventories.add(new DuctRoutePath(pipeTile, faceToNeighbour, getWalkedBlocks(), minProperties)); - } - } else if (pipeTile.isConnected(faceToNeighbour)) { - inventories.add(new DuctRoutePath(pipeTile, faceToNeighbour, getWalkedBlocks(), minProperties)); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeNet.java deleted file mode 100644 index 26d7247ed6..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeNet.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.duct; - -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; -import com.gregtechceu.gtceu.api.pipenet.Node; -import com.gregtechceu.gtceu.api.pipenet.PipeNet; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; - -import java.util.*; - -public class DuctPipeNet extends PipeNet { - - private final Map> NET_DATA = new HashMap<>(); - - public DuctPipeNet(LevelPipeNet> world) { - super(world); - } - - public List getNetData(BlockPos pipePos, Direction facing) { - List data = NET_DATA.get(pipePos); - if (data == null) { - data = DuctNetWalker.createNetData(this, pipePos, facing); - if (data == null) { - // walker failed, don't cache so it tries again on next insertion - return Collections.emptyList(); - } - NET_DATA.put(pipePos, data); - } - return data; - } - - @Override - public void onNeighbourUpdate(BlockPos fromPos) { - NET_DATA.clear(); - } - - @Override - public void onPipeConnectionsUpdate() { - NET_DATA.clear(); - } - - @Override - protected void transferNodeData(Map> transferredNodes, - PipeNet parentNet) { - super.transferNodeData(transferredNodes, parentNet); - NET_DATA.clear(); - ((DuctPipeNet) parentNet).NET_DATA.clear(); - } - - @Override - protected void writeNodeData(DuctPipeProperties nodeData, CompoundTag tagCompound) { - tagCompound.putFloat("Rate", nodeData.getTransferRate()); - } - - @Override - protected DuctPipeProperties readNodeData(CompoundTag tagCompound) { - return new DuctPipeProperties(tagCompound.getFloat("Rate")); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeProperties.java deleted file mode 100644 index 2812f1b832..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeProperties.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.duct; - -import lombok.Getter; -import lombok.Setter; - -import java.util.Objects; - -public class DuctPipeProperties { - - /** - * rate in stacks per sec - */ - @Getter - @Setter - private float transferRate; - - public DuctPipeProperties(float transferRate) { - this.transferRate = transferRate; - } - - /** - * Default property constructor. - */ - public DuctPipeProperties() { - this(0.25f); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DuctPipeProperties that = (DuctPipeProperties) o; - return Float.compare(that.transferRate, transferRate) == 0; - } - - @Override - public int hashCode() { - return Objects.hash(transferRate); - } - - @Override - public String toString() { - return "DuctPipeProperties{" + - "transferRate=" + transferRate + - '}'; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeType.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeType.java deleted file mode 100644 index 1323fa297f..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctPipeType.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.duct; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.pipenet.IPipeType; -import com.gregtechceu.gtceu.client.model.PipeModel; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.StringRepresentable; - -import lombok.Getter; - -import java.util.Locale; - -public enum DuctPipeType implements IPipeType, StringRepresentable { - - SMALL("small", 0.375f, 2f), - NORMAL("normal", 0.5f, 4f), - LARGE("large", 0.75f, 8f), - HUGE("huge", 0.875f, 16f), - ; - - public static final ResourceLocation TYPE_ID = GTCEu.id("duct"); - public static final DuctPipeType[] VALUES = values(); - - @Getter - public final String name; - @Getter - private final float thickness; - @Getter - private final float rateMultiplier; - - DuctPipeType(String name, float thickness, float rateMultiplier) { - this.name = name; - this.thickness = thickness; - this.rateMultiplier = rateMultiplier; - } - - @Override - public DuctPipeProperties modifyProperties(DuctPipeProperties baseProperties) { - return baseProperties; - } - - @Override - public boolean isPaintable() { - return true; - } - - @Override - public ResourceLocation type() { - return TYPE_ID; - } - - @Override - public String getSerializedName() { - return name().toLowerCase(Locale.ROOT); - } - - public PipeModel createPipeModel() { - return new PipeModel(thickness, () -> GTCEu.id("block/pipe/pipe_duct_side"), - () -> GTCEu.id("block/pipe/pipe_duct_in"), - null, null); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctRoutePath.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctRoutePath.java deleted file mode 100644 index 8488e7e589..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/DuctRoutePath.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.duct; - -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.IHazardParticleContainer; -import com.gregtechceu.gtceu.api.pipenet.IRoutePath; -import com.gregtechceu.gtceu.common.blockentity.DuctPipeBlockEntity; -import com.gregtechceu.gtceu.utils.FacingPos; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class DuctRoutePath implements IRoutePath { - - @Getter - private final DuctPipeBlockEntity targetPipe; - @NotNull - @Getter - private final Direction targetFacing; - @Getter - private final int distance; - @Getter - private final DuctPipeProperties properties; - - public DuctRoutePath(DuctPipeBlockEntity targetPipe, @NotNull Direction facing, int distance, - DuctPipeProperties properties) { - this.targetPipe = targetPipe; - this.targetFacing = facing; - this.distance = distance; - this.properties = properties; - } - - @Override - public @NotNull BlockPos getTargetPipePos() { - return targetPipe.getPipePos(); - } - - @Override - public @Nullable IHazardParticleContainer getHandler(Level world) { - return GTCapabilityHelper.getHazardContainer(world, getTargetPipePos().relative(targetFacing), - targetFacing.getOpposite()); - } - - public FacingPos toFacingPos() { - return new FacingPos(getTargetPipePos(), targetFacing); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/LevelDuctPipeNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/LevelDuctPipeNet.java deleted file mode 100644 index ab88dab06a..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/duct/LevelDuctPipeNet.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.gregtechceu.gtceu.common.pipelike.duct; - -import com.gregtechceu.gtceu.api.pipenet.LevelPipeNet; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; - -public class LevelDuctPipeNet extends LevelPipeNet { - - private static final String DATA_ID = "gtceu_duct_pipe_net"; - - public static LevelDuctPipeNet getOrCreate(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> new LevelDuctPipeNet(serverLevel, tag), - () -> new LevelDuctPipeNet(serverLevel), DATA_ID); - } - - public LevelDuctPipeNet(ServerLevel serverLevel) { - super(serverLevel); - } - - public LevelDuctPipeNet(ServerLevel serverLevel, CompoundTag tag) { - super(serverLevel, tag); - } - - @Override - protected DuctPipeNet createNetInstance() { - return new DuctPipeNet(this); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java new file mode 100644 index 0000000000..0d92e5a4dd --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java @@ -0,0 +1,59 @@ +package com.gregtechceu.gtceu.common.pipelike.handlers; + +import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctStructure; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; +import com.gregtechceu.gtceu.common.pipelike.net.optical.WorldOpticalNet; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public final class DuctNetHandler implements IPipeNetNodeHandler { + + public static final DuctNetHandler INSTANCE = new DuctNetHandler(); + + @Override + public @NotNull Collection getOrCreateFromNets(ServerLevel world, BlockPos pos, + IPipeStructure structure) { + if (structure instanceof DuctStructure) { + return Collections.singletonList(WorldOpticalNet.getWorldNet(world).getOrCreateNode(pos)); + } + return Collections.emptyList(); + } + + @Override + public @NotNull Collection getFromNets(ServerLevel world, BlockPos pos, + IPipeStructure structure) { + if (structure instanceof DuctStructure) { + WorldPipeNetNode node = WorldOpticalNet.getWorldNet(world).getNode(pos); + if (node != null) return Collections.singletonList(node); + } + return Collections.emptyList(); + } + + @Override + public void removeFromNets(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof DuctStructure) { + WorldOpticalNet net = WorldOpticalNet.getWorldNet(world); + WorldPipeNetNode node = net.getNode(pos); + if (node != null) net.removeNode(node); + } + } + + @Override + public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeStructure structure) { + tooltip.add(Component.translatable("block.gtceu.normal_optical_pipe.tooltip")); + } +} + diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java index 4ba40c6194..454f72c235 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/OpticalNetHandler.java @@ -21,7 +21,7 @@ public final class OpticalNetHandler implements IPipeNetNodeHandler { - public static final OpticalNetHandler INSTANCE = new OpticalNetHandler(); + public static final DuctNetHandler INSTANCE = new DuctNetHandler(); @Override public @NotNull Collection getOrCreateFromNets(ServerLevel world, BlockPos pos, diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java new file mode 100644 index 0000000000..f5bead17a3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java @@ -0,0 +1,177 @@ +package com.gregtechceu.gtceu.common.pipelike.net.duct; + +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.capability.IHazardParticleContainer; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.HazardProperty; +import com.gregtechceu.gtceu.api.data.medicalcondition.MedicalCondition; +import com.gregtechceu.gtceu.api.graphnet.pipenet.BasicWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; +import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardCleaner; +import com.gregtechceu.gtceu.common.capability.EnvironmentalHazardSavedData; +import com.lowdragmc.lowdraglib.Platform; +import lombok.Setter; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public class DuctCapabilityObject implements IPipeCapabilityObject, IHazardParticleContainer { + + private final WorldPipeNet net; + @Setter + private @Nullable PipeBlockEntity tile; + + public DuctCapabilityObject(@NotNull N net) { + this.net = net; + } + + private BasicWorldPipeNetPath.Provider getProvider() { + return (BasicWorldPipeNetPath.Provider) net; + } + + private Iterator getPaths() { + assert tile != null; + long tick = Platform.getMinecraftServer().getTickCount(); + return getProvider().getPaths(net.getNode(tile.getBlockPos()), IPredicateTestObject.INSTANCE, null, tick); + } + + @Override + public Capability[] getCapabilities() { + return WorldDuctNet.CAPABILITIES; + } + + @Override + public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { + if (capability == GTCapability.CAPABILITY_HAZARD_CONTAINER) { + return GTCapability.CAPABILITY_HAZARD_CONTAINER.orEmpty(capability, LazyOptional.of(() -> this)); + } + return null; + } + + @Override + public boolean inputsHazard(Direction side, MedicalCondition condition) { + for (Iterator it = getPaths(); it.hasNext();) { + BasicWorldPipeNetPath path = it.next(); + WorldPipeNetNode destination = path.getTargetNode(); + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + IHazardParticleContainer container = capability.getValue() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .orElse(null); + if (container != null && container.inputsHazard(side, condition)) { + return true; + } + } + } + return false; + } + + @Override + public float changeHazard(MedicalCondition condition, float differenceAmount) { + float total = 0; + for (Iterator it = getPaths(); it.hasNext();) { + BasicWorldPipeNetPath path = it.next(); + WorldPipeNetNode destination = path.getTargetNode(); + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + IHazardParticleContainer handler = capability.getValue() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .orElse(null); + if (handler == null) { + if (net.getLevel().getBlockEntity(path.getTargetNode().getEquivalencyData() + .relative(capability.getKey())) instanceof IMachineBlockEntity machineBE && + machineBE.getMetaMachine() instanceof IEnvironmentalHazardCleaner cleaner) { + cleaner.cleanHazard(condition, differenceAmount); + break; + } + + var savedData = EnvironmentalHazardSavedData.getOrCreate((ServerLevel) net.getLevel()); + savedData.addZone(path.getTargetNode().getEquivalencyData().relative(capability.getKey()), + differenceAmount, true, HazardProperty.HazardTrigger.INHALATION, condition); + total += differenceAmount; + emitPollutionParticles((ServerLevel) net.getLevel(), path.getTargetNode().getEquivalencyData(), capability.getKey()); + break; + } + float change = handler.changeHazard(condition, differenceAmount); + differenceAmount -= change; + total += change; + if (differenceAmount <= 0) { + break; + } + } + } + return total; + } + + @Override + public float getHazardStored(MedicalCondition condition) { + float total = 0; + for (Iterator it = getPaths(); it.hasNext();) { + BasicWorldPipeNetPath path = it.next(); + WorldPipeNetNode destination = path.getTargetNode(); + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + IHazardParticleContainer handler = capability.getValue() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .orElse(null); + if (handler != null) { + total += handler.getHazardStored(condition); + } + } + } + return total; + } + + @Override + public float getHazardCapacity(MedicalCondition condition) { + float total = 0; + for (Iterator it = getPaths(); it.hasNext();) { + BasicWorldPipeNetPath path = it.next(); + WorldPipeNetNode destination = path.getTargetNode(); + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + IHazardParticleContainer handler = capability.getValue() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .orElse(null); + if (handler != null) { + total += handler.getHazardCapacity(condition); + } + } + } + return total; + } + + public static void emitPollutionParticles(ServerLevel level, BlockPos pos, Direction frontFacing) { + float xPos = frontFacing.getStepX() * 0.76F + pos.getX() + 0.25F; + float yPos = frontFacing.getStepY() * 0.76F + pos.getY() + 0.25F; + float zPos = frontFacing.getStepZ() * 0.76F + pos.getZ() + 0.25F; + + float ySpd = frontFacing.getStepY() * 0.1F + 0.2F + 0.1F * GTValues.RNG.nextFloat(); + float xSpd; + float zSpd; + + if (frontFacing.getStepY() == -1) { + float temp = GTValues.RNG.nextFloat() * 2 * (float) Math.PI; + xSpd = (float) Math.sin(temp) * 0.1F; + zSpd = (float) Math.cos(temp) * 0.1F; + } else { + xSpd = frontFacing.getStepX() * (0.1F + 0.2F * GTValues.RNG.nextFloat()); + zSpd = frontFacing.getStepZ() * (0.1F + 0.2F * GTValues.RNG.nextFloat()); + } + level.sendParticles(ParticleTypes.LARGE_SMOKE, + xPos + GTValues.RNG.nextFloat() * 0.5F, + yPos + GTValues.RNG.nextFloat() * 0.5F, + zPos + GTValues.RNG.nextFloat() * 0.5F, + 1, + xSpd, ySpd, zSpd, + 0.1); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java new file mode 100644 index 0000000000..720caf4f1d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java @@ -0,0 +1,55 @@ +package com.gregtechceu.gtceu.common.pipelike.net.duct; + +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.graphnet.alg.DynamicWeightsShortestPathsAlgorithm; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.BasicWorldPipeNetPath; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.common.capabilities.Capability; +import org.jetbrains.annotations.Nullable; + +import java.util.Iterator; + +public class WorldDuctNet extends WorldPipeNet implements BasicWorldPipeNetPath.Provider { + + public static final Capability[] CAPABILITIES = new Capability[] { GTCapability.CAPABILITY_HAZARD_CONTAINER }; + + private static final String DATA_ID = "gtceu_world_laser_net"; + + public static WorldDuctNet getWorldNet(ServerLevel serverLevel) { + return serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldDuctNet net = new WorldDuctNet(); + net.load(tag); + return net; + }, WorldDuctNet::new, DATA_ID); + } + + public WorldDuctNet() { + super(false, DynamicWeightsShortestPathsAlgorithm::new); + } + + @Override + public Iterator getPaths(WorldPipeNetNode node, IPredicateTestObject testObject, + @Nullable SimulatorKey simulator, long queryTick) { + return backer.getPaths(node, 0, BasicWorldPipeNetPath.MAPPER, testObject, simulator, queryTick); + } + + @Override + public Capability[] getTargetCapabilities() { + return CAPABILITIES; + } + + @Override + public IPipeCapabilityObject[] getNewCapabilityObjects(WorldPipeNetNode node) { + return new IPipeCapabilityObject[] { new DuctCapabilityObject(this) }; + } + + @Override + public int getNetworkID() { + return 3; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java index 21240354bf..87637f9b8c 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java @@ -10,6 +10,7 @@ import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTItems; +import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctStructure; import com.gregtechceu.gtceu.common.pipelike.duct.DuctPipeType; import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; import com.gregtechceu.gtceu.utils.FormattingUtil; @@ -250,16 +251,16 @@ private static void processPipeNonuple(TagPrefix pipePrefix, Material material, private static void addDuctRecipes(Consumer provider, Material material, int outputAmount) { VanillaRecipeHelper.addShapedRecipe(provider, "small_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPES[DuctPipeType.SMALL.ordinal()].asStack(outputAmount * 2), "w", "X", "h", + GTBlocks.DUCT_PIPE_BLOCKS[DuctStructure.SMALL].asStack(outputAmount * 2), "w", "X", "h", 'X', new UnificationEntry(plate, material)); VanillaRecipeHelper.addShapedRecipe(provider, "medium_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPES[DuctPipeType.NORMAL.ordinal()].asStack(outputAmount), " X ", "wXh", " X ", + GTBlocks.DUCT_PIPE_BLOCKS[DuctPipeType.NORMAL.ordinal()].asStack(outputAmount), " X ", "wXh", " X ", 'X', new UnificationEntry(plate, material)); VanillaRecipeHelper.addShapedRecipe(provider, "large_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPES[DuctPipeType.LARGE.ordinal()].asStack(outputAmount), "XwX", "X X", "XhX", + GTBlocks.DUCT_PIPE_BLOCKS[DuctPipeType.LARGE.ordinal()].asStack(outputAmount), "XwX", "X X", "XhX", 'X', new UnificationEntry(plate, material)); VanillaRecipeHelper.addShapedRecipe(provider, "huge_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPES[DuctPipeType.HUGE.ordinal()].asStack(outputAmount), "XwX", "X X", "XhX", + GTBlocks.DUCT_PIPE_BLOCKS[DuctPipeType.HUGE.ordinal()].asStack(outputAmount), "XwX", "X X", "XhX", 'X', new UnificationEntry(plateDouble, material)); } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java index f1954da828..7fdec9b942 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.integration.jade.provider; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MetaMachine; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java index 0ed59e7c60..49d131dda6 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.integration.top.provider; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.blockentity.PipeBlockEntity; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import net.minecraft.network.chat.Component; From e41c4a85ecf60cf6b5c16304673e8cdf6f259c2a Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Fri, 23 Aug 2024 15:08:17 +0300 Subject: [PATCH 09/70] fluid pipe properties --- .../api/capability/IPropertyFluidFilter.java | 26 +- .../api/data/chemical/material/Material.java | 57 ++-- .../properties/FluidPipeProperties.java | 137 --------- .../properties/ItemPipeProperties.java | 96 ------- .../properties/PipeNetProperties.java | 6 +- .../material/properties/PropertyKey.java | 4 - .../gtceu/api/fluids/FluidBuilder.java | 21 +- .../gtceu/api/fluids/PropertyFluidFilter.java | 10 +- .../predicate/test/FluidTestObject.java | 2 +- .../renderer/block/PipeBlockRenderer.java | 131 --------- .../blockentity/DuctPipeBlockEntity.java | 148 ---------- .../gtceu/common/cover/PumpCover.java | 262 ++++++++++++++---- .../gtceu/common/data/GTMachines.java | 6 +- .../machine/electric/AirScrubberMachine.java | 4 +- .../properties/MaterialEnergyProperties.java | 247 +++++++++++++++++ .../properties/MaterialFluidProperties.java | 228 +++++++++++++++ .../properties/MaterialItemProperties.java | 120 ++++++++ .../recipe/generated/PipeRecipeHandler.java | 60 ++-- 18 files changed, 916 insertions(+), 649 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java index f8487a52a9..2a56a919f4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java @@ -26,7 +26,7 @@ public interface IPropertyFluidFilter extends Predicate { @Override default boolean test(@NotNull FluidStack stack) { Fluid fluid = stack.getFluid(); - if (FluidHelper.getTemperature(stack) < CRYOGENIC_FLUID_THRESHOLD && !isCryoProof()) return false; + if (FluidHelper.getTemperature(stack) < getMinFluidTemperature()) return false; if (fluid instanceof IAttributedFluid attributedFluid) { FluidState state = attributedFluid.getState(); @@ -85,15 +85,17 @@ default boolean test(@NotNull FluidStack stack) { */ default void appendTooltips(@NotNull List tooltip, boolean showToolsInfo, boolean showTemperatureInfo) { if (GTUtil.isShiftDown()) { - if (showTemperatureInfo) + if (showTemperatureInfo) { tooltip.add(Component.translatable("gtceu.fluid_pipe.max_temperature", FormattingUtil.formatNumbers(getMaxFluidTemperature()))); + tooltip.add(Component.translatable("gtceu.fluid_pipe.min_temperature", + FormattingUtil.formatNumbers(getMinFluidTemperature()))); + } if (isGasProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.gas_proof")); else tooltip.add(Component.translatable("gtceu.fluid_pipe.not_gas_proof")); if (isPlasmaProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.plasma_proof")); - if (isCryoProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.cryo_proof")); getContainedAttributes().forEach(a -> a.appendContainerTooltips(tooltip::add)); - } else if (isGasProof() || isCryoProof() || isPlasmaProof() || !getContainedAttributes().isEmpty()) { + } else if (isGasProof() || isPlasmaProof() || !getContainedAttributes().isEmpty()) { if (showToolsInfo) { tooltip.add(Component.translatable("gtceu.tooltip.tool_fluid_hold_shift")); } else { @@ -112,17 +114,23 @@ default void appendTooltips(@NotNull List tooltip, boolean showToolsI /** * This is always checked, regardless of the contained fluid being a {@link IAttributedFluid} or not * - * @return whether this filter allows gases + * @return the minimum allowed temperature for a fluid */ - boolean isGasProof(); + int getMinFluidTemperature(); /** - * @return whether this filter allows cryogenic fluids + * This is always checked, regardless of the contained fluid being a {@link IAttributedFluid} or not + * + * @return whether this filter allows gases */ - boolean isCryoProof(); + default boolean isGasProof() { + return canContain(FluidState.GAS); + } /** * @return whether this filter allows plasmas */ - boolean isPlasmaProof(); + default boolean isPlasmaProof() { + return canContain(FluidState.PLASMA); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java index b14c0797ff..8fcb59d73c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java @@ -11,12 +11,16 @@ import com.gregtechceu.gtceu.api.data.tag.TagUtil; import com.gregtechceu.gtceu.api.fluids.FluidBuilder; import com.gregtechceu.gtceu.api.fluids.FluidState; +import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttributes; import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKey; import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKeys; import com.gregtechceu.gtceu.api.item.tool.MaterialToolTier; import com.gregtechceu.gtceu.api.registry.registrate.BuilderBase; import com.gregtechceu.gtceu.common.data.GTMaterials; import com.gregtechceu.gtceu.common.data.GTMedicalConditions; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialFluidProperties; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialItemProperties; import com.gregtechceu.gtceu.integration.kjs.helpers.MaterialStackWrapper; import com.gregtechceu.gtceu.utils.FormattingUtil; @@ -1165,38 +1169,59 @@ public Builder addOreByproducts(Material... byproducts) { return this; } - public Builder cableProperties(long voltage, int amperage, int loss) { - cableProperties((int) voltage, amperage, loss, false); + private PipeNetProperties getOrCreatePipeNetProperties() { + if (properties.hasProperty(PropertyKey.PIPENET_PROPERTIES)) { + return properties.getProperty(PropertyKey.PIPENET_PROPERTIES); + } else { + PipeNetProperties prop = new PipeNetProperties(); + properties.setProperty(PropertyKey.PIPENET_PROPERTIES, prop); + return prop; + } + } + + public Builder cableProperties(long voltage, long amperage, long loss) { + getOrCreatePipeNetProperties().setProperty(MaterialEnergyProperties.create(voltage, amperage, loss)); return this; } - public Builder cableProperties(long voltage, int amperage, int loss, boolean isSuperCon) { - properties.ensureSet(PropertyKey.DUST); - properties.setProperty(PropertyKey.WIRE, new WireProperties((int) voltage, amperage, loss, isSuperCon)); + public Builder cableProperties(long voltage, long amperage, long loss, int superconductorTemperature) { + getOrCreatePipeNetProperties() + .setProperty(MaterialEnergyProperties.create(voltage, amperage, loss, superconductorTemperature)); return this; } - public Builder cableProperties(long voltage, int amperage, int loss, boolean isSuperCon, - int criticalTemperature) { - properties.ensureSet(PropertyKey.DUST); - properties.setProperty(PropertyKey.WIRE, - new WireProperties((int) voltage, amperage, loss, isSuperCon, criticalTemperature)); + public Builder fluidPipeProperties(int maxTemp, long throughput, boolean gasProof) { + getOrCreatePipeNetProperties().setProperty( + MaterialFluidProperties.createMax(throughput, maxTemp).setContain(FluidState.GAS, gasProof)); return this; } - public Builder fluidPipeProperties(int maxTemp, int throughput, boolean gasProof) { - return fluidPipeProperties(maxTemp, throughput, gasProof, false, false, false); + public Builder fluidPipeProperties(int maxTemp, long throughput, boolean gasProof, float priority) { + getOrCreatePipeNetProperties().setProperty(MaterialFluidProperties.createMax(throughput, maxTemp, priority) + .setContain(FluidState.GAS, gasProof)); + return this; } public Builder fluidPipeProperties(int maxTemp, int throughput, boolean gasProof, boolean acidProof, - boolean cryoProof, boolean plasmaProof) { - properties.setProperty(PropertyKey.FLUID_PIPE, - new FluidPipeProperties(maxTemp, throughput, gasProof, acidProof, cryoProof, plasmaProof)); + boolean plasmaProof) { + getOrCreatePipeNetProperties().setProperty( + MaterialFluidProperties.createMax(throughput, maxTemp).setContain(FluidState.GAS, gasProof) + .setContain(FluidAttributes.ACID, acidProof).setContain(FluidState.PLASMA, plasmaProof)); + return this; + } + + public Builder fluidPipeProperties(int maxTemp, int minTemp, int throughput, boolean gasProof, + boolean acidProof, + boolean plasmaProof) { + getOrCreatePipeNetProperties().setProperty(new MaterialFluidProperties(throughput, maxTemp, minTemp) + .setContain(FluidState.GAS, gasProof).setContain(FluidAttributes.ACID, acidProof) + .setContain(FluidState.PLASMA, plasmaProof)); return this; } public Builder itemPipeProperties(int priority, float stacksPerSec) { - properties.setProperty(PropertyKey.ITEM_PIPE, new ItemPipeProperties(priority, stacksPerSec)); + getOrCreatePipeNetProperties() + .setProperty(new MaterialItemProperties((long) (stacksPerSec * 16), priority)); return this; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java deleted file mode 100644 index d21cf1944d..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/FluidPipeProperties.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.gregtechceu.gtceu.api.data.chemical.material.properties; - -import com.gregtechceu.gtceu.api.capability.IPropertyFluidFilter; -import com.gregtechceu.gtceu.api.fluids.FluidState; -import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; -import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttributes; - -import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; - -import it.unimi.dsi.fastutil.objects.Object2BooleanMap; -import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; -import lombok.Getter; -import lombok.Setter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.UnmodifiableView; - -import java.util.Collection; -import java.util.Objects; - -public class FluidPipeProperties implements IMaterialProperty, IPropertyFluidFilter { - - /** - * The maximum number of channels any fluid pipe can have - */ - public static final int MAX_PIPE_CHANNELS = 9; - - @Getter - @Setter - private long throughput; - @Getter - @Setter - private int channels; - @Getter - @Setter - private int maxFluidTemperature; - @Getter - @Setter - private boolean gasProof; - @Getter - @Setter - private boolean cryoProof; - @Getter - @Setter - private boolean plasmaProof; - - private final Object2BooleanMap containmentPredicate = new Object2BooleanOpenHashMap<>(); - - public FluidPipeProperties(int maxFluidTemperature, long throughput, boolean gasProof, boolean acidProof, - boolean cryoProof, boolean plasmaProof, int channels) { - this.maxFluidTemperature = maxFluidTemperature; - this.throughput = throughput; - this.gasProof = gasProof; - if (acidProof) setCanContain(FluidAttributes.ACID, true); - this.cryoProof = cryoProof; - this.plasmaProof = plasmaProof; - this.channels = channels; - } - - /** - * Default property constructor. - */ - public FluidPipeProperties(int maxFluidTemperature, long throughput, boolean gasProof, boolean acidProof, - boolean cryoProof, boolean plasmaProof) { - this(maxFluidTemperature, throughput, gasProof, acidProof, cryoProof, plasmaProof, 1); - } - - @Override - public void verifyProperty(MaterialProperties properties) { - if (!properties.hasProperty(PropertyKey.WOOD)) { - properties.ensureSet(PropertyKey.INGOT, true); - } - - if (properties.hasProperty(PropertyKey.ITEM_PIPE)) { - throw new IllegalStateException( - "Material " + properties.getMaterial() + - " has both Fluid and Item Pipe Property, which is not allowed!"); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof FluidPipeProperties that)) return false; - return maxFluidTemperature == that.maxFluidTemperature && - throughput == that.throughput && gasProof == that.gasProof && channels == that.channels; - } - - @Override - public int hashCode() { - return Objects.hash(maxFluidTemperature, throughput, gasProof, channels); - } - - @Override - public String toString() { - return "FluidPipeProperties{" + - "maxFluidTemperature=" + maxFluidTemperature + - ", throughput=" + throughput + - ", gasProof=" + gasProof + - ", acidProof=" + isAcidProof() + - ", cryoProof=" + cryoProof + - ", plasmaProof=" + plasmaProof + - ", channels=" + channels + - '}'; - } - - public long getPlatformThroughput() { - return getThroughput() * FluidHelper.getBucket() / 1000; - } - - @Override - public boolean canContain(@NotNull FluidState state) { - return switch (state) { - case LIQUID -> true; - case GAS -> gasProof; - case PLASMA -> plasmaProof; - }; - } - - public boolean isAcidProof() { - return canContain(FluidAttributes.ACID); - } - - @Override - public boolean canContain(@NotNull FluidAttribute attribute) { - return containmentPredicate.getBoolean(attribute); - } - - @Override - public void setCanContain(@NotNull FluidAttribute attribute, boolean canContain) { - containmentPredicate.put(attribute, canContain); - } - - @Override - public @NotNull @UnmodifiableView Collection<@NotNull FluidAttribute> getContainedAttributes() { - return containmentPredicate.keySet(); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java deleted file mode 100644 index acfb7a57d1..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ItemPipeProperties.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.gregtechceu.gtceu.api.data.chemical.material.properties; - -import java.util.Objects; - -public class ItemPipeProperties implements IMaterialProperty { - - /** - * Items will try to take the path with the lowest priority - */ - private int priority; - - /** - * rate in stacks per sec - */ - private float transferRate; - - public ItemPipeProperties(int priority, float transferRate) { - this.priority = priority; - this.transferRate = transferRate; - } - - /** - * Default property constructor. - */ - public ItemPipeProperties() { - this(1, 0.25f); - } - - /** - * Retrieves the priority of the item pipe - * - * @return The item pipe priority - */ - public int getPriority() { - return priority; - } - - /** - * Sets the Priority of the item pipe - */ - public void setPriority(int priority) { - this.priority = priority; - } - - /** - * Retrieve the transfer rate of the item pipe - * - * @return The transfer rate of the item pipe - */ - public float getTransferRate() { - return transferRate; - } - - /** - * Sets the transfer rate of the item pipe - * - * @param transferRate The transfer rate - */ - public void setTransferRate(float transferRate) { - this.transferRate = transferRate; - } - - @Override - public void verifyProperty(MaterialProperties properties) { - if (!properties.hasProperty(PropertyKey.WOOD)) { - properties.ensureSet(PropertyKey.INGOT, true); - } - - if (properties.hasProperty(PropertyKey.FLUID_PIPE)) { - throw new IllegalStateException( - "Material " + properties.getMaterial() + - " has both Fluid and Item Pipe Property, which is not allowed!"); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ItemPipeProperties that = (ItemPipeProperties) o; - return priority == that.priority && Float.compare(that.transferRate, transferRate) == 0; - } - - @Override - public int hashCode() { - return Objects.hash(priority, transferRate); - } - - @Override - public String toString() { - return "ItemPipeProperties{" + - "priority=" + priority + - ", transferRate=" + transferRate + - '}'; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java index 85c8a36fcd..d39c0707ae 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java @@ -117,14 +117,14 @@ public int compare(IPipeNetMaterialProperty o1, IPipeNetMaterialProperty o2) { public interface IPipeNetMaterialProperty extends IMaterialProperty { @Nullable - WorldPipeNetNode getOrCreateFromNet(LevelAccessor world, BlockPos pos, IPipeStructure structure); + WorldPipeNetNode getOrCreateFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure); @Nullable - WorldPipeNetNode getFromNet(LevelAccessor world, BlockPos pos, IPipeStructure structure); + WorldPipeNetNode getFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure); void mutateData(NetLogicData data, IPipeStructure structure); - void removeFromNet(LevelAccessor world, BlockPos pos, IPipeStructure structure); + void removeFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure); boolean generatesStructure(IPipeStructure structure); diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java index 4771282201..da49123579 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java @@ -8,14 +8,10 @@ public class PropertyKey { public static final PropertyKey DUST = new PropertyKey<>("dust", DustProperty.class); public static final PropertyKey PIPENET_PROPERTIES = new PropertyKey<>("net_pipe", PipeNetProperties.class); - public static final PropertyKey FLUID_PIPE = new PropertyKey<>("fluid_pipe", - FluidPipeProperties.class); public static final PropertyKey FLUID = new PropertyKey<>("fluid", FluidProperty.class); public static final PropertyKey GEM = new PropertyKey<>("gem", GemProperty.class); public static final PropertyKey INGOT = new PropertyKey<>("ingot", IngotProperty.class); public static final PropertyKey POLYMER = new PropertyKey<>("polymer", PolymerProperty.class); - public static final PropertyKey ITEM_PIPE = new PropertyKey<>("item_pipe", - ItemPipeProperties.class); public static final PropertyKey ORE = new PropertyKey<>("ore", OreProperty.class); public static final PropertyKey TOOL = new PropertyKey<>("tool", ToolProperty.class); public static final PropertyKey ROTOR = new PropertyKey<>("rotor", RotorProperty.class); diff --git a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java index eeb3fcb0c0..4082afb2f6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java @@ -313,7 +313,20 @@ private void determineTextures(@Nullable Material material, @Nullable FluidStora } private void determineTemperature(@Nullable Material material) { - if (temperature != INFER_TEMPERATURE) return; + this.temperature = getDeterminedTemperature(material, null); + } + + public int getDeterminedTemperature(@Nullable Material material, @Nullable FluidStorageKey key) { + FluidState state = this.state; + if (state == null) { + if (key != null && key.getDefaultFluidState() != null) { + state = key.getDefaultFluidState(); + } else { + state = FluidState.LIQUID; // default fallback + } + } + int temperature = this.temperature; + if (temperature != INFER_TEMPERATURE) return temperature; if (material == null) { temperature = ROOM_TEMPERATURE; } else { @@ -328,9 +341,8 @@ private void determineTemperature(@Nullable Material material) { } case GAS -> ROOM_TEMPERATURE; case PLASMA -> { - if (material.hasFluid() && material.getFluidBuilder() != null && - material.getFluidBuilder() != material.getFluidBuilder(FluidStorageKeys.PLASMA)) { - yield BASE_PLASMA_TEMPERATURE + material.getFluidBuilder().temperature; + if (material.hasFluid() && material.getFluid() != null) { + yield BASE_PLASMA_TEMPERATURE + material.getFluid().getFluidType().getTemperature(); } yield BASE_PLASMA_TEMPERATURE; } @@ -343,6 +355,7 @@ private void determineTemperature(@Nullable Material material) { }; } } + return temperature; } private void determineColor(@Nullable Material material) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/fluids/PropertyFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/fluids/PropertyFluidFilter.java index 5373cba8c1..4ee41ecbad 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/fluids/PropertyFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/fluids/PropertyFluidFilter.java @@ -19,21 +19,21 @@ public class PropertyFluidFilter implements IPropertyFluidFilter { @Getter private final int maxFluidTemperature; @Getter - private final boolean gasProof; + private final int minFluidTemperature; @Getter - private final boolean cryoProof; + private final boolean gasProof; @Getter private final boolean plasmaProof; public PropertyFluidFilter(int maxFluidTemperature, + int minFluidTemperature, boolean gasProof, boolean acidProof, - boolean cryoProof, boolean plasmaProof) { this.maxFluidTemperature = maxFluidTemperature; + this.minFluidTemperature = minFluidTemperature; this.gasProof = gasProof; if (acidProof) setCanContain(FluidAttributes.ACID, true); - this.cryoProof = cryoProof; this.plasmaProof = plasmaProof; } @@ -65,8 +65,8 @@ public void setCanContain(@NotNull FluidAttribute attribute, boolean canContain) public String toString() { return "SimplePropertyFluidFilter{" + "maxFluidTemperature=" + maxFluidTemperature + + "minFluidTemperature=" + minFluidTemperature + ", gasProof=" + gasProof + - ", cryoProof=" + cryoProof + ", plasmaProof=" + plasmaProof + ", containmentPredicate=" + containmentPredicate + '}'; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java index 0561b9c9b4..36c846ee2e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java @@ -32,7 +32,7 @@ public FluidTestObject(@NotNull FluidStack stack) { } @Contract("_ -> new") - public @NotNull FluidStack recombine(int amount) { + public @NotNull FluidStack recombine(long amount) { return FluidStack.create(fluid, amount, tag); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java deleted file mode 100644 index 0bc22005f7..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/block/PipeBlockRenderer.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.block; - -import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; -import com.gregtechceu.gtceu.client.renderer.cover.ICoverableRenderer; -import com.gregtechceu.gtceu.common.data.GTBlocks; - -import com.lowdragmc.lowdraglib.LDLib; -import com.lowdragmc.lowdraglib.client.model.ModelFactory; -import com.lowdragmc.lowdraglib.client.renderer.IRenderer; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.*; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import com.mojang.blaze3d.vertex.PoseStack; -import lombok.Getter; -import org.jetbrains.annotations.NotNull; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.function.Consumer; - -/** - * @author KilaBash - * @date 2023/3/1 - * @implNote PipeBlockRenderer - */ -public class PipeBlockRenderer implements IRenderer, ICoverableRenderer { - - @Getter - PipeModel pipeModel; - - public PipeBlockRenderer(PipeModel pipeModel) { - this.pipeModel = pipeModel; - if (LDLib.isClient()) { - registerEvent(); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void renderItem(ItemStack stack, - ItemDisplayContext transformType, - boolean leftHand, PoseStack matrixStack, - MultiBufferSource buffer, int combinedLight, - int combinedOverlay, BakedModel model) { - pipeModel.renderItem(stack, transformType, leftHand, matrixStack, buffer, combinedLight, combinedOverlay, - model); - } - - @Override - public boolean useAO() { - return true; - } - - @Override - @OnlyIn(Dist.CLIENT) - public boolean useBlockLight(ItemStack stack) { - return true; - } - - @Override - @OnlyIn(Dist.CLIENT) - public List renderModel(BlockAndTintGetter level, BlockPos pos, BlockState state, Direction side, - RandomSource rand) { - if (level == null) { - return pipeModel.bakeQuads(side, PipeModel.ITEM_CONNECTIONS, 0); - } else if (level.getBlockEntity(pos) instanceof IPipeNode pipeNode) { - var quads = new LinkedList<>( - pipeModel.bakeQuads(side, pipeNode.getVisualConnections(), pipeNode.getBlockedConnections())); - var modelState = ModelFactory.getRotation(pipeNode.getCoverContainer().getFrontFacing()); - var modelFacing = side == null ? null : - ModelFactory.modelFacing(side, pipeNode.getCoverContainer().getFrontFacing()); - ICoverableRenderer.super.renderCovers(quads, side, rand, pipeNode.getCoverContainer(), modelFacing, pos, - level, modelState); - if (pipeNode.getFrameMaterial() != null) { - ResourceLocation rl = MaterialIconType.frameGt - .getBlockTexturePath(pipeNode.getFrameMaterial().getMaterialIconSet(), true); - BlockState blockState = GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, pipeNode.getFrameMaterial()) - .getDefaultState(); - var frameModel = Minecraft.getInstance().getBlockRenderer().getBlockModel(blockState); - for (Direction face : Direction.values()) { - if ((pipeNode.getConnections() & 1 << (12 + face.get3DDataValue())) == 0) { - var frameTintedFaces = frameModel.getQuads(state, face, rand) - .stream() - .map(quad -> new BakedQuad(quad.getVertices(), - quad.getTintIndex() + (quad.isTinted() ? 3 : 0), - quad.getDirection(), - quad.getSprite(), - quad.isShade(), - quad.hasAmbientOcclusion())) - .toList(); - quads.addAll(frameTintedFaces); - } - } - } - return quads; - } - return Collections.emptyList(); - } - - @NotNull - @Override - @OnlyIn(Dist.CLIENT) - public TextureAtlasSprite getParticleTexture() { - return pipeModel.getParticleTexture(); - } - - @Override - @OnlyIn(Dist.CLIENT) - public void onPrepareTextureAtlas(ResourceLocation atlasName, Consumer register) { - if (atlasName.equals(TextureAtlas.LOCATION_BLOCKS)) { - pipeModel.registerTextureAtlas(register); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java deleted file mode 100644 index 0905ec738c..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/DuctPipeBlockEntity.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.gregtechceu.gtceu.common.blockentity; - -import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; -import com.gregtechceu.gtceu.api.capability.IHazardParticleContainer; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; -import com.gregtechceu.gtceu.api.data.medicalcondition.MedicalCondition; -import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; -import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardCleaner; -import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardEmitter; -import com.gregtechceu.gtceu.common.pipelike.duct.*; -import com.gregtechceu.gtceu.utils.GTUtil; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.lang.ref.WeakReference; -import java.util.EnumMap; - -public class DuctPipeBlockEntity extends PipeBlockEntity { - - @Getter - protected final EnumMap handlers = new EnumMap<>(Direction.class); - // the DuctNetHandler can only be created on the server, so we have an empty placeholder for the client - public final IHazardParticleContainer clientCapability = new DefaultDuctContainer(); - private WeakReference currentPipeNet = new WeakReference<>(null); - @Getter - protected DuctNetHandler defaultHandler; - - protected DuctPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - } - - public static DuctPipeBlockEntity create(BlockEntityType type, BlockPos pos, BlockState blockState) { - return new DuctPipeBlockEntity(type, pos, blockState); - } - - public static void onBlockEntityRegister(BlockEntityType ductBlockEntityBlockEntityType) {} - - @Override - public @NotNull LazyOptional getCapability(@NotNull Capability cap, @Nullable Direction side) { - if (cap == GTCapability.CAPABILITY_HAZARD_CONTAINER) { - if (getLevel().isClientSide()) - return GTCapability.CAPABILITY_HAZARD_CONTAINER.orEmpty(cap, LazyOptional.of(() -> clientCapability)); - - if (handlers.isEmpty()) { - initHandlers(); - } - checkNetwork(); - return GTCapability.CAPABILITY_HAZARD_CONTAINER.orEmpty(cap, - LazyOptional.of(() -> handlers.getOrDefault(side, defaultHandler))); - } else if (cap == GTCapability.CAPABILITY_COVERABLE) { - return GTCapability.CAPABILITY_COVERABLE.orEmpty(cap, LazyOptional.of(this::getCoverContainer)); - } else if (cap == GTCapability.CAPABILITY_TOOLABLE) { - return GTCapability.CAPABILITY_TOOLABLE.orEmpty(cap, LazyOptional.of(() -> this)); - } - return super.getCapability(cap, side); - } - - @Override - public boolean canHaveBlockedFaces() { - return false; - } - - public void initHandlers() { - DuctPipeNet net = getDuctPipeNet(); - if (net == null) return; - for (Direction facing : GTUtil.DIRECTIONS) { - handlers.put(facing, new DuctNetHandler(net, this, facing)); - } - defaultHandler = new DuctNetHandler(net, this, null); - } - - public void checkNetwork() { - if (defaultHandler != null) { - DuctPipeNet current = getDuctPipeNet(); - if (defaultHandler.getNet() != current) { - defaultHandler.updateNetwork(current); - for (DuctNetHandler handler : handlers.values()) { - handler.updateNetwork(current); - } - } - } - } - - public DuctPipeNet getDuctPipeNet() { - if (level == null || level.isClientSide) { - return null; - } - DuctPipeNet currentPipeNet = this.currentPipeNet.get(); - if (currentPipeNet != null && currentPipeNet.isValid() && currentPipeNet.containsNode(getPipePos())) { - return currentPipeNet; - } - LevelDuctPipeNet worldNet = (LevelDuctPipeNet) getPipeBlock().getWorldPipeNet((ServerLevel) getPipeLevel()); - currentPipeNet = worldNet.getNetFromPos(getPipePos()); - if (currentPipeNet != null) { - this.currentPipeNet = new WeakReference<>(currentPipeNet); - } - return currentPipeNet; - } - - @Override - public boolean canAttachTo(Direction side) { - if (level != null) { - if (level.getBlockEntity(getBlockPos().relative(side)) instanceof DuctPipeBlockEntity) { - return false; - } - BlockPos relative = getBlockPos().relative(side); - return GTCapabilityHelper.getHazardContainer(level, relative, side.getOpposite()) != - null || - (level.getBlockEntity(relative) instanceof IMachineBlockEntity machineBlockEntity && - (machineBlockEntity.getMetaMachine() instanceof IEnvironmentalHazardCleaner || - machineBlockEntity.getMetaMachine() instanceof IEnvironmentalHazardEmitter)); - } - return false; - } - - private static class DefaultDuctContainer implements IHazardParticleContainer { - - @Override - public boolean inputsHazard(Direction side, MedicalCondition condition) { - return false; - } - - @Override - public float changeHazard(MedicalCondition condition, float differenceAmount) { - return 0; - } - - @Override - public float getHazardStored(MedicalCondition condition) { - return 0; - } - - @Override - public float getHazardCapacity(MedicalCondition condition) { - return 0; - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java index c6083c6347..57bb622f69 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.capability.IControllable; import com.gregtechceu.gtceu.api.capability.ICoverable; @@ -10,15 +11,26 @@ import com.gregtechceu.gtceu.api.cover.filter.FilterHandler; import com.gregtechceu.gtceu.api.cover.filter.FilterHandlers; import com.gregtechceu.gtceu.api.cover.filter.FluidFilter; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.traverse.TraverseHelpers; import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; import com.gregtechceu.gtceu.api.gui.widget.LongInputWidget; import com.gregtechceu.gtceu.api.gui.widget.NumberInputWidget; import com.gregtechceu.gtceu.api.machine.ConditionalSubscriptionHandler; import com.gregtechceu.gtceu.api.transfer.fluid.FluidTransferDelegate; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.BucketMode; +import com.gregtechceu.gtceu.common.cover.data.DistributionMode; import com.gregtechceu.gtceu.common.cover.data.ManualIOMode; -import com.gregtechceu.gtceu.utils.FluidStackHashStrategy; - +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidEQTraverseData; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidRRTraverseData; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidTraverseData; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.IFluidTraverseGuideProvider; import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; @@ -26,29 +38,34 @@ import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; import com.lowdragmc.lowdraglib.utils.LocalizationUtils; - +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import lombok.Getter; +import lombok.Setter; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; - -import it.unimi.dsi.fastutil.objects.Object2LongOpenCustomHashMap; -import lombok.Getter; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.fluids.capability.IFluidHandler; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import java.util.Arrays; import java.util.List; -import java.util.Map; - -import javax.annotation.ParametersAreNonnullByDefault; +import java.util.function.BiConsumer; +import java.util.function.LongUnaryOperator; /** * @author KilaBash @@ -79,6 +96,11 @@ public class PumpCover extends CoverBehavior implements IUICover, IControllable @Persisted @DescSynced @Getter + @Setter + protected DistributionMode distributionMode = DistributionMode.INSERT_FIRST; + @Persisted + @DescSynced + @Getter protected BucketMode bucketMode = BucketMode.MILLI_BUCKET; @Persisted @DescSynced @@ -97,6 +119,10 @@ public class PumpCover extends CoverBehavior implements IUICover, IControllable protected final ConditionalSubscriptionHandler subscriptionHandler; private NumberInputWidget transferRateWidget; + protected final Object2ObjectLinkedOpenHashMap> roundRobinCache = new Object2ObjectLinkedOpenHashMap<>(); + + protected @Nullable CoverRenderer rendererInverted; + /* * Transfer rate variables are treated as liters/millibuckets per tick. * The actual conversion to the platform's values happens inside tick handling. @@ -140,8 +166,8 @@ public ManagedFieldHolder getFieldHolder() { } @Override - public boolean canAttach() { - return getOwnFluidTransfer() != null; + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(ForgeCapabilities.FLUID_HANDLER, side).isPresent(); } public void setIo(IO io) { @@ -176,6 +202,28 @@ public void onNeighborChanged(Block block, BlockPos fromPos, boolean isMoving) { subscriptionHandler.updateSubscription(); } + @Override + public @NotNull CoverRenderer getRenderer() { + if (io == IO.OUT) { + if (renderer == null) renderer = buildRenderer(); + return renderer; + } else { + if (rendererInverted == null) rendererInverted = buildRendererInverted(); + return rendererInverted; + } + } + + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_pump"), + GTCEu.id("block/cover/overlay_pump_emissive")).build(); + } + + protected CoverRenderer buildRendererInverted() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_pump_inverted"), + GTCEu.id("block/cover/overlay_pump_inverted_emissive")).build(); + } + @Override public void setWorkingEnabled(boolean isWorkingAllowed) { if (this.isWorkingEnabled != isWorkingAllowed) { @@ -218,76 +266,172 @@ protected void setManualIOMode(ManualIOMode manualIOMode) { protected void update() { long timer = coverHolder.getOffsetTimer(); - if (timer % 5 != 0) - return; - - if (milliBucketsLeftToTransferLastSecond > 0) { - long platformTransferredFluid = doTransferFluids(milliBucketsLeftToTransferLastSecond * MILLIBUCKET_SIZE); - this.milliBucketsLeftToTransferLastSecond -= platformTransferredFluid / MILLIBUCKET_SIZE; + if (isWorkingEnabled && getFluidsLeftToTransfer() > 0) { + BlockEntity tileEntity = coverHolder.getNeighbor(attachedSide); + IFluidHandler fluidHandlerCap = tileEntity == null ? null : tileEntity + .getCapability(ForgeCapabilities.FLUID_HANDLER, attachedSide.getOpposite()).resolve().orElse(null); + IFluidHandler myFluidHandlerCap = coverHolder.getCapability( + ForgeCapabilities.FLUID_HANDLER, + attachedSide).resolve().orElse(null); + if (myFluidHandlerCap != null && fluidHandlerCap != null) { + IFluidTransfer myFluidHandler = FluidTransferHelperImpl.toFluidTransfer(myFluidHandlerCap); + IFluidTransfer fluidHandler = FluidTransferHelperImpl.toFluidTransfer(fluidHandlerCap); + if (io == IO.OUT) { + performTransferOnUpdate(myFluidHandler, fluidHandler); + } else { + performTransferOnUpdate(fluidHandler, myFluidHandler); + } + } } - if (timer % 20 == 0) { - this.milliBucketsLeftToTransferLastSecond = currentMilliBucketsPerTick * 20; + refreshBuffer(maxMilliBucketsPerTick); } subscriptionHandler.updateSubscription(); } - private long doTransferFluids(long platformTransferLimit) { - var adjacentFluidTransfer = getAdjacentFluidTransfer(); - var ownFluidTransfer = getOwnFluidTransfer(); + public long getFluidsLeftToTransfer() { + return milliBucketsLeftToTransferLastSecond; + } - if (adjacentFluidTransfer != null && ownFluidTransfer != null) { - return switch (io) { - case IN -> doTransferFluidsInternal(adjacentFluidTransfer, ownFluidTransfer, platformTransferLimit); - case OUT -> doTransferFluidsInternal(ownFluidTransfer, adjacentFluidTransfer, platformTransferLimit); - default -> 0L; - }; - } - return 0; + public void reportFluidsTransfer(long transferred) { + milliBucketsLeftToTransferLastSecond -= transferred; } - protected long doTransferFluidsInternal(IFluidTransfer source, IFluidTransfer destination, - long platformTransferLimit) { - return transferAny(source, destination, platformTransferLimit); + protected void refreshBuffer(long transferRate) { + this.milliBucketsLeftToTransferLastSecond = transferRate; } - protected long transferAny(IFluidTransfer source, IFluidTransfer destination, long platformTransferLimit) { - return FluidTransferHelper.transferFluids(source, destination, platformTransferLimit, - filterHandler.getFilter()); + protected void performTransferOnUpdate(@NotNull IFluidTransfer sourceHandler, @NotNull IFluidTransfer destHandler) { + reportFluidsTransfer(performTransfer(sourceHandler, destHandler, false, i -> 0, + i -> getFluidsLeftToTransfer(), null)); } - protected enum TransferDirection { - INSERT, - EXTRACT + /** + * Performs transfer + * + * @param sourceHandler the handler to pull from + * @param destHandler the handler to push to + * @param byFilterSlot whether to perform the transfer by filter slot. + * @param minTransfer the minimum allowed transfer amount, when given a filter slot. If no filter exists or not + * transferring by slot, a filter slot of -1 will be passed in. + * @param maxTransfer the maximum allowed transfer amount, when given a filter slot. If no filter exists or not + * transferring by slot, a filter slot of -1 will be passed in. + * @param transferReport where transfer is reported; a is the filter slot, b is the amount of transfer. + * Each filter slot will report its transfer before the next slot is calculated. + * @return how much was transferred in total. + */ + protected long performTransfer(@NotNull IFluidTransfer sourceHandler, @NotNull IFluidTransfer destHandler, + boolean byFilterSlot, @NotNull LongUnaryOperator minTransfer, + @NotNull LongUnaryOperator maxTransfer, @Nullable BiConsumer transferReport) { + FluidFilter filter = this.filterHandler.getFilter(); + byFilterSlot = byFilterSlot && filter != FluidFilter.EMPTY; // can't be by filter slot if there is no filter + Object2LongOpenHashMap contained = new Object2LongOpenHashMap<>(); + for (int i = 0; i < sourceHandler.getTanks(); ++i) { + FluidStack contents = sourceHandler.getFluidInTank(i); + if (!contents.isEmpty()) contained.merge(new FluidTestObject(contents), contents.getAmount(), Long::sum); + } + var iter = contained.object2LongEntrySet().fastIterator(); + long totalTransfer = 0; + while (iter.hasNext()) { + var content = iter.next(); + FluidStack contents = content.getKey().recombine(content.getLongValue()); + MatchResult match = null; + if (filter == FluidFilter.EMPTY || (match = filter.match(contents)).isMatched()) { + int filterSlot = -1; + if (byFilterSlot) { + assert filter != FluidFilter.EMPTY; // we know it is not null, because if it were byFilterSlot would be false. + filterSlot = match.getFilterIndex(); + } + long min = minTransfer.applyAsLong(filterSlot); + long max = maxTransfer.applyAsLong(filterSlot); + if (max < min || max <= 0) continue; + + if (contents.getAmount() < min) continue; + long transfer = Math.min(contents.getAmount(), max); + FluidStack extracted = sourceHandler.drain(content.getKey().recombine(transfer), false); + if (extracted == null || extracted.getAmount() < min) continue; + transfer = insertToHandler(destHandler, content.getKey(), extracted.getAmount(), true); + if (transfer <= 0 || transfer < min) continue; + extracted = sourceHandler.drain(content.getKey().recombine(transfer), true); + if (extracted == null) continue; + transfer = insertToHandler(destHandler, content.getKey(), extracted.getAmount(), false); + if (transferReport != null) transferReport.accept(filterSlot, transfer); + totalTransfer += transfer; + } + } + return totalTransfer; } - protected Map enumerateDistinctFluids(IFluidTransfer fluidTransfer, TransferDirection direction) { - final Map summedFluids = new Object2LongOpenCustomHashMap<>( - FluidStackHashStrategy.comparingAllButAmount()); - for (int tank = 0; tank < fluidTransfer.getTanks(); tank++) { - if (!canTransfer(fluidTransfer, direction, tank)) - continue; + protected long insertToHandler(@NotNull IFluidTransfer destHandler, FluidTestObject testObject, long count, + boolean simulate) { + if (!(destHandler instanceof IFluidTraverseGuideProvider provider)) { + return simpleInsert(destHandler, testObject, count, simulate); + } + switch (distributionMode) { + case INSERT_FIRST -> { + var guide = provider.getGuide(this::getTD, testObject, count, simulate); + if (guide == null) return 0; + int consumed = (int) TraverseHelpers.traverseFlood(guide.getData(), guide.getPaths(), guide.getFlow()); + guide.reportConsumedFlow(consumed); + return consumed; + } + case ROUND_ROBIN_GLOBAL -> { + var guide = provider.getGuide(this::getEQTD, testObject, count, simulate); + if (guide == null) return 0; + int consumed = (int) TraverseHelpers.traverseEqualDistribution(guide.getData(), + guide.getPathsSupplier(), guide.getFlow(), true); + guide.reportConsumedFlow(consumed); + return consumed; + } + case ROUND_ROBIN_PRIO -> { + var guide = provider + .getGuide( + (net, testObject1, simulator, queryTick, sourcePos, inputFacing) -> getRRTD(net, + testObject1, simulator, queryTick, sourcePos, inputFacing, simulate), + testObject, count, simulate); + if (guide == null) return 0; + int consumed = (int) TraverseHelpers.traverseRoundRobin(guide.getData(), guide.getPaths(), + guide.getFlow(), true); + guide.reportConsumedFlow(consumed); + return consumed; + } + } + return 0; + } - FluidStack fluidStack = fluidTransfer.getFluidInTank(tank); - if (fluidStack.isEmpty()) - continue; + @Contract("_, _, _, _, _, _ -> new") + protected @NotNull FluidTraverseData getTD(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + return new FluidTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } - summedFluids.putIfAbsent(fluidStack, 0L); - summedFluids.computeIfPresent(fluidStack, (stack, totalAmount) -> { - return totalAmount + stack.getAmount(); - }); - } + @Contract("_, _, _, _, _, _ -> new") + protected @NotNull FluidEQTraverseData getEQTD(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + return new FluidEQTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + @Contract("_, _, _, _, _, _, _ -> new") + protected @NotNull FluidRRTraverseData getRRTD(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing, + boolean simulate) { + return new FluidRRTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing, + getRoundRobinCache(simulate)); + } + + protected Object2ObjectLinkedOpenHashMap> getRoundRobinCache(boolean simulate) { + return simulate ? roundRobinCache.clone() : roundRobinCache; + } - return summedFluids; + protected long simpleInsert(@NotNull IFluidTransfer destHandler, FluidTestObject testObject, long count, + boolean simulate) { + return count - destHandler.fill(testObject.recombine(count), !simulate); } - private static boolean canTransfer(IFluidTransfer fluidTransfer, TransferDirection direction, int tank) { - return switch (direction) { - case INSERT -> fluidTransfer.supportsFill(tank); - case EXTRACT -> fluidTransfer.supportsDrain(tank); - }; + protected boolean checkInputFluid(FluidStack fluidStack) { + return filterHandler.test(fluidStack); } ////////////////////////////////////// diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java index a9007ba55e..227897b1f2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java @@ -12,7 +12,6 @@ import com.gregtechceu.gtceu.api.capability.recipe.ItemRecipeCapability; import com.gregtechceu.gtceu.api.data.RotationState; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidPipeProperties; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.data.medicalcondition.MedicalCondition; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; @@ -56,6 +55,7 @@ import com.gregtechceu.gtceu.common.machine.steam.SteamSolarBoiler; import com.gregtechceu.gtceu.common.machine.steam.SteamSolidBoilerMachine; import com.gregtechceu.gtceu.common.machine.storage.*; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialFluidProperties; import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidEndpointMachine; import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemEndpointMachine; import com.gregtechceu.gtceu.config.ConfigHolder; @@ -687,8 +687,8 @@ public static BiConsumer> createTankTooltips(String n var item = stack.getItem(); if (item instanceof DrumMachineItem drumItem && material != null) { - if (material.hasProperty(PropertyKey.FLUID_PIPE)) { - FluidPipeProperties pipeprops = material.getProperty(PropertyKey.FLUID_PIPE); + if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES)) { + MaterialFluidProperties pipeprops = material.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY); pipeprops.appendTooltips(list, true, true); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/AirScrubberMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/AirScrubberMachine.java index ff5c8e0f42..c41d385fb5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/AirScrubberMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/AirScrubberMachine.java @@ -2,10 +2,10 @@ import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.data.medicalcondition.MedicalCondition; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.SimpleTieredMachine; import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardCleaner; -import com.gregtechceu.gtceu.common.blockentity.DuctPipeBlockEntity; import com.gregtechceu.gtceu.common.capability.EnvironmentalHazardSavedData; import com.gregtechceu.gtceu.common.data.GTMachines; import com.gregtechceu.gtceu.common.data.GTRecipeTypes; @@ -75,7 +75,7 @@ public boolean onWorking() { for (Direction dir : GTUtil.DIRECTIONS) { BlockPos offset = getPos().relative(dir); if (GTCapabilityHelper.getHazardContainer(getLevel(), offset, dir.getOpposite()) != null) { - if (getLevel().getBlockEntity(offset) instanceof DuctPipeBlockEntity duct && + if (getLevel().getBlockEntity(offset) instanceof PipeBlockEntity duct && !duct.isConnected(dir.getOpposite())) { continue; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java new file mode 100644 index 0000000000..e192754ecf --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java @@ -0,0 +1,247 @@ +package com.gregtechceu.gtceu.common.pipelike.handlers.properties; + +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidProperty; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.MaterialProperties; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PipeNetProperties; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; +import com.gregtechceu.gtceu.api.fluids.FluidBuilder; +import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKeys; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLossFunction; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.net.energy.SuperconductorLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.VoltageLimitLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.VoltageLossLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.WorldEnergyNet; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.material.Fluid; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import snownee.jade.api.BlockAccessor; + +import java.util.List; + +import static com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialFlags.GENERATE_FOIL; +import static com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialFlags.NO_UNIFICATION; + +public final class MaterialEnergyProperties implements PipeNetProperties.IPipeNetMaterialProperty { + + public static final MaterialPropertyKey KEY = new MaterialPropertyKey<>( + "EnergyProperties"); + + private final long voltageLimit; + private final long amperageLimit; + private int materialMeltTemperature; + private final long lossPerAmp; + private final int superconductorCriticalTemperature; + + /** + * Generate a MaterialEnergyProperties + * + * @param voltageLimit the voltage limit for the cable + * @param amperageLimit the base amperage for the cable. + * @param lossPerAmp the base loss per amp per block traveled. + * @param superconductorCriticalTemperature the superconductor temperature. When the temperature is at or below + * superconductor temperature, loss will be treated as zero. A + * superconductor + * temperature of 0 or less will be treated as not a superconductor. + */ + public MaterialEnergyProperties(long voltageLimit, long amperageLimit, long lossPerAmp, + int superconductorCriticalTemperature) { + this.voltageLimit = voltageLimit; + this.amperageLimit = amperageLimit; + this.lossPerAmp = lossPerAmp; + this.superconductorCriticalTemperature = superconductorCriticalTemperature; + } + + public long getVoltageLimit() { + return voltageLimit; + } + + public static MaterialEnergyProperties create(long voltageLimit, long amperageLimit, long lossPerAmp, + int superconductorCriticalTemperature) { + return new MaterialEnergyProperties(voltageLimit, amperageLimit, lossPerAmp, + superconductorCriticalTemperature); + } + + public static MaterialEnergyProperties create(long voltageLimit, long amperageLimit, long lossPerAmp) { + return new MaterialEnergyProperties(voltageLimit, amperageLimit, lossPerAmp, 0); + } + + public static TagPrefix.MaterialRecipeHandler registrationHandler(TagPrefix.MaterialRecipeHandler handler) { + return (orePrefix, material, properties, provider) -> { + if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && !material.hasFlag(NO_UNIFICATION) && + material.getProperty(PropertyKey.PIPENET_PROPERTIES).hasProperty(KEY)) { + handler.accept(orePrefix, material, + material.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(KEY), provider); + } + }; + } + + public boolean isSuperconductor() { + return this.superconductorCriticalTemperature > 1; + } + + @Override + public MaterialPropertyKey getKey() { + return KEY; + } + + @Override + public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeMaterialStructure structure) { + int tier = GTUtil.getTierByVoltage(voltageLimit); + if (isSuperconductor()) + tooltip.add(Component.translatable("gtceu.cable.superconductor", GTValues.VN[tier])); + tooltip.add(Component.translatable("gtceu.cable.voltage", voltageLimit, GTValues.VNF[tier])); + tooltip.add(Component.translatable("gtceu.cable.amperage", getAmperage(structure))); + tooltip.add(Component.translatable("gtceu.cable.loss_per_block", getLoss(structure))); + if (isSuperconductor()) + tooltip.add(Component.translatable("gtceu.cable.superconductor_loss", superconductorCriticalTemperature)); + } + + @Override + public void verifyProperty(MaterialProperties properties) { + properties.ensureSet(PropertyKey.DUST, true); + if (properties.hasProperty(PropertyKey.INGOT)) { + // Ensure all Materials with Cables and voltage tier IV or above have a Foil for recipe generation + Material thisMaterial = properties.getMaterial(); + if (!isSuperconductor() && voltageLimit >= GTValues.V[GTValues.IV] && + !thisMaterial.hasFlag(GENERATE_FOIL)) { + thisMaterial.addFlags(GENERATE_FOIL); + } + } + this.materialMeltTemperature = computeMaterialMeltTemperature(properties); + } + + public static int computeMaterialMeltTemperature(@NotNull MaterialProperties properties) { + if (properties.hasProperty(PropertyKey.FLUID)) { + // autodetermine melt temperature from registered fluid + FluidProperty prop = properties.getProperty(PropertyKey.FLUID); + Fluid fluid = prop.get(FluidStorageKeys.LIQUID); + if (fluid == null) { + FluidBuilder builder = prop.getQueuedBuilder(FluidStorageKeys.LIQUID); + if (builder != null) { + return builder.getDeterminedTemperature(properties.getMaterial(), FluidStorageKeys.LIQUID); + } + } else { + return fluid.getFluidType().getTemperature(); + } + } + return 3000; + } + + @Override + @Nullable + public WorldPipeNetNode getOrCreateFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof CableStructure) { + WorldPipeNetNode node = WorldEnergyNet.getWorldNet(world).getOrCreateNode(pos); + mutateData(node.getData(), structure); + return node; + } else if (structure instanceof MaterialPipeStructure pipe) { + long amperage = amperageLimit * pipe.material() / 2; + if (amperage == 0) return null; // skip pipes that are too small + WorldPipeNetNode node = WorldEnergyNet.getWorldNet(world).getOrCreateNode(pos); + mutateData(node.getData(), pipe); + return node; + } + return null; + } + + @Override + public void mutateData(NetLogicData data, IPipeStructure structure) { + if (structure instanceof CableStructure cable) { + long loss = getLoss(structure); + long amperage = getAmperage(structure); + boolean insulated = cable.partialBurnStructure() != null; + // insulated cables cool down half as fast + float coolingFactor = (float) (Math.sqrt(cable.material()) / (insulated ? 8 : 4)); + data.setLogicEntry(VoltageLossLogic.INSTANCE.getWith(loss)) + .setLogicEntry(WeightFactorLogic.INSTANCE.getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.INSTANCE.getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.INSTANCE.getWith(voltageLimit)) + .setLogicEntry(TemperatureLogic.INSTANCE + .getWith(TemperatureLossFunction.getOrCreateCable(coolingFactor), materialMeltTemperature, + 1, + 100 * cable.material(), cable.partialBurnThreshold())); + if (superconductorCriticalTemperature > 0) { + data.setLogicEntry(SuperconductorLogic.INSTANCE.getWith(superconductorCriticalTemperature)); + } + } else if (structure instanceof MaterialPipeStructure pipe) { + long amperage = getAmperage(structure); + if (amperage == 0) return; // skip pipes that are too small + long loss = getLoss(structure); + float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); + data.setLogicEntry(VoltageLossLogic.INSTANCE.getWith(loss)) + .setLogicEntry(WeightFactorLogic.INSTANCE.getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.INSTANCE.getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.INSTANCE.getWith(voltageLimit)) + .setLogicEntry(TemperatureLogic.INSTANCE + .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, 1, + 50 * pipe.material(), null)); + if (superconductorCriticalTemperature > 0) { + data.setLogicEntry(SuperconductorLogic.INSTANCE.getWith(superconductorCriticalTemperature)); + } + } + } + + private long getLoss(IPipeStructure structure) { + if (structure instanceof CableStructure cable) { + return lossPerAmp * cable.costFactor(); + } else if (structure instanceof MaterialPipeStructure pipe) { + return lossPerAmp * (pipe.material() > 6 ? 3 : 2); + } else return lossPerAmp; + } + + private long getAmperage(IPipeStructure structure) { + if (structure instanceof CableStructure cable) { + return amperageLimit * cable.material(); + } else if (structure instanceof MaterialPipeStructure pipe) { + return amperageLimit * pipe.material() / 2; + } else return amperageLimit; + } + + @Override + @Nullable + public WorldPipeNetNode getFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof CableStructure || structure instanceof MaterialPipeStructure) + return WorldEnergyNet.getWorldNet(world).getNode(pos); + else return null; + } + + @Override + public void removeFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof CableStructure || structure instanceof MaterialPipeStructure) { + WorldEnergyNet net = WorldEnergyNet.getWorldNet(world); + NetNode node = net.getNode(pos); + if (node != null) net.removeNode(node); + } + } + + @Override + public boolean generatesStructure(IPipeStructure structure) { + return structure instanceof CableStructure cable && (!isSuperconductor() || !cable.isInsulated()); + } + + @Override + public boolean supportsStructure(IPipeStructure structure) { + return structure instanceof CableStructure || structure instanceof MaterialPipeStructure; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java new file mode 100644 index 0000000000..04a52860c8 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java @@ -0,0 +1,228 @@ +package com.gregtechceu.gtceu.common.pipelike.handlers.properties; + +import com.gregtechceu.gtceu.api.capability.IPropertyFluidFilter; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.MaterialProperties; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PipeNetProperties; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.fluids.FluidConstants; +import com.gregtechceu.gtceu.api.fluids.FluidState; +import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLossFunction; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidContainmentLogic; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.WorldFluidNet; +import com.gregtechceu.gtceu.utils.FormattingUtil; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import lombok.Getter; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.UnmodifiableView; + +import java.util.Collection; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; + +public final class MaterialFluidProperties implements PipeNetProperties.IPipeNetMaterialProperty, IPropertyFluidFilter { + + public static final MaterialPropertyKey KEY = new MaterialPropertyKey<>("FluidProperties"); + + @Getter + private final Set containedAttributes = new ObjectOpenHashSet<>(); + private final EnumSet containableStates = EnumSet.of(FluidState.LIQUID); + + @Getter + private final int maxFluidTemperature; + private final int minFluidTemperature; + private int materialMeltTemperature; + + private final long baseThroughput; + private final float priority; + + public MaterialFluidProperties(long baseThroughput, int maxFluidTemperature, int minFluidTemperature, + float priority) { + this.baseThroughput = baseThroughput; + this.maxFluidTemperature = maxFluidTemperature; + this.minFluidTemperature = minFluidTemperature; + this.priority = priority; + } + + public MaterialFluidProperties(long baseThroughput, int maxFluidTemperature, int minFluidTemperature) { + this(baseThroughput, maxFluidTemperature, minFluidTemperature, 2048f / baseThroughput); + } + + public static MaterialFluidProperties createMax(long baseThroughput, int maxFluidTemperature) { + return createMax(baseThroughput, maxFluidTemperature, 2048f / baseThroughput); + } + + public static MaterialFluidProperties createMax(long baseThroughput, int maxFluidTemperature, float priority) { + return new MaterialFluidProperties(baseThroughput, maxFluidTemperature, + FluidConstants.CRYOGENIC_FLUID_THRESHOLD + 1, priority); + } + + public static MaterialFluidProperties createMin(long baseThroughput, int minFluidTemperature) { + return createMin(baseThroughput, minFluidTemperature, 2048f / baseThroughput); + } + + public static MaterialFluidProperties createMin(long baseThroughput, int minFluidTemperature, float priority) { + return new MaterialFluidProperties(baseThroughput, 0, minFluidTemperature, priority); + } + + public static MaterialFluidProperties create(long baseThroughput) { + return create(baseThroughput, 2048f / baseThroughput); + } + + public static MaterialFluidProperties create(long baseThroughput, float priority) { + return new MaterialFluidProperties(baseThroughput, 0, 0, priority); + } + + public MaterialFluidProperties setContain(FluidState state, boolean canContain) { + if (canContain) contain(state); + else notContain(state); + return this; + } + + public MaterialFluidProperties setContain(FluidAttribute attribute, boolean canContain) { + if (canContain) contain(attribute); + else notContain(attribute); + return this; + } + + public MaterialFluidProperties contain(FluidState state) { + this.containableStates.add(state); + return this; + } + + public MaterialFluidProperties contain(FluidAttribute attribute) { + this.containedAttributes.add(attribute); + return this; + } + + public MaterialFluidProperties notContain(FluidState state) { + this.containableStates.remove(state); + return this; + } + + public MaterialFluidProperties notContain(FluidAttribute attribute) { + this.containedAttributes.remove(attribute); + return this; + } + + public boolean canContain(@NotNull FluidState state) { + return this.containableStates.contains(state); + } + + public boolean canContain(@NotNull FluidAttribute attribute) { + return this.containedAttributes.contains(attribute); + } + + @Override + public void setCanContain(@NotNull FluidAttribute attribute, boolean canContain) { + setContain(attribute, canContain); + } + + public int getMinFluidTemperature() { + return minFluidTemperature; + } + + @Override + public MaterialPropertyKey getKey() { + return KEY; + } + + @Override + public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeMaterialStructure structure) { + tooltip.add(Component.translatable("gtceu.universal.tooltip.fluid_transfer_rate", getThroughput(structure))); + tooltip.add(Component.translatable("gtceu.fluid_pipe.max_temperature", getMaxFluidTemperature())); + tooltip.add(Component.translatable("gtceu.fluid_pipe.min_temperature", getMinFluidTemperature())); + tooltip.add(Component.translatable("gtceu.fluid_pipe.priority", + FormattingUtil.formatNumbers(getFlowPriority(structure)))); + } + + @Override + public void verifyProperty(MaterialProperties properties) { + if (!properties.hasProperty(PropertyKey.WOOD)) { + properties.ensureSet(PropertyKey.INGOT, true); + } + this.materialMeltTemperature = MaterialEnergyProperties.computeMaterialMeltTemperature(properties); + } + + @Override + @Nullable + public WorldPipeNetNode getOrCreateFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure) { + WorldPipeNetNode node = WorldFluidNet.getWorldNet(world).getOrCreateNode(pos); + mutateData(node.getData(), structure); + return node; + } + return null; + } + + @Override + public void mutateData(NetLogicData data, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure pipe) { + long throughput = getThroughput(structure); + float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); + data.setLogicEntry(WeightFactorLogic.INSTANCE.getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.INSTANCE.getWith(throughput)) + .setLogicEntry(FluidContainmentLogic.INSTANCE.getWith(containableStates, containedAttributes, + maxFluidTemperature)) + .setLogicEntry(TemperatureLogic.INSTANCE + .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, + minFluidTemperature, 50 * pipe.material(), null)); + } + } + + private long getThroughput(IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure pipe) { + return baseThroughput * pipe.material(); + } else return baseThroughput; + } + + private double getFlowPriority(IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure pipe) { + return priority * (pipe.restrictive() ? 100d : 1d) * pipe.channelCount() / pipe.material(); + } else return priority; + } + + @Override + public @Nullable WorldPipeNetNode getFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure) + return WorldFluidNet.getWorldNet(world).getNode(pos); + else return null; + } + + @Override + public void removeFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure) { + WorldFluidNet net = WorldFluidNet.getWorldNet(world); + NetNode node = net.getNode(pos); + if (node != null) net.removeNode(node); + } + } + + @Override + public boolean generatesStructure(IPipeStructure structure) { + return structure.getClass() == MaterialPipeStructure.class; + } + + @Override + public boolean supportsStructure(IPipeStructure structure) { + return structure instanceof MaterialPipeStructure; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java new file mode 100644 index 0000000000..a696bda81f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java @@ -0,0 +1,120 @@ +package com.gregtechceu.gtceu.common.pipelike.handlers.properties; + +import com.gregtechceu.gtceu.api.data.chemical.material.properties.MaterialProperties; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PipeNetProperties; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.net.item.WorldItemNet; +import com.gregtechceu.gtceu.utils.FormattingUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public final class MaterialItemProperties implements PipeNetProperties.IPipeNetMaterialProperty { + + public static final MaterialPropertyKey KEY = new MaterialPropertyKey<>("ItemProperties"); + + private final long baseItemsPer5Ticks; + private final float priority; + + public MaterialItemProperties(long baseItemsPer5Ticks, float priority) { + this.baseItemsPer5Ticks = baseItemsPer5Ticks; + this.priority = priority; + } + + public static MaterialItemProperties create(long baseThroughput) { + return new MaterialItemProperties(baseThroughput, 2048f / baseThroughput); + } + + @Override + public MaterialPropertyKey getKey() { + return KEY; + } + + @Override + public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, + @NotNull TooltipFlag flagIn, IPipeMaterialStructure structure) { + if (baseItemsPer5Ticks % 16 != 0) { + tooltip.add(Component.translatable("gtceu.universal.tooltip.item_transfer_rate", + baseItemsPer5Ticks * 4)); + } else { + tooltip.add(Component.translatable("gtceu.universal.tooltip.item_transfer_rate_stacks", + baseItemsPer5Ticks / 16)); + } + tooltip.add(Component.translatable("gtceu.item_pipe.priority", + FormattingUtil.formatNumbers(getFlowPriority(structure)))); + } + + @Override + public void verifyProperty(MaterialProperties properties) { + if (!properties.hasProperty(PropertyKey.WOOD)) { + properties.ensureSet(PropertyKey.INGOT, true); + } + } + + @Override + @Nullable + public WorldPipeNetNode getOrCreateFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure) { + WorldPipeNetNode node = WorldItemNet.getWorldNet(world).getOrCreateNode(pos); + mutateData(node.getData(), structure); + return node; + } + return null; + } + + @Override + public void mutateData(NetLogicData data, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure pipe) { + long throughput = baseItemsPer5Ticks * pipe.material(); + data.setLogicEntry(WeightFactorLogic.INSTANCE.getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.INSTANCE.getWith(throughput)); + } + } + + private double getFlowPriority(IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure pipe) { + return priority * (pipe.restrictive() ? 100d : 1d) * pipe.channelCount() / pipe.material(); + } else return priority; + } + + @Override + public @Nullable WorldPipeNetNode getFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure) + return WorldItemNet.getWorldNet(world).getNode(pos); + else return null; + } + + @Override + public void removeFromNet(ServerLevel world, BlockPos pos, IPipeStructure structure) { + if (structure instanceof MaterialPipeStructure) { + WorldItemNet net = WorldItemNet.getWorldNet(world); + NetNode node = net.getNode(pos); + if (node != null) net.removeNode(node); + } + } + + @Override + public boolean generatesStructure(IPipeStructure structure) { + return structure.getClass() == MaterialPipeStructure.class; + } + + @Override + public boolean supportsStructure(IPipeStructure structure) { + return structure instanceof MaterialPipeStructure; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java index 87637f9b8c..5bb9065273 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java @@ -2,20 +2,16 @@ import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidPipeProperties; import com.gregtechceu.gtceu.api.data.chemical.material.properties.IMaterialProperty; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.ItemPipeProperties; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.data.chemical.material.stack.UnificationEntry; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctStructure; -import com.gregtechceu.gtceu.common.pipelike.duct.DuctPipeType; import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; import com.gregtechceu.gtceu.utils.FormattingUtil; import com.gregtechceu.gtceu.utils.GTUtil; - import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.world.item.ItemStack; @@ -30,38 +26,40 @@ public class PipeRecipeHandler { public static void init(Consumer provider) { - pipeTiny.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeTiny); - pipeSmall.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeSmall); - pipeNormal.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeNormal); - pipeLarge.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeLarge); - pipeHuge.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeHuge); - - pipeQuadruple.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeQuadruple); - pipeNonuple.executeHandler(provider, PropertyKey.FLUID_PIPE, PipeRecipeHandler::processPipeNonuple); + pipeTiny.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeTiny); + pipeSmall.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeSmall); + pipeNormal.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeNormal); + pipeLarge.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeLarge); + pipeHuge.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeHuge); - pipeSmallItem.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processPipeSmall); - pipeNormalItem.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processPipeNormal); - pipeLargeItem.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processPipeLarge); - pipeHugeItem.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processPipeHuge); + pipeQuadruple.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeQuadruple); + pipeNonuple.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeNonuple); - pipeSmallRestrictive.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processRestrictivePipe); - pipeNormalRestrictive.executeHandler(provider, PropertyKey.ITEM_PIPE, + pipeTinyRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + pipeSmallRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + pipeNormalRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); - pipeLargeRestrictive.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processRestrictivePipe); - pipeHugeRestrictive.executeHandler(provider, PropertyKey.ITEM_PIPE, PipeRecipeHandler::processRestrictivePipe); + pipeLargeRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + pipeHugeRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + + pipeQuadrupleRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + pipeNonupleRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); addDuctRecipes(provider, Steel, 2); addDuctRecipes(provider, StainlessSteel, 4); addDuctRecipes(provider, TungstenSteel, 8); } - private static void processRestrictivePipe(TagPrefix pipePrefix, Material material, ItemPipeProperties property, + private static void processRestrictivePipe(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { TagPrefix unrestrictive; - if (pipePrefix == pipeSmallRestrictive) unrestrictive = pipeSmallItem; - else if (pipePrefix == pipeNormalRestrictive) unrestrictive = pipeNormalItem; - else if (pipePrefix == pipeLargeRestrictive) unrestrictive = pipeLargeItem; - else if (pipePrefix == pipeHugeRestrictive) unrestrictive = pipeHugeItem; + if (pipePrefix == pipeTinyRestrictive) unrestrictive = pipeTiny; + else if (pipePrefix == pipeSmallRestrictive) unrestrictive = pipeSmall; + else if (pipePrefix == pipeNormalRestrictive) unrestrictive = pipeNormal; + else if (pipePrefix == pipeLargeRestrictive) unrestrictive = pipeLarge; + else if (pipePrefix == pipeHugeRestrictive) unrestrictive = pipeHuge; + else if (pipePrefix == pipeQuadrupleRestrictive) unrestrictive = pipeQuadruple; + else if (pipePrefix == pipeNonupleRestrictive) unrestrictive = pipeNonuple; else return; ASSEMBLER_RECIPES.recipeBuilder("assemble_" + material.getName() + "_" + pipePrefix.name) @@ -213,7 +211,7 @@ private static void processPipeHuge(TagPrefix pipePrefix, Material material, IMa } } - private static void processPipeQuadruple(TagPrefix pipePrefix, Material material, FluidPipeProperties property, + private static void processPipeQuadruple(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; ItemStack smallPipe = ChemicalHelper.get(pipeSmall, material); @@ -231,7 +229,7 @@ private static void processPipeQuadruple(TagPrefix pipePrefix, Material material .save(provider); } - private static void processPipeNonuple(TagPrefix pipePrefix, Material material, FluidPipeProperties property, + private static void processPipeNonuple(TagPrefix pipePrefix, Material material, IMaterialProperty property, Consumer provider) { if (material.hasProperty(PropertyKey.WOOD)) return; ItemStack smallPipe = ChemicalHelper.get(pipeSmall, material); @@ -251,16 +249,16 @@ private static void processPipeNonuple(TagPrefix pipePrefix, Material material, private static void addDuctRecipes(Consumer provider, Material material, int outputAmount) { VanillaRecipeHelper.addShapedRecipe(provider, "small_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPE_BLOCKS[DuctStructure.SMALL].asStack(outputAmount * 2), "w", "X", "h", + GTBlocks.DUCT_PIPE_BLOCKS.get(DuctStructure.SMALL).asStack(outputAmount * 2), "w", "X", "h", 'X', new UnificationEntry(plate, material)); VanillaRecipeHelper.addShapedRecipe(provider, "medium_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPE_BLOCKS[DuctPipeType.NORMAL.ordinal()].asStack(outputAmount), " X ", "wXh", " X ", + GTBlocks.DUCT_PIPE_BLOCKS.get(DuctStructure.NORMAL).asStack(outputAmount), " X ", "wXh", " X ", 'X', new UnificationEntry(plate, material)); VanillaRecipeHelper.addShapedRecipe(provider, "large_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPE_BLOCKS[DuctPipeType.LARGE.ordinal()].asStack(outputAmount), "XwX", "X X", "XhX", + GTBlocks.DUCT_PIPE_BLOCKS.get(DuctStructure.LARGE).asStack(outputAmount), "XwX", "X X", "XhX", 'X', new UnificationEntry(plate, material)); VanillaRecipeHelper.addShapedRecipe(provider, "huge_duct_%s".formatted(material.getName()), - GTBlocks.DUCT_PIPE_BLOCKS[DuctPipeType.HUGE.ordinal()].asStack(outputAmount), "XwX", "X X", "XhX", + GTBlocks.DUCT_PIPE_BLOCKS.get(DuctStructure.HUGE).asStack(outputAmount), "XwX", "X X", "XhX", 'X', new UnificationEntry(plateDouble, material)); } From a5c641530db4e2d8ad58eaf859b73dc6d5766f2e Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Fri, 23 Aug 2024 17:22:44 +0300 Subject: [PATCH 10/70] WHAT THE FUCK THE COMPILE ERRORS STOPPED COMING now for the runtime ones :) --- .../gtceu/api/block/MaterialBlock.java | 19 +- .../api/capability/IPropertyFluidFilter.java | 2 - .../gtceu/api/cover/filter/Filter.java | 21 + .../gtceu/api/cover/filter/FluidFilter.java | 16 + .../gtceu/api/cover/filter/ItemFilter.java | 16 + .../api/cover/filter/SimpleFluidFilter.java | 42 ++ .../api/cover/filter/SimpleItemFilter.java | 21 + .../api/cover/filter/TagFluidFilter.java | 26 ++ .../gtceu/api/cover/filter/TagItemFilter.java | 27 ++ .../properties/PipeNetProperties.java | 1 - .../material/properties/PropertyKey.java | 1 - .../material/properties/WireProperties.java | 164 -------- .../gtceu/api/data/tag/TagPrefix.java | 23 +- .../gtceu/api/fluids/FluidBuilder.java | 1 - .../graphnet/pipenet/WorldPipeNetNode.java | 2 +- .../pipenet/physical/IPipeStructure.java | 7 + ...ableBlock.java => ActivablePipeBlock.java} | 4 +- ...erialBlock.java => MaterialPipeBlock.java} | 22 +- .../physical/block/MaterialPipeBlockItem.java | 6 +- .../pipenet/physical/block/PipeBlock.java | 16 +- .../pipenet/physical/block/PipeBlockItem.java | 2 +- ...tity.java => MaterialPipeBlockEntity.java} | 10 +- .../physical/tile/PipeBlockEntity.java | 93 ++++- .../api/gui/fancy/FancyMachineUIWidget.java | 8 +- .../gtceu/api/item/MetaMachineItem.java | 12 +- .../gtceu/api/pattern/Predicates.java | 3 +- .../renderer/BlockHighLightRenderer.java | 10 +- .../renderer/cover/FacadeCoverRenderer.java | 23 ++ .../renderer/pipe/AbstractPipeModel.java | 6 +- .../client/renderer/pipe/CableModel.java | 4 +- .../client/renderer/pipe/DuctPipeModel.java | 6 +- .../gtceu/client/renderer/pipe/PipeModel.java | 4 +- .../renderer/pipe/cover/CoverRenderer.java | 4 +- .../pipe/cover/CoverRendererBuilder.java | 14 +- .../pipe/cover/CoverRendererPackage.java | 6 +- .../common/cover/ComputerMonitorCover.java | 6 + .../gtceu/common/cover/ConveyorCover.java | 8 +- .../gtceu/common/cover/CoverSolarPanel.java | 14 +- .../gtceu/common/cover/FacadeCover.java | 7 + .../gtceu/common/cover/FluidFilterCover.java | 14 +- .../common/cover/FluidRegulatorCover.java | 370 ++++++++++++------ .../common/cover/InfiniteWaterCover.java | 14 +- .../gtceu/common/cover/ItemFilterCover.java | 15 +- .../common/cover/MachineControllerCover.java | 21 +- .../gtceu/common/cover/PumpCover.java | 28 +- .../gtceu/common/cover/RobotArmCover.java | 349 +++++++++++++---- .../gtceu/common/cover/ShutterCover.java | 8 + .../cover/detector/ActivityDetectorCover.java | 14 +- .../cover/detector/EnergyDetectorCover.java | 15 +- .../cover/detector/FluidDetectorCover.java | 14 +- .../cover/detector/ItemDetectorCover.java | 14 +- .../detector/MaintenanceDetectorCover.java | 15 +- .../voiding/AdvancedFluidVoidingCover.java | 65 ++- .../cover/voiding/FluidVoidingCover.java | 67 ++-- .../gtceu/common/data/GTBlockEntities.java | 18 +- .../gtceu/common/data/GTBlocks.java | 23 +- .../gtceu/common/data/GTCovers.java | 2 +- .../gtceu/common/data/GTItems.java | 11 +- .../gtceu/common/data/GTMachines.java | 5 +- .../data/materials/ElementMaterials.java | 14 +- .../data/materials/FirstDegreeMaterials.java | 20 +- .../materials/OrganicChemistryMaterials.java | 2 +- .../data/materials/SecondDegreeMaterials.java | 2 +- .../common/item/ColorSprayBehaviour.java | 9 +- .../common/item/PortableScannerBehavior.java | 8 +- .../electric/WorldAcceleratorMachine.java | 1 + .../common/machine/storage/DrumMachine.java | 3 +- .../pipelike/block/cable/CableBlock.java | 4 +- .../pipelike/block/cable/CableStructure.java | 7 + .../pipelike/block/duct/DuctPipeBlock.java | 7 +- .../pipelike/block/duct/DuctStructure.java | 15 +- .../pipelike/block/laser/LaserPipeBlock.java | 6 +- .../block/optical/OpticalPipeBlock.java | 6 +- .../block/pipe/MaterialPipeBlock.java | 4 +- .../pipelike/handlers/DuctNetHandler.java | 4 +- .../properties/MaterialEnergyProperties.java | 15 +- .../properties/MaterialFluidProperties.java | 8 +- .../properties/MaterialItemProperties.java | 2 + .../net/duct/DuctCapabilityObject.java | 20 +- .../pipelike/net/duct/WorldDuctNet.java | 2 + .../net/energy/AveragingPerTickCounter.java | 83 ++++ .../pipelike/net/energy/EnergyFlowLogic.java | 21 +- .../net/fluid/IFluidTransferController.java | 4 +- .../gregtechceu/gtceu/core/MixinHelpers.java | 6 - .../recipe/generated/PartsRecipeHandler.java | 4 +- .../recipe/generated/PipeRecipeHandler.java | 19 +- .../generated/WireCombiningHandler.java | 19 +- .../recipe/generated/WireRecipeHandler.java | 26 +- .../data/recipe/misc/ComponentRecipes.java | 4 +- .../recipe/misc/MetaTileEntityLoader.java | 2 +- .../MetaTileEntityMachineRecipeLoader.java | 4 +- .../gtceu/integration/jade/GTJadePlugin.java | 4 +- .../jade/provider/CableBlockProvider.java | 41 +- .../provider/FluidPipeStorageProvider.java | 10 +- .../jade/provider/StainedColorProvider.java | 3 +- .../top/provider/CableInfoProvider.java | 70 ++-- .../top/provider/StainedColorProvider.java | 3 +- .../gregtechceu/gtceu/utils/TriConsumer.java | 7 + 98 files changed, 1523 insertions(+), 725 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java rename src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/{PipeActivableBlock.java => ActivablePipeBlock.java} (91%) rename src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/{PipeMaterialBlock.java => MaterialPipeBlock.java} (79%) rename src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/{PipeMaterialBlockEntity.java => MaterialPipeBlockEntity.java} (89%) create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/AveragingPerTickCounter.java create mode 100644 src/main/java/com/gregtechceu/gtceu/utils/TriConsumer.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java index 83aed64836..497653c763 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/block/MaterialBlock.java @@ -2,6 +2,9 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; import com.gregtechceu.gtceu.client.renderer.block.MaterialBlockRenderer; @@ -187,7 +190,7 @@ public InteractionResult use(BlockState state, Level level, BlockPos pos, Player continue; } BlockEntity te = level.getBlockEntity(blockPos); - if (te instanceof PipeBlockEntity pbe && pbe.getFrameMaterial() != null) { + if (te instanceof PipeBlockEntity pbe && pbe.getFrameMaterial() != null) { blockPos.move(Direction.UP); continue; } @@ -196,7 +199,7 @@ public InteractionResult use(BlockState state, Level level, BlockPos pos, Player if (!player.isCreative()) stack.shrink(1); return InteractionResult.SUCCESS; - } else if (te instanceof PipeBlockEntity pbe && pbe.getFrameMaterial() == null) { + } else if (te instanceof PipeBlockEntity pbe && pbe.getFrameMaterial() == null) { pbe.setFrameMaterial(frameBlock.material); if (!player.isCreative()) @@ -223,7 +226,7 @@ public static MaterialBlock getFrameboxFromItem(ItemStack stack) { public boolean removeFrame(Level level, BlockPos pos, Player player, ItemStack stack) { BlockEntity te = level.getBlockEntity(pos); - if (te instanceof PipeBlockEntity pipeTile) { + if (te instanceof PipeBlockEntity pipeTile) { Material mat = pipeTile.getFrameMaterial(); if (mat != null) { pipeTile.setFrameMaterial(null); @@ -245,17 +248,17 @@ public boolean canBeReplaced(BlockState state, BlockPlaceContext useContext) { public boolean replaceWithFramedPipe(Level level, BlockPos pos, BlockState state, Player player, ItemStack stackInHand, BlockHitResult hit) { - PipeBlock pipeBlock = (PipeBlock) ((PipeBlockItem) stackInHand.getItem()).getBlock(); - if (pipeBlock.pipeType.getThickness() < 1) { + PipeBlock pipeBlock = ((PipeBlockItem) stackInHand.getItem()).getBlock(); + if (pipeBlock.getStructure().getRenderThickness() < 1) { PipeBlockItem itemBlock = (PipeBlockItem) stackInHand.getItem(); BlockState pipeState = pipeBlock.defaultBlockState(); BlockPlaceContext context = new BlockPlaceContext(level, player, InteractionHand.MAIN_HAND, stackInHand, hit); BlockState original = level.getBlockState(context.getClickedPos()); itemBlock.placeBlock(context, pipeState); - var pipeTile = pipeBlock.getPipeTile(level, pos); - if (pipeTile instanceof PipeBlockEntity pipeBlockEntity) { - pipeBlockEntity.setFrameMaterial(material); + var pipeTile = pipeBlock.getBlockEntity(level, pos); + if (pipeTile != null) { + pipeTile.setFrameMaterial(material); } else { // reset the state if we didn't place correctly level.setBlockAndUpdate(context.getClickedPos(), original); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java index 2a56a919f4..1f337b47e3 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java @@ -19,8 +19,6 @@ import java.util.List; import java.util.function.Predicate; -import static com.gregtechceu.gtceu.api.fluids.FluidConstants.CRYOGENIC_FLUID_THRESHOLD; - public interface IPropertyFluidFilter extends Predicate { @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java index fd5d16559c..976dd1378a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java @@ -8,6 +8,7 @@ import net.minecraft.util.StringRepresentable; import lombok.RequiredArgsConstructor; +import net.minecraft.world.item.ItemStack; import java.util.function.Consumer; import java.util.function.Function; @@ -35,6 +36,26 @@ default boolean isBlackList() { default void setBlackList(boolean blackList) {} + int getMaxTransferSize(); + + void setMaxTransferSize(int maxTransferSize); + + default int getTransferLimit(int slot, int transferSize) { + return transferSize; + } + + default int getTransferLimit(int slot) { + return getMaxTransferSize(); + } + + default int getTransferLimit(T stack, int transferSize) { + return 0; + } + + default int getTransferLimit(T stack) { + return 0; + } + default boolean testGeneric(Object test) { return this.test((T) test); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java index 041fa8ee04..c97702d42e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.api.cover.filter; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; @@ -48,6 +49,11 @@ default boolean supportsAmounts() { */ FluidFilter EMPTY = new FluidFilter() { + @Override + public MatchResult apply(FluidStack fluidStack) { + return MatchResult.ANY; + } + @Override public boolean test(FluidStack fluidStack) { return true; @@ -77,5 +83,15 @@ public CompoundTag saveFilter() { public void setOnUpdated(Consumer onUpdated) { throw new NotImplementedException("Not available for empty fluid filter"); } + + @Override + public int getMaxTransferSize() { + return 0; + } + + @Override + public void setMaxTransferSize(int maxTransferSize) { + + } }; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java index 7c8d5181d0..44f3788687 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.api.cover.filter; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import net.minecraft.nbt.CompoundTag; @@ -51,6 +52,11 @@ default int getMaxStackSize() { */ ItemFilter EMPTY = new ItemFilter() { + @Override + public MatchResult apply(ItemStack stack) { + return MatchResult.ANY; + } + @Override public int testItemCount(ItemStack itemStack) { return Integer.MAX_VALUE; @@ -80,5 +86,15 @@ public CompoundTag saveFilter() { public void setOnUpdated(Consumer onUpdated) { throw new NotImplementedException("Not available for empty item filter"); } + + @Override + public int getMaxTransferSize() { + return 0; + } + + @Override + public void setMaxTransferSize(int maxTransferSize) { + + } }; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java index 41cc7f78ca..9d9ef037db 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.gui.widget.ScrollablePhantomFluidWidget; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.misc.FluidStorage; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; @@ -12,6 +13,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; +import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; import lombok.Getter; @@ -101,6 +103,31 @@ public void setBlackList(boolean blackList) { onUpdated.accept(this); } + public void setMaxTransferSize(int transferRate) { + transferRate = Mth.clamp(transferRate, 1, Integer.MAX_VALUE); + if (this.maxStackSize != transferRate) { + this.maxStackSize = transferRate; + onUpdated.accept(this); + } + } + + public int getMaxTransferSize() { + return isBlackList ? 1 : (int) this.maxStackSize; + } + + @Override + public int getTransferLimit(FluidStack fluidStack, int transferSize) { + long limit = 0; + + for (int i = 0; i < this.matches.length; i++) { + var fluid = this.matches[i]; + if (fluid != null && fluid.isFluidEqual(fluidStack)) { + limit = fluid.getAmount(); + } + } + return isBlackList ? transferSize : (int) limit; + } + public void setIgnoreNbt(boolean ingoreNbt) { this.ignoreNbt = ingoreNbt; onUpdated.accept(this); @@ -191,4 +218,19 @@ public void setMaxStackSize(long maxStackSize) { match.setAmount(Math.min(match.getAmount(), maxStackSize)); } } + + @Override + public MatchResult apply(FluidStack fluidStack) { + int index = -1; + FluidStack returnable = FluidStack.empty(); + for (int i = 0; i < matches.length; i++) { + var fluid = matches[i]; + if (fluid != null && fluid.isFluidEqual(fluidStack)) { + index = i; + returnable = fluid.copy(); + break; + } + } + return MatchResult.create(index != -1, returnable, index); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java index 5c21b8f945..a355159376 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleItemFilter.java @@ -13,6 +13,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; +import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; import lombok.Getter; @@ -101,11 +102,31 @@ public void setBlackList(boolean blackList) { onUpdated.accept(this); } + @Override + public int getMaxTransferSize() { + return maxStackSize; + } + + @Override + public void setMaxTransferSize(int maxTransferSize) { + maxTransferSize = Mth.clamp(maxTransferSize, 1, Integer.MAX_VALUE); + if (this.maxStackSize != maxTransferSize) { + this.maxStackSize = maxTransferSize; + onUpdated.accept(this); + } + } + public void setIgnoreNbt(boolean ingoreNbt) { this.ignoreNbt = ingoreNbt; onUpdated.accept(this); } + @Override + public int getTransferLimit(ItemStack stack, int transferSize) { + int matchedSlot = itemFilterMatch(ignoreNbt, stack); + return getTransferLimit(matchedSlot, transferSize); + } + public WidgetGroup openConfigurator(int x, int y) { WidgetGroup group = new WidgetGroup(x, y, 18 * 3 + 25, 18 * 3); // 80 55 for (int i = 0; i < 3; i++) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java index b7aa58325b..500599f3c9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java @@ -1,10 +1,13 @@ package com.gregtechceu.gtceu.api.cover.filter; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.gregtechceu.gtceu.utils.OreDictExprFilter; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import lombok.Getter; import net.minecraft.nbt.CompoundTag; +import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; @@ -22,6 +25,9 @@ public class TagFluidFilter extends TagFilter implement private final Object2BooleanMap cache = new Object2BooleanOpenHashMap<>(); + @Getter + protected long maxStackSize = 1L; + protected TagFluidFilter() {} public static TagFluidFilter loadFilter(ItemStack itemStack) { @@ -45,6 +51,20 @@ public CompoundTag saveFilter() { return tag; } + @Override + public int getMaxTransferSize() { + return (int) maxStackSize; + } + + @Override + public void setMaxTransferSize(int transferRate) { + transferRate = Mth.clamp(transferRate, 1, Integer.MAX_VALUE); + if (this.maxStackSize != transferRate) { + this.maxStackSize = transferRate; + onUpdated.accept(this); + } + } + public void setOreDict(String oreDict) { cache.clear(); super.setOreDict(oreDict); @@ -71,4 +91,10 @@ public long testFluidAmount(FluidStack fluidStack) { public boolean supportsAmounts() { return false; } + + @Override + public MatchResult apply(FluidStack fluidStack) { + var match = OreDictExprFilter.matchesOreDict(matchRules, fluidStack); + return MatchResult.create(match != isBlackList(), match ? fluidStack.copy() : FluidStack.empty(), -1); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java index ecc5f91bb5..c43ffa947d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java @@ -1,8 +1,12 @@ package com.gregtechceu.gtceu.api.cover.filter; +import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.gregtechceu.gtceu.utils.OreDictExprFilter; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import lombok.Getter; import net.minecraft.nbt.CompoundTag; +import net.minecraft.util.Mth; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -20,6 +24,9 @@ public class TagItemFilter extends TagFilter implements I private final Object2BooleanMap cache = new Object2BooleanOpenHashMap<>(); + @Getter + protected int maxStackSize = 1; + protected TagItemFilter() {} public static TagItemFilter loadFilter(ItemStack itemStack) { @@ -43,6 +50,20 @@ public CompoundTag saveFilter() { return tag; } + @Override + public int getMaxTransferSize() { + return maxStackSize; + } + + @Override + public void setMaxTransferSize(int transferRate) { + transferRate = Mth.clamp(transferRate, 1, Integer.MAX_VALUE); + if (this.maxStackSize != transferRate) { + this.maxStackSize = transferRate; + onUpdated.accept(this); + } + } + public void setOreDict(String oreDict) { cache.clear(); super.setOreDict(oreDict); @@ -69,4 +90,10 @@ public int testItemCount(ItemStack itemStack) { public boolean supportsAmounts() { return false; } + + @Override + public MatchResult apply(ItemStack itemStack) { + var match = OreDictExprFilter.matchesOreDict(matchRules, itemStack); + return MatchResult.create(match != isBlackList(), match ? itemStack.copy() : ItemStack.EMPTY, -1); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java index d39c0707ae..04ae1e6775 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PipeNetProperties.java @@ -13,7 +13,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelAccessor; import it.unimi.dsi.fastutil.objects.Object2ObjectRBTreeMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java index da49123579..96dba4fa1c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/PropertyKey.java @@ -15,7 +15,6 @@ public class PropertyKey { public static final PropertyKey ORE = new PropertyKey<>("ore", OreProperty.class); public static final PropertyKey TOOL = new PropertyKey<>("tool", ToolProperty.class); public static final PropertyKey ROTOR = new PropertyKey<>("rotor", RotorProperty.class); - public static final PropertyKey WIRE = new PropertyKey<>("wire", WireProperties.class); public static final PropertyKey WOOD = new PropertyKey<>("wood", WoodProperty.class); public static final PropertyKey HAZARD = new PropertyKey<>("hazard", HazardProperty.class); diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java deleted file mode 100644 index bc7c5fab79..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/WireProperties.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.gregtechceu.gtceu.api.data.chemical.material.properties; - -import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; - -import java.util.Objects; - -import static com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialFlags.GENERATE_FOIL; - -public class WireProperties implements IMaterialProperty { - - private int voltage; - private int amperage; - private int lossPerBlock; - private int superconductorCriticalTemperature; - private boolean isSuperconductor; - - public WireProperties(int voltage, int baseAmperage, int lossPerBlock) { - this(voltage, baseAmperage, lossPerBlock, false); - } - - public WireProperties(int voltage, int baseAmperage, int lossPerBlock, boolean isSuperCon) { - this(voltage, baseAmperage, lossPerBlock, isSuperCon, 0); - } - - public WireProperties(int voltage, int baseAmperage, int lossPerBlock, boolean isSuperCon, - int criticalTemperature) { - this.voltage = voltage; - this.amperage = baseAmperage; - this.lossPerBlock = isSuperCon ? 0 : lossPerBlock; - this.superconductorCriticalTemperature = isSuperCon ? criticalTemperature : 0; - this.isSuperconductor = isSuperCon; - } - - public WireProperties copy() { - return new WireProperties(voltage, amperage, lossPerBlock, isSuperconductor, superconductorCriticalTemperature); - } - - /** - * Default values constructor - */ - public WireProperties() { - this(8, 1, 1, false); - } - - /** - * Retrieves the current wire voltage - * - * @return The current wire voltage - */ - public int getVoltage() { - return voltage; - } - - /** - * Sets the current wire voltage - * - * @param voltage The new wire voltage - */ - public void setVoltage(int voltage) { - this.voltage = voltage; - } - - /** - * Retrieves the current wire amperage - * - * @return The current wire amperage - */ - public int getAmperage() { - return amperage; - } - - /** - * Sets the current wire amperage - * - * @param amperage The new current wire amperage - */ - public void setAmperage(int amperage) { - this.amperage = amperage; - } - - /** - * Retrieves the current wire loss per block - * - * @return The current wire loss per block - */ - public int getLossPerBlock() { - return lossPerBlock; - } - - /** - * Sets the current wire loss per block - * - * @param lossPerBlock The new wire loss per block - */ - public void setLossPerBlock(int lossPerBlock) { - this.lossPerBlock = lossPerBlock; - } - - /** - * If the current wire is a Superconductor wire - * - * @return {@code true} if the current wire is a Superconductor - */ - public boolean isSuperconductor() { - return isSuperconductor; - } - - /** - * Sets the current wire to a superconductor wire - * - * @param isSuperconductor The new wire superconductor status - */ - public void setSuperconductor(boolean isSuperconductor) { - this.isSuperconductor = isSuperconductor; - } - - /** - * Retrieves the critical temperature of the superconductor (the temperature at which the superconductive phase - * transition happens) - * - * @return Critical temperature of the material - */ - public int getSuperconductorCriticalTemperature() { - return superconductorCriticalTemperature; - } - - /** - * Sets the material's critical temperature - * - * @param criticalTemperature The new critical temperature - */ - public void setSuperconductorCriticalTemperature(int criticalTemperature) { - this.superconductorCriticalTemperature = this.isSuperconductor ? criticalTemperature : 0; - } - - @Override - public void verifyProperty(MaterialProperties properties) { - properties.ensureSet(PropertyKey.DUST, true); - if (properties.hasProperty(PropertyKey.INGOT)) { - // Ensure all Materials with Cables and voltage tier IV or above have a Foil for recipe generation - Material thisMaterial = properties.getMaterial(); - if (!isSuperconductor && voltage >= GTValues.V[GTValues.IV] && !thisMaterial.hasFlag(GENERATE_FOIL)) { - thisMaterial.addFlags(GENERATE_FOIL); - } - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof WireProperties that)) return false; - return voltage == that.voltage && - amperage == that.amperage && - lossPerBlock == that.lossPerBlock && - superconductorCriticalTemperature == that.superconductorCriticalTemperature && - isSuperconductor == that.isSuperconductor; - } - - @Override - public int hashCode() { - return Objects.hash(voltage, amperage, lossPerBlock); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java index c531987318..5fba6fc0f5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java @@ -1095,18 +1095,33 @@ public boolean doGenerateBlock(Material material) { } @FunctionalInterface - public interface MaterialRecipeHandler { + public interface PropertyMaterialRecipeHandler { void accept(TagPrefix prefix, Material material, T property, Consumer provider); } + @FunctionalInterface + public interface MaterialRecipeHandler { + + void accept(TagPrefix prefix, Material material, Consumer provider); + } + public void executeHandler(Consumer provider, PropertyKey propertyKey, - MaterialRecipeHandler handler) { - for (Material material : GTCEuAPI.materialManager.getRegisteredMaterials()) { + PropertyMaterialRecipeHandler handler) { + executeHandler(provider, (prefix, material, provider1) -> { if (material.hasProperty(propertyKey) && !material.hasFlag(MaterialFlags.NO_UNIFICATION) && !ChemicalHelper.get(this, material).isEmpty()) { - handler.accept(this, material, material.getProperty(propertyKey), provider); + handler.accept(this, material, material.getProperty(propertyKey), provider1); + } + }); + } + + public void executeHandler(Consumer provider, MaterialRecipeHandler handler) { + for (Material material : GTCEuAPI.materialManager.getRegisteredMaterials()) { + if (!material.hasFlag(MaterialFlags.NO_UNIFICATION) && + !ChemicalHelper.get(this, material).isEmpty()) { + handler.accept(this, material, provider); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java index 4082afb2f6..2d9a1dd02a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java @@ -6,7 +6,6 @@ import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKey; -import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKeys; import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; import com.gregtechceu.gtceu.api.registry.registrate.IGTFluidBuilder; import com.gregtechceu.gtceu.utils.GTUtil; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java index 5c47d38833..f0fcf2e187 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -20,7 +20,7 @@ public final class WorldPipeNetNode extends WorldNetNode { - private static final PipeBlockEntity FALLBACK = new PipeBlockEntity(GTBlockEntities.NEW_PIPE.get(), BlockPos.ZERO, + private static final PipeBlockEntity FALLBACK = new PipeBlockEntity(GTBlockEntities.PIPE.get(), BlockPos.ZERO, GTBlocks.MATERIAL_PIPE_BLOCKS.get(TagPrefix.pipeNormal, GTMaterials.Aluminium).getDefaultState()); @Nullable diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java index 3ea5e7bb19..fb94b5e6b9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -1,9 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import net.minecraft.core.Direction; import net.minecraft.util.StringRepresentable; import net.minecraft.world.phys.shapes.Shapes; @@ -25,6 +27,11 @@ public interface IPipeStructure extends StringRepresentable { AbstractPipeModel getModel(); + + default ResourceTexture getPipeTexture(boolean isBlock) { + return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; + } + /** * Allows for controlling what sides can be connected to based on current connections, * such as in the case of optical and laser pipes. diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java similarity index 91% rename from src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java rename to src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java index 15b229499e..d90965840d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeActivableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java @@ -14,9 +14,9 @@ import java.lang.ref.WeakReference; -public abstract class PipeActivableBlock extends PipeBlock { +public abstract class ActivablePipeBlock extends PipeBlock { - public PipeActivableBlock(BlockBehaviour.Properties properties, IPipeStructure structure) { + public ActivablePipeBlock(BlockBehaviour.Properties properties, IPipeStructure structure) { super(properties, structure); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlock.java similarity index 79% rename from src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java rename to src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlock.java index 79a140a03f..c1fb7aeebc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlock.java @@ -4,8 +4,9 @@ import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeMaterialBlockEntity; +import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTMaterials; import com.gregtechceu.gtceu.config.ConfigHolder; @@ -16,6 +17,7 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -23,11 +25,11 @@ import java.lang.ref.WeakReference; import java.util.List; -public abstract class PipeMaterialBlock extends PipeBlock { +public abstract class MaterialPipeBlock extends PipeBlock { public final Material material; - public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStructure structure, + public MaterialPipeBlock(BlockBehaviour.Properties properties, IPipeMaterialStructure structure, Material material) { super(properties, structure); this.material = material; @@ -38,9 +40,15 @@ public IPipeMaterialStructure getStructure() { return (IPipeMaterialStructure) super.getStructure(); } + @Nullable + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new MaterialPipeBlockEntity(GTBlockEntities.MATERIAL_PIPE.get(), pos, state); + } + @Override protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { - PipeMaterialBlockEntity tile = getBlockEntity(world, pos); + MaterialPipeBlockEntity tile = getBlockEntity(world, pos); if (tile != null) return tile.getMaterial().getProperty(PropertyKey.PIPENET_PROPERTIES); else return GTMaterials.Aluminium.getProperty(PropertyKey.PIPENET_PROPERTIES); } @@ -66,13 +74,13 @@ public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List(pipe)); return pipe; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index f863606663..54f82592f7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -10,13 +10,13 @@ public class MaterialPipeBlockItem extends PipeBlockItem { - public MaterialPipeBlockItem(PipeMaterialBlock block, Item.Properties properties) { + public MaterialPipeBlockItem(MaterialPipeBlock block, Item.Properties properties) { super(block, properties); } @Override - public @NotNull PipeMaterialBlock getBlock() { - return (PipeMaterialBlock) super.getBlock(); + public @NotNull MaterialPipeBlock getBlock() { + return (MaterialPipeBlock) super.getBlock(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 8c02c8e15e..85dafaa202 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -102,15 +102,6 @@ public abstract class PipeBlock extends Block implements EntityBlock { public PipeBlock(BlockBehaviour.Properties properties, IPipeStructure structure) { super(properties); this.structure = structure; - /* - * setTranslationKey(structure.getName()); - * setSoundType(SoundType.METAL); - * setHardness(2.0f); - * setHarvestLevel(getToolClass(), 1); - * setResistance(3.0f); - * setLightOpacity(1); - * disableStats(); - */ } // net logic // @@ -324,7 +315,7 @@ public static void unblockTile(@NotNull PipeBlockEntity tile, @Nullable PipeBloc } } - protected boolean allowsBlocking() { + public boolean allowsBlocking() { return true; } @@ -540,7 +531,7 @@ public PipeBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull Block @Nullable @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new PipeBlockEntity(GTBlockEntities.NEW_PIPE.get(), pos, state); + return new PipeBlockEntity(GTBlockEntities.PIPE.get(), pos, state); } @Override @@ -580,8 +571,7 @@ public void neighborChanged(BlockState state, Level level, BlockPos pos, if (tile != null) { Direction facing = GTUtil.getFacingToNeighbor(pos, neighborPos); if (facing != null) tile.onNeighborChanged(facing); - // TODO redstone - // tile.getCoverHolder().notifyBlockUpdate(); + tile.getCoverHolder().notifyBlockUpdate(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java index ac13580e4e..7ba0537ccc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java @@ -26,7 +26,7 @@ public PipeBlockItem(PipeBlock block, Item.Properties properties) { } @Override - protected boolean placeBlock(BlockPlaceContext context, BlockState state) { + public boolean placeBlock(BlockPlaceContext context, BlockState state) { if (super.placeBlock(context, state)) { ItemStack offhand = context.getPlayer().getOffhandItem(); for (int i = 0; i < DyeColor.values().length; i++) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java similarity index 89% rename from src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialBlockEntity.java rename to src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java index d26bff06ed..e2e03ddbdc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeMaterialBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.common.data.GTMaterials; import com.gregtechceu.gtceu.utils.GTUtil; @@ -18,13 +18,13 @@ import org.jetbrains.annotations.NotNull; -public class PipeMaterialBlockEntity extends PipeBlockEntity { +public class MaterialPipeBlockEntity extends PipeBlockEntity { @Persisted @DescSynced private Material material; - public PipeMaterialBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { + public MaterialPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); } @@ -44,8 +44,8 @@ public void placedBy(ItemStack stack, Player player) { } @Override - public @NotNull PipeMaterialBlock getBlockType() { - return (PipeMaterialBlock) super.getBlockType(); + public @NotNull MaterialPipeBlock getBlockType() { + return (MaterialPipeBlock) super.getBlockType(); } public void setMaterial(Material material) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 431833d3a7..4dd6ce92bc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.blockentity.ITickSubscription; import com.gregtechceu.gtceu.api.blockentity.NeighborCacheBlockEntity; +import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.IToolable; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverBehavior; @@ -19,6 +20,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.api.machine.TickableSubscription; @@ -31,12 +33,14 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; +import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; import net.minecraft.core.BlockPos; @@ -60,6 +64,8 @@ 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.BlockHitResult; +import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -87,6 +93,10 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity implements IWorldPipeNetTile, ITickSubscription, IEnhancedManaged, IAsyncAutoSyncBlockEntity, IAutoPersistBlockEntity, IToolGridHighLight, IToolable { + protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(PipeBlockEntity.class); + @Getter + public final IManagedStorage syncStorage = new FieldManagedStorage(this); + public static final int DEFAULT_COLOR = 0xFFFFFFFF; public static final int UPDATE_PIPE_LOGIC = 0; @@ -99,12 +109,15 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity @Persisted @DescSynced + @Getter private byte connectionMask; @Persisted @DescSynced + @Getter private byte renderMask; @Persisted @DescSynced + @Getter private byte blockedMask; @Persisted @DescSynced @@ -226,10 +239,6 @@ public boolean renderClosed(Direction facing) { return (this.renderMask & 1 << facing.ordinal()) > 0; } - public byte getConnectionMask() { - return connectionMask; - } - public void setBlocked(Direction facing) { this.blockedMask |= (byte) (1 << facing.ordinal()); } @@ -242,10 +251,6 @@ public boolean isBlocked(Direction facing) { return (this.blockedMask & 1 << facing.ordinal()) > 0; } - public byte getBlockedMask() { - return blockedMask; - } - // paint // public int getPaintingColor() { @@ -671,12 +676,11 @@ public void markAsDirty() { @Override public @NotNull ModelData getModelData() { byte frameMask = 0; - byte connectionMask = this.connectionMask; for (Direction facing : GTUtil.DIRECTIONS) { CoverBehavior cover = getCoverHolder().getCoverAtSide(facing); if (cover != null) { frameMask |= (byte) (1 << facing.ordinal()); - if (cover.forcePipeRenderConnection()) connectionMask |= (byte) (1 << facing.ordinal()); + if (cover.forcePipeRenderConnection()) this.connectionMask |= (byte) (1 << facing.ordinal()); } } return ModelData.builder() @@ -693,7 +697,7 @@ public void markAsDirty() { public void getCoverBoxes(Consumer consumer) { for (Direction facing : GTUtil.DIRECTIONS) { if (getCoverHolder().hasCover(facing)) { - consumer.accept(CoverRendererBuilder.PLATE_AABBS.get(facing)); + consumer.accept(Shapes.create(CoverRendererBuilder.PLATE_AABBS.get(facing))); } } } @@ -737,17 +741,68 @@ public void setNeighborsToFire() { @Override public Pair<@Nullable GTToolType, InteractionResult> onToolClick(@NotNull Set toolTypes, ItemStack itemStack, UseOnContext context) { - return null; - } + // the side hit from the machine grid + var playerIn = context.getPlayer(); + if (playerIn == null) return Pair.of(null, InteractionResult.PASS); + + var hand = context.getHand(); + var hitResult = new BlockHitResult(context.getClickLocation(), context.getClickedFace(), + context.getClickedPos(), false); + Direction gridSide = ICoverable.determineGridSideHit(hitResult); + CoverBehavior coverBehavior = gridSide == null ? null : covers.getCoverAtSide(gridSide); + if (gridSide == null) gridSide = hitResult.getDirection(); + + // Prioritize covers where they apply (Screwdriver, Soft Mallet) + if (toolTypes.contains(GTToolType.SCREWDRIVER)) { + if (coverBehavior != null) { + return Pair.of(GTToolType.SCREWDRIVER, coverBehavior.onScrewdriverClick(playerIn, hand, hitResult)); + } + } else if (toolTypes.contains(GTToolType.SOFT_MALLET)) { + if (coverBehavior != null) { + return Pair.of(GTToolType.SOFT_MALLET, coverBehavior.onSoftMalletClick(playerIn, hand, hitResult)); + } + } else if (toolTypes.contains(this.getBlockType().getToolClass())) { + if (playerIn.isShiftKeyDown() && this.getBlockType().allowsBlocking()) { + boolean isBlocked = this.isBlocked(gridSide); + if (isBlocked) { + this.setUnblocked(gridSide); + } else { + this.setBlocked(gridSide); + } + } else { + boolean isOpen = this.isConnected(gridSide); + if (isOpen) { + this.setDisconnected(gridSide); + } else { + this.setConnected(gridSide, true); + } + } + playerIn.swing(hand); + return Pair.of(this.getBlockType().getToolClass(), InteractionResult.CONSUME); + } else if (toolTypes.contains(GTToolType.CROWBAR)) { + if (coverBehavior != null) { + if (isServerSide()) { + covers.removeCover(gridSide, playerIn); + playerIn.swing(hand); + return Pair.of(GTToolType.CROWBAR, InteractionResult.CONSUME); + } + } else { + if (frameMaterial != null) { + Block.popResource(getLevel(), getBlockPos(), + GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, frameMaterial).asStack()); + frameMaterial = null; + playerIn.swing(hand); + return Pair.of(GTToolType.CROWBAR, InteractionResult.CONSUME); + } + } + } - @Override - public ManagedFieldHolder getFieldHolder() { - return null; + return Pair.of(null, InteractionResult.PASS); } @Override - public IManagedStorage getSyncStorage() { - return null; + public ManagedFieldHolder getFieldHolder() { + return MANAGED_FIELD_HOLDER; } @Override @@ -755,6 +810,6 @@ public void onChanged() {} @Override public IManagedStorage getRootStorage() { - return null; + return syncStorage; } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/gui/fancy/FancyMachineUIWidget.java b/src/main/java/com/gregtechceu/gtceu/api/gui/fancy/FancyMachineUIWidget.java index fcd8798aad..ab12f8a0c5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/gui/fancy/FancyMachineUIWidget.java +++ b/src/main/java/com/gregtechceu/gtceu/api/gui/fancy/FancyMachineUIWidget.java @@ -42,11 +42,13 @@ public class FancyMachineUIWidget extends WidgetGroup { protected final IFancyUIProvider mainPage; - /* - * Current Page: The page visible in the UI - * Current Home Page: The currently selected multiblock part's home page. + /** + * The page visible in the UI */ protected IFancyUIProvider currentPage; + /** + * The currently selected multiblock part's home page. + */ protected IFancyUIProvider currentHomePage; protected List allPages; diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java index c2d4ad8dec..b4a20311d4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java @@ -1,6 +1,8 @@ package com.gregtechceu.gtceu.api.item; import com.gregtechceu.gtceu.api.block.IMachineBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.machine.MachineDefinition; import com.lowdragmc.lowdraglib.client.renderer.IItemRendererProvider; @@ -44,7 +46,6 @@ public IRenderer getRenderer(ItemStack stack) { } @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) protected boolean placeBlock(BlockPlaceContext context, BlockState state) { Level level = context.getLevel(); BlockPos pos = context.getClickedPos(); @@ -55,11 +56,10 @@ protected boolean placeBlock(BlockPlaceContext context, BlockState state) { if (!level.isClientSide) { BlockPos possiblePipe = pos.offset(side.getOpposite().getNormal()); Block block = level.getBlockState(possiblePipe).getBlock(); - if (block instanceof PipeBlock) { - IPipeNode pipeTile = ((PipeBlock) block).getPipeTile(level, possiblePipe); - if (pipeTile != null && ((PipeBlock) block).canPipeConnectToBlock(pipeTile, side.getOpposite(), - level.getBlockEntity(pos))) { - pipeTile.setConnection(side, true, false); + if (block instanceof PipeBlock pipeBlock) { + PipeBlockEntity pipeTile = pipeBlock.getBlockEntity(level, possiblePipe); + if (pipeTile != null && pipeTile.canConnectTo(side.getOpposite())) { + pipeTile.setConnected(side, true); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java b/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java index 05734bc807..27d0d0589c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java +++ b/src/main/java/com/gregtechceu/gtceu/api/pattern/Predicates.java @@ -9,6 +9,7 @@ import com.gregtechceu.gtceu.api.capability.recipe.ItemRecipeCapability; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.machine.multiblock.IBatteryData; import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.pattern.error.PatternStringError; @@ -258,7 +259,7 @@ public static TraceabilityPredicate frames(Material... frameMaterials) { .toArray(Block[]::new)) .or(new TraceabilityPredicate(blockWorldState -> { BlockEntity tileEntity = blockWorldState.getBlockEntity(); - if (!(tileEntity instanceof IPipeNode pipeNode)) { + if (!(tileEntity instanceof PipeBlockEntity pipeNode)) { return false; } return ArrayUtils.contains(frameMaterials, pipeNode.getFrameMaterial()); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java index e75cedfb56..21a133bf26 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java @@ -2,6 +2,8 @@ import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; @@ -141,10 +143,10 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, } // draw pipe connection grid highlight - var pipeType = held.getItem() instanceof PipeBlockItem pipeBlockItem ? pipeBlockItem.getBlock().pipeType : + var pipeStructure = held.getItem() instanceof PipeBlockItem pipeBlockItem ? pipeBlockItem.getBlock().getStructure() : null; - if (pipeType instanceof IPipeType type && blockEntity instanceof PipeBlockEntity pipeBlockEntity && - pipeBlockEntity.getPipeType().type().equals(type.type())) { + if (pipeStructure != null && blockEntity instanceof PipeBlockEntity pipeBlockEntity && + pipeBlockEntity.getStructure() == pipeStructure) { Vec3 pos = camera.getPosition(); poseStack.pushPose(); poseStack.translate(-pos.x, -pos.y, -pos.z); @@ -152,7 +154,7 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, RenderSystem.lineWidth(3); drawGridOverlays(poseStack, buffer, target, side -> level.isEmptyBlock(blockPos.relative(side)) ? - pipeBlockEntity.getPipeTexture(true) : null); + pipeStructure.getPipeTexture(true) : null); poseStack.popPose(); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java index 71ac14e596..26a2b0ccab 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java @@ -3,6 +3,8 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.client.model.ModelUtil; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.FacadeCover; import com.gregtechceu.gtceu.common.item.FacadeItemBehaviour; import com.gregtechceu.gtceu.utils.GTUtil; @@ -25,6 +27,7 @@ import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; @@ -36,6 +39,7 @@ import org.joml.AxisAngle4d; import org.joml.Quaternionf; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -141,4 +145,23 @@ public void renderCover(List quads, Direction side, RandomSource rand } } } + + public static CoverRenderer createRenderer(final BlockAndTintGetter world, BlockPos pos, final BlockState state) { + BlockRenderDispatcher dispatcher = Minecraft.getInstance().getBlockRenderer(); + + BakedModel model = dispatcher.getBlockModel(state); + + return (quads, side, rand, renderPlate, renderBackside, modelData, data, renderType) -> { + if (renderType != RenderType.cutoutMipped()) return; + + AABB cube = CoverRendererBuilder.PLATE_AABBS.get(side); + for (BakedQuad quad : ModelUtil.getBakedModelQuads(model, world, pos, state, side, rand)) { + quads.add(FaceQuad.builder(side.getOpposite(), quad.getSprite()) + .cube(cube) + .shade(quad.isShade()) + .tintIndex(quad.getTintIndex()) + .bake()); + } + }; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index c89a61546b..d9ab3b1866 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -83,14 +83,14 @@ public List getQuads(@Nullable BlockState state, @Nullable Direction safeByte(modelData.get(CLOSED_MASK_PROPERTY)), safeByte(modelData.get(BLOCKED_MASK_PROPERTY)), data, modelData.get(FRAME_MATERIAL_PROPERTY), safeByte(modelData.get(FRAME_MASK_PROPERTY)), coverMask); - if (rendererPackage != null) renderCovers(quads, rendererPackage, rand, modelData); + if (rendererPackage != null) renderCovers(quads, rendererPackage, rand, modelData, renderType); return quads; } return Collections.emptyList(); } protected void renderCovers(List quads, @NotNull CoverRendererPackage rendererPackage, - RandomSource rand, @NotNull ModelData data) { + RandomSource rand, @NotNull ModelData data, RenderType renderType) { int color = safeInt(data.get(COLOR_PROPERTY)); if (data.get(AbstractPipeModel.MATERIAL_PROPERTY) != null) { Material material = data.get(AbstractPipeModel.MATERIAL_PROPERTY); @@ -102,7 +102,7 @@ protected void renderCovers(List quads, @NotNull CoverRendererPackage } } } - rendererPackage.addQuads(quads, rand, new ColorData(color)); + rendererPackage.addQuads(quads, rand, data, new ColorData(color), renderType); } protected ColorData computeColorData(@NotNull ModelData data) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java index 4b1af6f098..8df9399386 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java @@ -4,8 +4,8 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconSet; import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.client.renderer.pipe.cache.ExtraCappedSQC; import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; @@ -134,7 +134,7 @@ protected StructureQuadCache constructForKey(CacheKey key) { LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; - Material mater = block instanceof PipeMaterialBlock mat ? mat.material : null; + Material mater = block instanceof MaterialPipeBlock mat ? mat.material : null; return new PipeItemModel<>(this, new CacheKey(block.getStructure().getRenderThickness()), new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : PipeBlockEntity.DEFAULT_COLOR, DEFAULT_INSULATION_COLOR)); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java index 4b45471fbe..68e4704f92 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java @@ -8,13 +8,16 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; + import com.lowdragmc.lowdraglib.client.model.ModelFactory; + import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraftforge.client.model.data.ModelData; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -57,7 +60,8 @@ public SpriteInformation getParticleSprite(@Nullable Material material) { } @Override - protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity) { + protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, + LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; return new PipeItemModel<>(this, new CacheKey(block.getStructure().getRenderThickness()), new ColorData()); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java index 93064cb586..c9436fe759 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -3,8 +3,8 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.client.renderer.pipe.cache.BlockableSQC; import com.gregtechceu.gtceu.client.renderer.pipe.cache.RestrictiveSQC; @@ -139,7 +139,7 @@ protected StructureQuadCache constructForKey(WoodCacheKey key) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; Material mater = null; - boolean wood = block instanceof PipeMaterialBlock mat && (mater = mat.material) != null && + boolean wood = block instanceof MaterialPipeBlock mat && (mater = mat.material) != null && mater.hasProperty(PropertyKey.WOOD); return new PipeItemModel<>(this, new WoodCacheKey(block.getStructure().getRenderThickness(), wood), new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java index a564027989..cea3cec916 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRenderer.java @@ -2,11 +2,13 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelData; import java.util.EnumSet; import java.util.List; @@ -17,5 +19,5 @@ public interface CoverRenderer { void addQuads(List quads, Direction side, RandomSource rand, EnumSet renderPlate, boolean renderBackside, - ColorData data); + ModelData modelData, ColorData data, RenderType renderType); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java index f0ad5a65aa..c38c358727 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java @@ -19,6 +19,7 @@ import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -44,7 +45,7 @@ public class CoverRendererBuilder { private static final ColorQuadCache PLATE_QUADS; private static final EnumMap PLATE_COORDS = new EnumMap<>(Direction.class); - public static final EnumMap PLATE_AABBS = new EnumMap<>(Direction.class); + public static final EnumMap PLATE_AABBS = new EnumMap<>(Direction.class); private static final EnumMap> PLATE_BOXES = new EnumMap<>(Direction.class); private static final EnumMap> OVERLAY_BOXES_1 = new EnumMap<>( Direction.class); @@ -55,17 +56,16 @@ public class CoverRendererBuilder { static { for (Direction facing : GTUtil.DIRECTIONS) { - PLATE_AABBS.put(facing, ICoverable.getCoverPlateBox(facing, 1d / 16)); + PLATE_AABBS.put(facing, ICoverable.getCoverPlateBox(facing, 1d / 16).bounds()); } for (var value : PLATE_AABBS.entrySet()) { // make sure that plates render slightly below any normal block quad - // TODO replace .bounds() calls with actual VoxelShape support PLATE_BOXES.put(value.getKey(), - QuadHelper.fullOverlay(value.getKey(), value.getValue().bounds(), -OVERLAY_DIST_1)); + QuadHelper.fullOverlay(value.getKey(), value.getValue(), -OVERLAY_DIST_1)); OVERLAY_BOXES_1.put(value.getKey(), - QuadHelper.fullOverlay(value.getKey(), value.getValue().bounds(), OVERLAY_DIST_1)); + QuadHelper.fullOverlay(value.getKey(), value.getValue(), OVERLAY_DIST_1)); OVERLAY_BOXES_2.put(value.getKey(), - QuadHelper.fullOverlay(value.getKey(), value.getValue().bounds(), OVERLAY_DIST_2)); + QuadHelper.fullOverlay(value.getKey(), value.getValue(), OVERLAY_DIST_2)); } PLATE_QUADS = buildPlates(new SpriteInformation(defaultPlateSprite(), 0)); } @@ -156,7 +156,7 @@ public CoverRenderer build() { spriteEmissive))); } - return (quads, side, rand, renderPlate, renderBackside, data) -> { + return (quads, side, rand, renderPlate, renderBackside, modelData, data, renderType) -> { addPlates(quads, getPlates(side, data, plateQuads), renderPlate); quads.add(spriteQuads.get(side).getLeft()); if (renderBackside) quads.add(spriteQuads.get(side).getRight()); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java index 2c33b52716..9d2c677cd9 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java @@ -2,11 +2,13 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.model.data.ModelProperty; import org.jetbrains.annotations.NotNull; @@ -36,13 +38,13 @@ public void addRenderer(CoverRenderer renderer, @NotNull Direction facing) { plates.remove(facing); } - public void addQuads(List quads, RandomSource rand, ColorData data) { + public void addQuads(List quads, RandomSource rand, ModelData modelData, ColorData data, RenderType renderType) { for (var renderer : renderers.entrySet()) { EnumSet plates = EnumSet.copyOf(this.plates); // force front and back plates to render plates.add(renderer.getKey()); plates.add(renderer.getKey().getOpposite()); - renderer.getValue().addQuads(quads, renderer.getKey(), rand, plates, renderBackside, data); + renderer.getValue().addQuads(quads, renderer.getKey(), rand, plates, renderBackside, modelData, data, renderType); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java index 3fc282952b..bc88859865 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import net.minecraft.core.Direction; public class ComputerMonitorCover extends CoverBehavior { @@ -13,4 +14,9 @@ public ComputerMonitorCover(CoverDefinition definition, ICoverable coverHolder, } // No implementation here, this cover is just for decorative purposes + + @Override + protected CoverRenderer buildRenderer() { + return null; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java index 6b217927dd..00316b3d8b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java @@ -285,7 +285,7 @@ protected int performTransfer(@NotNull IItemTransfer sourceHandler, @NotNull IIt @NotNull IntUnaryOperator maxTransfer, @Nullable BiConsumer transferReport) { ItemFilter filter = filterHandler.getFilter(); - byFilterSlot = byFilterSlot && filter != ItemFilter.EMPTY; // can't be by filter slot if there is no filter + byFilterSlot = byFilterSlot && getFilterHandler().isFilterPresent(); // can't be by filter slot if there is no filter Int2IntArrayMap extractableByFilterSlot = new Int2IntArrayMap(); Int2ObjectArrayMap> filterSlotToMergability = new Int2ObjectArrayMap<>(); for (int i = 0; i < sourceHandler.getSlots(); i++) { @@ -293,7 +293,7 @@ protected int performTransfer(@NotNull IItemTransfer sourceHandler, @NotNull IIt int extracted = stack.getCount(); if (extracted == 0) continue; MatchResult match = null; - if (filter == ItemFilter.EMPTY || (match = filter.match(stack)).isMatched()) { + if (!getFilterHandler().isFilterPresent() || (match = filter.match(stack)).isMatched()) { int filterSlot = -1; if (byFilterSlot) { filterSlot = match.getFilterIndex(); @@ -444,7 +444,7 @@ public int insertToHandler(@NotNull ItemTestObject testObject, int amount, @NotN io == IO.IN) // insert to handler is an extract from us return IItemTransferController.super.insertToHandler(testObject, amount, destHandler, simulate); ItemFilter filter = getFilterHandler().getFilter(); - if (filter == ItemFilter.EMPTY || filter.test(testObject.recombine())) { + if (getFilterHandler().isFilterPresent() || filter.test(testObject.recombine())) { return IItemTransferController.super.insertToHandler(testObject, amount, destHandler, simulate); } else return amount; } @@ -457,7 +457,7 @@ public int extractFromHandler(@NotNull ItemTestObject testObject, int amount, @N io == IO.OUT) // extract from handler is an insert to us return IItemTransferController.super.extractFromHandler(testObject, amount, sourceHandler, simulate); ItemFilter filter = getFilterHandler().getFilter(); - if (filter == ItemFilter.EMPTY || filter.test(testObject.recombine())) { + if (!getFilterHandler().isFilterPresent() || filter.test(testObject.recombine())) { return IItemTransferController.super.extractFromHandler(testObject, amount, sourceHandler, simulate); } else return 0; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java b/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java index a8517d07c5..3467cad2b5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/CoverSolarPanel.java @@ -1,18 +1,23 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.IEnergyContainer; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.machine.TickableSubscription; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class CoverSolarPanel extends CoverBehavior { @@ -40,8 +45,13 @@ public void onRemoved() { } @Override - public boolean canAttach() { - return attachedSide == Direction.UP && getEnergyContainer() != null; + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_solar_panel"), null).build(); + } + + @Override + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return side == Direction.UP && coverable.getCapability(GTCapability.CAPABILITY_ENERGY_CONTAINER).isPresent(); } protected void update() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java index 6a65b59998..fe0fd44e0f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FacadeCover.java @@ -3,6 +3,8 @@ import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.cover.FacadeCoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.common.item.FacadeItemBehaviour; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; @@ -73,6 +75,11 @@ public boolean forcePipeRenderConnection() { return false; } + @Override + protected CoverRenderer buildRenderer() { + return FacadeCoverRenderer.createRenderer(coverHolder.getLevel(), coverHolder.getPos(), facadeState); + } + @Nullable public BlockState getAppearance(BlockState sourceState, BlockPos sourcePos) { return facadeState; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java index 19232c0cf6..fcd9be0ddf 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java @@ -1,11 +1,14 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.IUICover; import com.gregtechceu.gtceu.api.cover.filter.FluidFilter; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; @@ -13,6 +16,8 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; @@ -32,8 +37,13 @@ public FluidFilterCover(CoverDefinition definition, ICoverable coverHolder, Dire } @Override - public boolean canAttach() { - return FluidTransferHelper.getFluidTransfer(coverHolder.getLevel(), coverHolder.getPos(), attachedSide) != null; + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(ForgeCapabilities.FLUID_HANDLER).isPresent(); + } + + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_filter"), null).build(); } public FluidFilter getFluidFilter() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java index 15d8e249b0..c23d58953e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java @@ -4,26 +4,42 @@ import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.filter.FluidFilter; import com.gregtechceu.gtceu.api.cover.filter.SimpleFluidFilter; +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.api.graphnet.pipenet.traverse.SimpleTileRoundRobinData; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; import com.gregtechceu.gtceu.api.gui.widget.LongInputWidget; import com.gregtechceu.gtceu.api.gui.widget.NumberInputWidget; import com.gregtechceu.gtceu.common.cover.data.BucketMode; import com.gregtechceu.gtceu.common.cover.data.TransferMode; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidEQTraverseData; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidRRTraverseData; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidTraverseData; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.IFluidTransferController; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import lombok.Getter; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.fluids.capability.IFluidHandler; import org.jetbrains.annotations.NotNull; -import java.util.Map; +import javax.annotation.ParametersAreNonnullByDefault; +import java.util.function.IntToLongFunction; +@ParametersAreNonnullByDefault public class FluidRegulatorCover extends PumpCover { private static final long MAX_STACK_SIZE = 2_048_000_000; // Capacity of quantum tank IX @@ -32,19 +48,14 @@ public class FluidRegulatorCover extends PumpCover { @DescSynced @Getter private TransferMode transferMode = TransferMode.TRANSFER_ANY; - - @Persisted - @DescSynced - @Getter - private BucketMode transferBucketMode = BucketMode.MILLI_BUCKET; + protected boolean noTransferDueToMinimum = false; @Persisted @DescSynced @Getter protected long globalTransferSizeMillibuckets; - protected long fluidTransferBuffered = 0L; private NumberInputWidget transferSizeInput; - private EnumSelectorWidget transferBucketModeInput; + private EnumSelectorWidget bucketModeInput; public FluidRegulatorCover(CoverDefinition definition, ICoverable coverHolder, Direction attachedSide, int tier) { super(definition, coverHolder, attachedSide, tier); @@ -55,120 +66,90 @@ public FluidRegulatorCover(CoverDefinition definition, ICoverable coverHolder, D ////////////////////////////////////// @Override - protected long doTransferFluidsInternal(IFluidTransfer source, IFluidTransfer destination, - long platformTransferLimit) { - return switch (transferMode) { - case TRANSFER_ANY -> transferAny(source, destination, platformTransferLimit); - case TRANSFER_EXACT -> transferExact(source, destination, platformTransferLimit); - case KEEP_EXACT -> keepExact(source, destination, platformTransferLimit); - }; - } - - private long transferExact(IFluidTransfer source, IFluidTransfer destination, long platformTransferLimit) { - long fluidLeftToTransfer = platformTransferLimit; - - for (int slot = 0; slot < source.getTanks(); slot++) { - if (fluidLeftToTransfer <= 0L) - break; - - FluidStack sourceFluid = source.getFluidInTank(slot).copy(); - long supplyAmount = getFilteredFluidAmount(sourceFluid) * MILLIBUCKET_SIZE; - - // If the remaining transferrable amount in this operation is not enough to transfer the full stack size, - // the remaining amount for this operation will be buffered and added to the next operation's maximum. - if (fluidLeftToTransfer + fluidTransferBuffered < supplyAmount) { - this.fluidTransferBuffered += fluidLeftToTransfer; - fluidLeftToTransfer = 0L; - break; + protected void refreshBuffer(long transferRate) { + if (this.transferMode == TransferMode.TRANSFER_EXACT && noTransferDueToMinimum) { + FluidFilter filter = this.getFilterHandler().getFilter(); + if (filter != FluidFilter.EMPTY) { + this.noTransferDueToMinimum = false; + this.milliBucketsLeftToTransferLastSecond += transferRate; + int max = filter.getMaxTransferSize(); + if (this.milliBucketsLeftToTransferLastSecond > max) { + this.milliBucketsLeftToTransferLastSecond = max; + } + return; } - - if (sourceFluid.isEmpty() || supplyAmount <= 0L) - continue; - - sourceFluid.setAmount(supplyAmount); - FluidStack drained = source.drain(sourceFluid, true); - - if (drained.isEmpty() || drained.getAmount() < supplyAmount) - continue; - - long insertableAmount = destination.fill(drained.copy(), true); - if (insertableAmount <= 0) - continue; - - drained.setAmount(insertableAmount); - drained = source.drain(drained, false); - - if (!drained.isEmpty()) { - destination.fill(drained, false); - fluidLeftToTransfer -= (drained.getAmount() - fluidTransferBuffered); - } - - fluidTransferBuffered = 0L; } - - return platformTransferLimit - fluidLeftToTransfer; + super.refreshBuffer(transferRate); } - private long keepExact(IFluidTransfer source, IFluidTransfer destination, long platformTransferLimit) { - long fluidLeftToTransfer = platformTransferLimit; - - final Map sourceAmounts = enumerateDistinctFluids(source, TransferDirection.EXTRACT); - final Map destinationAmounts = enumerateDistinctFluids(destination, TransferDirection.INSERT); - - for (FluidStack fluidStack : sourceAmounts.keySet()) { - if (fluidLeftToTransfer <= 0L) - break; - - long amountToKeep = getFilteredFluidAmount(fluidStack) * MILLIBUCKET_SIZE; - long amountInDest = destinationAmounts.getOrDefault(fluidStack, 0L); - if (amountInDest >= amountToKeep) - continue; - - FluidStack fluidToMove = fluidStack.copy(); - fluidToMove.setAmount(Math.min(fluidLeftToTransfer, amountToKeep - amountInDest)); - if (fluidToMove.getAmount() <= 0L) - continue; - - FluidStack drained = source.drain(fluidToMove, true); - long fillableAmount = destination.fill(drained, true); - if (fillableAmount <= 0L) - continue; - - fluidToMove.setAmount(Math.min(fluidToMove.getAmount(), fillableAmount)); - - drained = source.drain(fluidToMove, false); - long movedAmount = destination.fill(drained, false); - - fluidLeftToTransfer -= movedAmount; + @Override + protected void performTransferOnUpdate(@NotNull IFluidTransfer sourceHandler, @NotNull IFluidTransfer destHandler) { + if (transferMode == TransferMode.TRANSFER_ANY) { + super.performTransferOnUpdate(sourceHandler, destHandler); + return; + } + FluidFilter filter = getFilterHandler().getFilter(); + if (filter == FluidFilter.EMPTY) return; + if (transferMode == TransferMode.KEEP_EXACT) { + IntToLongFunction maxflow = s -> Math.min(filter.getTransferLimit(s), getFluidsLeftToTransfer()); + reportFluidsTransfer(performTransfer(sourceHandler, destHandler, true, s -> 0, maxflow, null)); + } else if (transferMode == TransferMode.TRANSFER_EXACT) { + IntToLongFunction maxflow = s -> { + int limit = filter.getTransferLimit(s); + if (getFluidsLeftToTransfer() < limit) { + noTransferDueToMinimum = true; + return 0; + } else return limit; + }; + performTransfer(sourceHandler, destHandler, true, maxflow, maxflow, (a, b) -> reportFluidsTransfer(b)); } - - return platformTransferLimit - fluidLeftToTransfer; } - private void setTransferBucketMode(BucketMode transferBucketMode) { - var oldMultiplier = this.transferBucketMode.multiplier; - var newMultiplier = transferBucketMode.multiplier; - - this.transferBucketMode = transferBucketMode; - - if (transferSizeInput == null) return; - - if (oldMultiplier > newMultiplier) { - transferSizeInput.setValue(getCurrentBucketModeTransferSize()); + @Override + protected @NotNull FluidTraverseData getTD(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + if (transferMode == TransferMode.KEEP_EXACT) { + return new KeepFluidTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); } - this.transferSizeInput.setMax(MAX_STACK_SIZE / this.transferBucketMode.multiplier); - if (newMultiplier > oldMultiplier) { - transferSizeInput.setValue(getCurrentBucketModeTransferSize()); + return super.getTD(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + @Override + protected @NotNull FluidEQTraverseData getEQTD(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + if (getTransferMode() == TransferMode.KEEP_EXACT) { + return new KeepFluidEQTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); } + return super.getEQTD(net, testObject, simulator, queryTick, sourcePos, inputFacing); } - private void setTransferMode(TransferMode transferMode) { - this.transferMode = transferMode; + @Override + protected @NotNull FluidRRTraverseData getRRTD(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing, + boolean simulate) { + if (transferMode == TransferMode.KEEP_EXACT) { + return new KeepFluidRRTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing, + getRoundRobinCache(simulate)); + } + return super.getRRTD(net, testObject, simulator, queryTick, sourcePos, inputFacing, simulate); + } - configureTransferSizeInput(); + @Override + protected long simpleInsert(@NotNull IFluidTransfer destHandler, FluidTestObject testObject, long count, + boolean simulate) { + if (transferMode == TransferMode.KEEP_EXACT) { + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(testObject.recombine()); + count = Math.min(count, kept - computeContained(destHandler, testObject)); + } + return super.simpleInsert(destHandler, testObject, count, simulate); + } - if (!this.isRemote()) { - configureFilter(); + public void setTransferMode(TransferMode transferMode) { + if (this.transferMode != transferMode) { + this.transferMode = transferMode; + this.coverHolder.markDirty(); + this.getFilterHandler().getFilter().setMaxTransferSize(this.transferMode.maxStackSize); } } @@ -181,15 +162,6 @@ protected void configureFilter() { configureTransferSizeInput(); } - private long getFilteredFluidAmount(FluidStack fluidStack) { - if (!filterHandler.isFilterPresent()) - return globalTransferSizeMillibuckets; - - FluidFilter filter = filterHandler.getFilter(); - return (filter.supportsAmounts() ? filter.testFluidAmount(fluidStack) : globalTransferSizeMillibuckets) * - MILLIBUCKET_SIZE; - } - /////////////////////////// // ***** GUI ******// /////////////////////////// @@ -210,26 +182,26 @@ protected void buildAdditionalUI(WidgetGroup group) { configureTransferSizeInput(); group.addWidget(this.transferSizeInput); - this.transferBucketModeInput = new EnumSelectorWidget<>(121, 45, 20, 20, BucketMode.values(), - transferBucketMode, this::setTransferBucketMode); - group.addWidget(this.transferBucketModeInput); + this.bucketModeInput = new EnumSelectorWidget<>(121, 45, 20, 20, BucketMode.values(), + bucketMode, this::setBucketMode); + group.addWidget(this.bucketModeInput); } private long getCurrentBucketModeTransferSize() { - return this.globalTransferSizeMillibuckets / this.transferBucketMode.multiplier; + return this.getFilterHandler().getFilter().getMaxTransferSize() / this.bucketMode.multiplier; } private void setCurrentBucketModeTransferSize(long transferSize) { - this.globalTransferSizeMillibuckets = Math.min(Math.max(transferSize * this.transferBucketMode.multiplier, 0), - MAX_STACK_SIZE); + this.getFilterHandler().getFilter().setMaxTransferSize((int) Math.min(Math.max(transferSize * this.bucketMode.multiplier, 0), + MAX_STACK_SIZE)); } private void configureTransferSizeInput() { - if (this.transferSizeInput == null || transferBucketModeInput == null) + if (this.transferSizeInput == null || bucketModeInput == null) return; this.transferSizeInput.setVisible(shouldShowTransferSize()); - this.transferBucketModeInput.setVisible(shouldShowTransferSize()); + this.bucketModeInput.setVisible(shouldShowTransferSize()); } private boolean shouldShowTransferSize() { @@ -242,6 +214,151 @@ private boolean shouldShowTransferSize() { return !this.filterHandler.getFilter().supportsAmounts(); } + protected long computeContained(@NotNull IFluidTransfer handler, @NotNull FluidTestObject testObject) { + long found = 0; + for (int i = 0; i < handler.getTanks(); ++i) { + FluidStack contained = handler.getFluidInTank(i); + if (testObject.test(contained)) { + found += contained.getAmount(); + } + } + return found; + } + + protected class KeepFluidTraverseData extends FluidTraverseData { + + public KeepFluidTraverseData(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IFluidHandler containerCap = capability.getValue() + .getCapability(ForgeCapabilities.FLUID_HANDLER, + capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); + long contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained >= kept) continue; + availableFlow -= IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() == null); + } + } + return flowReachingDestination - availableFlow; + } + } + + protected class KeepFluidEQTraverseData extends FluidEQTraverseData { + + public KeepFluidEQTraverseData(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + @Override + protected void compute(@NotNull WorldPipeNetNode destination) { + this.destCount = 0; + this.maxMinFlow = 0; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IFluidHandler containerCap = capability.getValue() + .getCapability(ForgeCapabilities.FLUID_HANDLER, + capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); + long contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained >= kept) continue; + if (destCount == 0) maxMinFlow = Integer.MAX_VALUE; + destCount += 1; + maxMinFlow = Math.min(maxMinFlow, + IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + kept - contained, + container, false)); + } + } + } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IFluidHandler containerCap = capability.getValue() + .getCapability(ForgeCapabilities.FLUID_HANDLER, + capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); + long contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained >= kept) continue; + availableFlow -= IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() == null); + } + } + return flowReachingDestination - availableFlow; + } + } + + protected class KeepFluidRRTraverseData extends FluidRRTraverseData { + + public KeepFluidRRTraverseData(IGraphNet net, FluidTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing, + @NotNull Object2ObjectLinkedOpenHashMap> cache) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing, cache); + } + + @Override + public long finalizeAtDestination(@NotNull SimpleTileRoundRobinData data, + @NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + Direction pointerFacing = data.getPointerFacing(getSimulatorKey()); + // anti insert-to-our-source logic + if (!destination.getEquivalencyData().equals(sourcePos) || + !(pointerFacing == inputFacing)) { + IFluidHandler containerCap = data.getAtPointer(destination, getSimulatorKey()); + if (containerCap != null) { + IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); + long contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained < kept) { + availableFlow -= IFluidTransferController.CONTROL.get( + destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(pointerFacing)) + .insertToHandler(getTestObject(), + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() == null); + } + } + } + return flowReachingDestination - availableFlow; + } + } + ////////////////////////////////////// // ***** LDLib SyncData ******// ////////////////////////////////////// @@ -249,6 +366,7 @@ private boolean shouldShowTransferSize() { public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(FluidRegulatorCover.class, PumpCover.MANAGED_FIELD_HOLDER); + @NotNull @Override public ManagedFieldHolder getFieldHolder() { return MANAGED_FIELD_HOLDER; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/InfiniteWaterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/InfiniteWaterCover.java index 8e4e33db2b..7d9d81f638 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/InfiniteWaterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/InfiniteWaterCover.java @@ -1,10 +1,13 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.machine.TickableSubscription; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; @@ -12,6 +15,8 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.Direction; import net.minecraft.world.level.material.Fluids; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; @@ -31,8 +36,13 @@ public InfiniteWaterCover(CoverDefinition definition, ICoverable coverHolder, Di } @Override - public boolean canAttach() { - return FluidTransferHelper.getFluidTransfer(coverHolder.getLevel(), coverHolder.getPos(), attachedSide) != null; + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_infinite_water"), GTCEu.id("block/cover/overlay_infinite_water_emissive")).build(); + } + + @Override + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(ForgeCapabilities.FLUID_HANDLER).isPresent(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ItemFilterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ItemFilterCover.java index 4dfd227b83..dd6193a087 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ItemFilterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ItemFilterCover.java @@ -1,17 +1,19 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.IUICover; import com.gregtechceu.gtceu.api.cover.filter.ItemFilter; import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.ItemFilterMode; import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; -import com.lowdragmc.lowdraglib.side.item.ItemTransferHelper; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; @@ -20,6 +22,8 @@ import net.minecraft.core.Direction; import lombok.Getter; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; @@ -45,6 +49,11 @@ public ItemFilterCover(CoverDefinition definition, ICoverable coverHolder, Direc super(definition, coverHolder, attachedSide); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_filter"), null).build(); + } + public ItemFilter getItemFilter() { if (itemFilter == null) { itemFilter = ItemFilter.loadFilter(attachItem); @@ -58,8 +67,8 @@ public void setFilterMode(ItemFilterMode filterMode) { } @Override - public boolean canAttach() { - return ItemTransferHelper.getItemTransfer(coverHolder.getLevel(), coverHolder.getPos(), attachedSide) != null; + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(ForgeCapabilities.ITEM_HANDLER).isPresent(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java index 7403461e1a..2d7482e53a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/MachineControllerCover.java @@ -1,14 +1,18 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.IControllable; import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.IUICover; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.IntInputWidget; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.ControllerMode; import com.gregtechceu.gtceu.data.lang.LangHandler; @@ -30,6 +34,7 @@ import net.minecraft.world.level.block.Block; import lombok.Getter; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; @@ -71,8 +76,13 @@ public MachineControllerCover(CoverDefinition definition, ICoverable coverHolder } @Override - public boolean canAttach() { - return !getAllowedModes().isEmpty(); + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_controller"), null).build(); + } + + @Override + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return !getAllowedModes(coverable, side).isEmpty(); } @Override @@ -186,6 +196,13 @@ public List getAllowedModes() { .collect(Collectors.toList()); } + public static List getAllowedModes(ICoverable coverable, Direction attachedSide) { + return Arrays.stream(ControllerMode.values()) + .filter(mode -> mode.side != attachedSide) + .filter(mode -> coverable.getCapability(GTCapability.CAPABILITY_CONTROLLABLE, mode.side).isPresent()) + .collect(Collectors.toList()); + } + private int getInputSignal() { return coverHolder.getInputRedstoneSignal(attachedSide, true); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java index 57bb622f69..3d83a91979 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/PumpCover.java @@ -31,6 +31,7 @@ import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidRRTraverseData; import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidTraverseData; import com.gregtechceu.gtceu.common.pipelike.net.fluid.IFluidTraverseGuideProvider; + import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; @@ -44,10 +45,7 @@ import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; import com.lowdragmc.lowdraglib.utils.LocalizationUtils; -import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import lombok.Getter; -import lombok.Setter; + import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -57,16 +55,23 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.fluids.capability.IFluidHandler; + +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import lombok.Getter; +import lombok.Setter; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; +import java.util.function.IntToLongFunction; import java.util.function.LongUnaryOperator; +import javax.annotation.ParametersAreNonnullByDefault; + /** * @author KilaBash * @date 2023/3/12 @@ -322,8 +327,9 @@ protected void performTransferOnUpdate(@NotNull IFluidTransfer sourceHandler, @N * @return how much was transferred in total. */ protected long performTransfer(@NotNull IFluidTransfer sourceHandler, @NotNull IFluidTransfer destHandler, - boolean byFilterSlot, @NotNull LongUnaryOperator minTransfer, - @NotNull LongUnaryOperator maxTransfer, @Nullable BiConsumer transferReport) { + boolean byFilterSlot, @NotNull IntToLongFunction minTransfer, + @NotNull IntToLongFunction maxTransfer, + @Nullable BiConsumer transferReport) { FluidFilter filter = this.filterHandler.getFilter(); byFilterSlot = byFilterSlot && filter != FluidFilter.EMPTY; // can't be by filter slot if there is no filter Object2LongOpenHashMap contained = new Object2LongOpenHashMap<>(); @@ -340,7 +346,8 @@ protected long performTransfer(@NotNull IFluidTransfer sourceHandler, @NotNull I if (filter == FluidFilter.EMPTY || (match = filter.match(contents)).isMatched()) { int filterSlot = -1; if (byFilterSlot) { - assert filter != FluidFilter.EMPTY; // we know it is not null, because if it were byFilterSlot would be false. + assert filter != FluidFilter.EMPTY; // we know it is not null, because if it were byFilterSlot would + // be false. filterSlot = match.getFilterIndex(); } long min = minTransfer.applyAsLong(filterSlot); @@ -363,9 +370,8 @@ protected long performTransfer(@NotNull IFluidTransfer sourceHandler, @NotNull I return totalTransfer; } - protected long insertToHandler(@NotNull IFluidTransfer destHandler, FluidTestObject testObject, long count, - boolean simulate) { + boolean simulate) { if (!(destHandler instanceof IFluidTraverseGuideProvider provider)) { return simpleInsert(destHandler, testObject, count, simulate); } @@ -426,7 +432,7 @@ protected Object2ObjectLinkedOpenHashMap moveInventoryItems(itemHandler, myItemHandler, maxTransferAmount); - case TRANSFER_EXACT -> doTransferExact(itemHandler, myItemHandler, maxTransferAmount); - case KEEP_EXACT -> doKeepExact(itemHandler, myItemHandler, maxTransferAmount); - }; + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_arm"), GTCEu.id("block/cover/overlay_arm_emissive")).build(); } - protected int doTransferExact(IItemTransfer sourceInventory, IItemTransfer targetInventory, int maxTransferAmount) { - Map sourceItemAmount = countInventoryItemsByType(sourceInventory); - - Iterator iterator = sourceItemAmount.keySet().iterator(); - while (iterator.hasNext()) { - TypeItemInfo sourceInfo = sourceItemAmount.get(iterator.next()); - int itemAmount = sourceInfo.totalCount; - int itemToMoveAmount = getFilteredItemAmount(sourceInfo.itemStack); + @Override + protected CoverRenderer buildRendererInverted() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_arm"), GTCEu.id("block/cover/overlay_arm_inverted_emissive")).build(); + } - if (itemAmount >= itemToMoveAmount) { - sourceInfo.totalCount = itemToMoveAmount; - } else { - iterator.remove(); + @Override + protected void refreshBuffer(int transferRate) { + if (this.transferMode == TransferMode.TRANSFER_EXACT && noTransferDueToMinimum) { + if (getFilterHandler().isFilterPresent()) { + this.noTransferDueToMinimum = false; + this.itemsLeftToTransferLastSecond += transferRate; + int max = getFilterHandler().getFilter().getMaxTransferSize(); + if (this.itemsLeftToTransferLastSecond > max) { + this.itemsLeftToTransferLastSecond = max; + } + return; } } + super.refreshBuffer(transferRate); + } - int itemsTransferred = 0; - int maxTotalTransferAmount = maxTransferAmount + itemsTransferBuffered; - boolean notEnoughTransferRate = false; - for (TypeItemInfo itemInfo : sourceItemAmount.values()) { - if (maxTotalTransferAmount >= itemInfo.totalCount) { - boolean result = moveInventoryItemsExact(sourceInventory, targetInventory, itemInfo); - itemsTransferred += result ? itemInfo.totalCount : 0; - maxTotalTransferAmount -= result ? itemInfo.totalCount : 0; - } else { - notEnoughTransferRate = true; - } + @Override + protected void performTransferOnUpdate(@NotNull IItemTransfer sourceHandler, @NotNull IItemTransfer destHandler) { + if (transferMode == TransferMode.TRANSFER_ANY) { + super.performTransferOnUpdate(sourceHandler, destHandler); + return; } - // if we didn't transfer anything because of too small transfer rate, buffer it - if (itemsTransferred == 0 && notEnoughTransferRate) { - itemsTransferBuffered += maxTransferAmount; - } else { - // otherwise, if transfer succeed, empty transfer buffer value - itemsTransferBuffered = 0; + if (!getFilterHandler().isFilterPresent()) return; + ItemFilter filter = getFilterHandler().getFilter(); + if (transferMode == TransferMode.KEEP_EXACT) { + IntUnaryOperator maxflow = s -> Math.min(filter.getTransferLimit(s), getItemsLeftToTransfer()); + reportItemsTransfer(performTransfer(sourceHandler, destHandler, true, s -> 0, maxflow, null)); + } else if (transferMode == TransferMode.TRANSFER_EXACT) { + IntUnaryOperator maxflow = s -> { + int limit = filter.getTransferLimit(s); + if (getItemsLeftToTransfer() < limit) { + noTransferDueToMinimum = true; + return 0; + } else return limit; + }; + performTransfer(sourceHandler, destHandler, true, maxflow, maxflow, (a, b) -> reportItemsTransfer(b)); } - return Math.min(itemsTransferred, maxTransferAmount); } - protected int doKeepExact(IItemTransfer sourceInventory, IItemTransfer targetInventory, int maxTransferAmount) { - Map targetItemAmounts = countInventoryItemsByMatchSlot(targetInventory); - Map sourceItemAmounts = countInventoryItemsByMatchSlot(sourceInventory); + @Override + protected @NotNull ItemTraverseData getTD(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + if (transferMode == TransferMode.KEEP_EXACT) { + return new KeepItemTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + return super.getTD(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } - Iterator iterator = sourceItemAmounts.keySet().iterator(); - while (iterator.hasNext()) { - ItemStack filteredItem = iterator.next(); - GroupItemInfo sourceInfo = sourceItemAmounts.get(filteredItem); - int itemToKeepAmount = getFilteredItemAmount(sourceInfo.itemStack); + @Override + protected @NotNull ItemEQTraverseData getEQTD(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing) { + if (transferMode == TransferMode.KEEP_EXACT) { + return new KeepItemEQTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + return super.getEQTD(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } - int itemAmount = 0; - if (targetItemAmounts.containsKey(filteredItem)) { - GroupItemInfo destItemInfo = targetItemAmounts.get(filteredItem); - itemAmount = destItemInfo.totalCount; - } - if (itemAmount < itemToKeepAmount) { - sourceInfo.totalCount = itemToKeepAmount - itemAmount; - } else { - iterator.remove(); + @Override + protected @NotNull ItemRRTraverseData getRRTD(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, + long queryTick, BlockPos sourcePos, Direction inputFacing, + boolean simulate) { + if (transferMode == TransferMode.KEEP_EXACT) { + return new KeepItemRRTraverseData(net, testObject, simulator, queryTick, sourcePos, inputFacing, + getRoundRobinCache(simulate)); + } + return super.getRRTD(net, testObject, simulator, queryTick, sourcePos, inputFacing, simulate); + } + + @Override + protected int simpleInsert(@NotNull IItemTransfer destHandler, ItemTestObject testObject, int count, + boolean simulate) { + if (transferMode == TransferMode.KEEP_EXACT) { + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(testObject.recombine()); + count = Math.min(count, kept - computeContained(destHandler, testObject)); + } + return super.simpleInsert(destHandler, testObject, count, simulate); + } + + public void setTransferMode(TransferMode transferMode) { + if (this.transferMode != transferMode) { + this.transferMode = transferMode; + this.coverHolder.markDirty(); + configureStackSizeInput(); + this.getFilterHandler().getFilter().setMaxTransferSize(transferMode.maxStackSize); + } + } + + @Override + public int insertToHandler(@NotNull ItemTestObject testObject, int amount, @NotNull IItemTransfer destHandler, + boolean simulate) { + if (io == IO.OUT) { + if (transferMode == TransferMode.KEEP_EXACT) { + int contained = computeContained(destHandler, testObject); + assert getFilterHandler().isFilterPresent(); + int keep = getFilterHandler().getFilter().getTransferLimit(testObject.recombine()); + if (contained >= keep) return amount; + int allowed = Math.min(keep - contained, amount); + return (amount - allowed) + super.insertToHandler(testObject, allowed, destHandler, simulate); + } else if (transferMode == TransferMode.TRANSFER_EXACT) { + assert getFilterHandler().isFilterPresent(); + int required = getFilterHandler().getFilter().getTransferLimit(testObject.recombine()); + if (amount < required) return amount; + return (amount - required) + super.insertToHandler(testObject, required, destHandler, simulate); } } + return super.insertToHandler(testObject, amount, destHandler, simulate); + } - return moveInventoryItems(sourceInventory, targetInventory, sourceItemAmounts, maxTransferAmount); + @Override + public int extractFromHandler(@NotNull ItemTestObject testObject, int amount, @NotNull IItemTransfer sourceHandler, + boolean simulate) { + if (io == IO.IN) { + // TODO should extraction instead be ignored for transfer exact? + if (transferMode == TransferMode.TRANSFER_EXACT) { + assert getFilterHandler().isFilterPresent(); + int required = getFilterHandler().getFilter().getTransferLimit(testObject.recombine()); + if (amount < required) return 0; + else amount = required; + } + } + return super.extractFromHandler(testObject, amount, sourceHandler, simulate); } private int getFilteredItemAmount(ItemStack itemStack) { @@ -177,16 +250,6 @@ protected void buildAdditionalUI(WidgetGroup group) { group.addWidget(this.stackSizeInput); } - private void setTransferMode(TransferMode transferMode) { - this.transferMode = transferMode; - - configureStackSizeInput(); - - if (!this.isRemote()) { - configureFilter(); - } - } - @Override protected void configureFilter() { if (filterHandler.getFilter() instanceof SimpleItemFilter filter) { @@ -214,4 +277,146 @@ private boolean shouldShowStackSize() { return !this.filterHandler.getFilter().supportsAmounts(); } + + protected int computeContained(@NotNull IItemTransfer handler, @NotNull ItemTestObject testObject) { + int found = 0; + for (int i = 0; i < handler.getSlots(); i++) { + ItemStack contained = handler.getStackInSlot(i); + if (testObject.test(contained)) { + found += contained.getCount(); + } + } + return found; + } + + protected class KeepItemTraverseData extends ItemTraverseData { + + public KeepItemTraverseData(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IItemHandler containerCap = capability.getValue() + .getCapability(ForgeCapabilities.ITEM_HANDLER, + capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); + int contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained >= kept) continue; + availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() != null); + } + } + return flowReachingDestination - availableFlow; + } + } + + protected class KeepItemEQTraverseData extends ItemEQTraverseData { + + public KeepItemEQTraverseData(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing); + } + + @Override + protected void compute(@NotNull WorldPipeNetNode destination) { + this.destCount = 0; + this.maxMinFlow = 0; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IItemHandler containerCap = capability.getValue() + .getCapability(ForgeCapabilities.ITEM_HANDLER, + capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); + int contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained >= kept) continue; + if (destCount == 0) maxMinFlow = Integer.MAX_VALUE; + destCount += 1; + int test = kept - contained; + maxMinFlow = Math.min(maxMinFlow, test - + IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), test, + container, true)); + } + } + } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long flowReachingDestination) { + long availableFlow = flowReachingDestination; + for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { + if (destination.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IItemHandler containerCap = capability.getValue() + .getCapability(ForgeCapabilities.ITEM_HANDLER, + capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); + int contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained >= kept) continue; + availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() != null); + } + } + return flowReachingDestination - availableFlow; + } + } + + protected class KeepItemRRTraverseData extends ItemRRTraverseData { + + public KeepItemRRTraverseData(IGraphNet net, ItemTestObject testObject, SimulatorKey simulator, long queryTick, + BlockPos sourcePos, Direction inputFacing, + @NotNull Object2ObjectLinkedOpenHashMap> cache) { + super(net, testObject, simulator, queryTick, sourcePos, inputFacing, cache); + } + + @Override + public long finalizeAtDestination(@NotNull SimpleTileRoundRobinData data, + @NotNull WorldPipeNetNode destination, + long flowReachingDestination) { + long availableFlow = flowReachingDestination; + Direction pointerFacing = data.getPointerFacing(getSimulatorKey()); + if (destination.getEquivalencyData().equals(sourcePos) && pointerFacing == inputFacing) + return 0; // anti insert-to-our-source logic + + IItemHandler containerCap = data.getAtPointer(destination, getSimulatorKey()); + if (containerCap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); + int contained = computeContained(container, getTestObject()); + assert getFilterHandler().isFilterPresent(); + int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); + if (contained >= kept) return 0; + availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() + .getCoverAtSide(pointerFacing)).insertToHandler(getTestObject(), + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() != null); + } + return flowReachingDestination - availableFlow; + } + } } + diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java index 5763abcc7e..612f95399e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java @@ -1,10 +1,13 @@ package com.gregtechceu.gtceu.common.cover; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.IControllable; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; @@ -39,6 +42,11 @@ public ShutterCover(@NotNull CoverDefinition definition, @NotNull ICoverable cov super(definition, coverableView, attachedSide); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_shutter"), null).build(); + } + @Override public InteractionResult onScrewdriverClick(Player playerIn, InteractionHand hand, BlockHitResult hitResult) { return InteractionResult.FAIL; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java index d10aa75c3f..544a5b060a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java @@ -1,11 +1,16 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; @@ -18,8 +23,13 @@ public ActivityDetectorCover(CoverDefinition definition, ICoverable coverHolder, } @Override - public boolean canAttach() { - return GTCapabilityHelper.getWorkable(coverHolder.getLevel(), coverHolder.getPos(), attachedSide) != null; + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_activity_detector"), GTCEu.id("block/cover/overlay_activity_detector_emissive")).build(); + } + + @Override + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(GTCapability.CAPABILITY_WORKABLE).isPresent(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java index c5334db9f5..6190badd92 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java @@ -1,13 +1,19 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.IEnergyInfoProvider; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; +import com.gregtechceu.gtceu.common.machine.multiblock.electric.PowerSubstationMachine; import com.gregtechceu.gtceu.utils.RedstoneUtil; import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class EnergyDetectorCover extends DetectorCover { @@ -17,8 +23,13 @@ public EnergyDetectorCover(CoverDefinition definition, ICoverable coverHolder, D } @Override - public boolean canAttach() { - return getEnergyInfoProvider() != null; + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_energy_detector"), GTCEu.id("block/cover/overlay_energy_detector_emissive")).build(); + } + + @Override + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(GTCapability.CAPABILITY_ENERGY_INFO_PROVIDER).isPresent(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java index de79297413..39efc89ccb 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java @@ -1,7 +1,10 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.utils.RedstoneUtil; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; @@ -9,6 +12,8 @@ import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import org.jetbrains.annotations.NotNull; public class FluidDetectorCover extends DetectorCover { @@ -17,8 +22,13 @@ public FluidDetectorCover(CoverDefinition definition, ICoverable coverHolder, Di } @Override - public boolean canAttach() { - return getFluidTransfer() != null; + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_detector"), GTCEu.id("block/cover/overlay_fluid_detector_emissive")).build(); + } + + @Override + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(ForgeCapabilities.FLUID_HANDLER).isPresent(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java index f9bb515262..82caf90293 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java @@ -1,13 +1,18 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.utils.RedstoneUtil; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.side.item.ItemTransferHelper; import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import org.jetbrains.annotations.NotNull; public class ItemDetectorCover extends DetectorCover { @@ -16,8 +21,13 @@ public ItemDetectorCover(CoverDefinition definition, ICoverable coverHolder, Dir } @Override - public boolean canAttach() { - return getItemTransfer() != null; + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { + return coverable.getCapability(ForgeCapabilities.ITEM_HANDLER).isPresent(); + } + + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_detector"), GTCEu.id("block/cover/overlay_item_detector_emissive")).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java index ad5ba24c7c..fd0e3de1cf 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java @@ -1,12 +1,17 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMaintenanceMachine; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.config.ConfigHolder; import net.minecraft.core.Direction; +import org.jetbrains.annotations.NotNull; public class MaintenanceDetectorCover extends DetectorCover { @@ -15,13 +20,17 @@ public MaintenanceDetectorCover(CoverDefinition definition, ICoverable coverHold } @Override - public boolean canAttach() { + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_maintenance_detector"), null).build(); + } + + @Override + public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) { if (!ConfigHolder.INSTANCE.machines.enableMaintenance) { return false; } - return GTCapabilityHelper.getMaintenanceMachine(coverHolder.getLevel(), coverHolder.getPos(), attachedSide) != - null; + return coverable.getCapability(GTCapability.CAPABILITY_MAINTENANCE_MACHINE).isPresent(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java index e81047e923..8ee087b313 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.cover.voiding; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.filter.FluidFilter; @@ -7,12 +8,16 @@ import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; import com.gregtechceu.gtceu.api.gui.widget.LongInputWidget; import com.gregtechceu.gtceu.api.gui.widget.NumberInputWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.BucketMode; import com.gregtechceu.gtceu.common.cover.data.VoidingMode; +import com.gregtechceu.gtceu.utils.GTTransferUtils; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; @@ -21,9 +26,11 @@ import net.minecraft.core.Direction; import lombok.Getter; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.fluids.capability.IFluidHandler; import org.jetbrains.annotations.NotNull; -import java.util.Map; +import java.util.function.Predicate; import javax.annotation.ParametersAreNonnullByDefault; @@ -52,36 +59,58 @@ public AdvancedFluidVoidingCover(CoverDefinition definition, ICoverable coverHol super(definition, coverHolder, attachedSide); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_voiding_advanced"), + GTCEu.id("block/cover/overlay_fluid_voiding_advanced_emissive")).build(); + } + ////////////////////////////////////////////// // *********** COVER LOGIC ***********// ////////////////////////////////////////////// @Override - protected void doVoidFluids() { - IFluidTransfer fluidTransfer = getOwnFluidTransfer(); - if (fluidTransfer == null) { + protected void doTransferFluids() { + IFluidHandler myFluidHandlerCap = coverHolder.getCapability(ForgeCapabilities.FLUID_HANDLER, + attachedSide).resolve().orElse(null); + if (myFluidHandlerCap == null) { return; } - + IFluidTransfer myFluidHandler = FluidTransferHelperImpl.toFluidTransfer(myFluidHandlerCap); switch (voidingMode) { - case VOID_ANY -> voidAny(fluidTransfer); - case VOID_OVERFLOW -> voidOverflow(fluidTransfer); + case VOID_ANY -> GTTransferUtils.transferFluids(myFluidHandler, nullFluidTank, Integer.MAX_VALUE, + getFilterHandler()::test); + case VOID_OVERFLOW -> voidOverflow(myFluidHandler, getFilterHandler()::test, + this.globalTransferSizeMillibuckets); } + subscriptionHandler.updateSubscription(); } - private void voidOverflow(IFluidTransfer fluidTransfer) { - final Map fluidAmounts = enumerateDistinctFluids(fluidTransfer, TransferDirection.EXTRACT); + /** + * Performs one tick worth of Keep Exact behavior. + * + * @param sourceHandler source(s) to move fluids from + * @param fluidFilter a predicate which determines what fluids may be moved + * @param keepAmount the desired amount in milliBuckets of a particular fluid in the destination + */ + protected void voidOverflow(final IFluidTransfer sourceHandler, + final Predicate fluidFilter, + long keepAmount) { + if (sourceHandler == null || fluidFilter == null) + return; - for (FluidStack fluidStack : fluidAmounts.keySet()) { - long presentAmount = fluidAmounts.get(fluidStack); - long targetAmount = getFilteredFluidAmount(fluidStack) * MILLIBUCKET_SIZE; - if (targetAmount <= 0L || targetAmount > presentAmount) + for (int i = 0; i < sourceHandler.getTanks(); ++i) { + FluidStack sourceFluid = sourceHandler.getFluidInTank(i); + if (this.getFilterHandler().isFilterPresent() && + voidingMode == VoidingMode.VOID_OVERFLOW) { + keepAmount = this.getFilterHandler().getFilter() + .getTransferLimit(sourceFluid, (int) maxMilliBucketsPerTick); + } + if (sourceFluid.isEmpty() || sourceFluid.getAmount() == 0 || + !getFilterHandler().test(sourceFluid)) continue; - - var toDrain = fluidStack.copy(); - toDrain.setAmount(presentAmount - targetAmount); - - fluidTransfer.drain(toDrain, false); + sourceFluid.setAmount(sourceFluid.getAmount() - keepAmount); + sourceHandler.drain(sourceFluid, true); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java index 26374ffa1b..3cd546f680 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java @@ -1,16 +1,22 @@ package com.gregtechceu.gtceu.common.cover.voiding; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.PumpCover; +import com.gregtechceu.gtceu.utils.GTTransferUtils; import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; +import com.lowdragmc.lowdraglib.misc.FluidStorage; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; @@ -18,6 +24,8 @@ import net.minecraft.core.Direction; import lombok.Getter; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.fluids.capability.IFluidHandler; import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -28,6 +36,8 @@ @ParametersAreNonnullByDefault public class FluidVoidingCover extends PumpCover { + protected final NullFluidTank nullFluidTank = new NullFluidTank(); + @Persisted @Getter protected boolean isEnabled = false; @@ -36,6 +46,11 @@ public FluidVoidingCover(CoverDefinition definition, ICoverable coverHolder, Dir super(definition, coverHolder, attachedSide, 0); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_voiding"), null).build(); + } + @Override protected boolean isSubscriptionActive() { return isWorkingEnabled() && isEnabled(); @@ -45,35 +60,24 @@ protected boolean isSubscriptionActive() { // *********** COVER LOGIC ***********// ////////////////////////////////////////////// - @Override - protected void update() { - if (coverHolder.getOffsetTimer() % 5 != 0) - return; - doVoidFluids(); - subscriptionHandler.updateSubscription(); - } - - protected void doVoidFluids() { - IFluidTransfer fluidTransfer = getOwnFluidTransfer(); - if (fluidTransfer == null) { - return; + @Override + public void update() { + if (isWorkingEnabled && coverHolder.getOffsetTimer() % 20 == 0) { + doTransferFluids(); } - voidAny(fluidTransfer); } - void voidAny(IFluidTransfer fluidTransfer) { - final Map fluidAmounts = enumerateDistinctFluids(fluidTransfer, TransferDirection.EXTRACT); - - for (FluidStack fluidStack : fluidAmounts.keySet()) { - if (!filterHandler.test(fluidStack)) - continue; - - var toDrain = fluidStack.copy(); - toDrain.setAmount(fluidAmounts.get(fluidStack)); - - fluidTransfer.drain(toDrain, false); + protected void doTransferFluids() { + IFluidHandler myFluidHandlerCap = coverHolder.getCapability(ForgeCapabilities.FLUID_HANDLER, + attachedSide).resolve().orElse(null); + if (myFluidHandlerCap == null) { + return; } + IFluidTransfer myFluidHandler = FluidTransferHelperImpl.toFluidTransfer(myFluidHandlerCap); + GTTransferUtils.transferFluids(myFluidHandler, nullFluidTank, Integer.MAX_VALUE, + getFilterHandler()::test); + subscriptionHandler.updateSubscription(); } public void setWorkingEnabled(boolean workingEnabled) { @@ -131,4 +135,19 @@ protected void configureFilter() { public ManagedFieldHolder getFieldHolder() { return MANAGED_FIELD_HOLDER; } + + class NullFluidTank extends FluidStorage { + + public NullFluidTank() { + super(Integer.MAX_VALUE); + } + + @Override + public long fill(FluidStack resource, boolean execute, boolean notifyChanges) { + if (FluidVoidingCover.this.filterHandler.test(resource)) { + return resource.getAmount(); + } + return 0; + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index dbbbc4e9a7..a3e155d265 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -1,16 +1,14 @@ package com.gregtechceu.gtceu.common.data; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.blockentity.*; -import com.simibubi.create.content.fluids.pipes.FluidPipeBlockEntity; import net.minecraft.world.level.block.entity.SignBlockEntity; import com.tterrag.registrate.util.entry.BlockEntityEntry; -import com.tterrag.registrate.util.entry.BlockEntry; import com.tterrag.registrate.util.nullness.NonNullSupplier; -import java.util.Arrays; import java.util.stream.Stream; import static com.gregtechceu.gtceu.common.registry.GTRegistration.REGISTRATE; @@ -23,13 +21,17 @@ @SuppressWarnings("unchecked") public class GTBlockEntities { - public static final BlockEntityEntry NEW_PIPE = REGISTRATE + public static final BlockEntityEntry PIPE = REGISTRATE .blockEntity("pipe", PipeBlockEntity::new) .validBlocks(Stream.concat(GTBlocks.DUCT_PIPE_BLOCKS.values().stream(), - Stream.concat(Stream.of(GTBlocks.OPTICAL_PIPE), - Stream.concat(Stream.of(GTBlocks.LASER_PIPE), - Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), - GTBlocks.MATERIAL_PIPE_BLOCKS.values().stream())))) + Stream.concat(Stream.of(GTBlocks.OPTICAL_PIPE), Stream.of(GTBlocks.LASER_PIPE))) + .toArray(NonNullSupplier[]::new)) + .register(); + + public static final BlockEntityEntry MATERIAL_PIPE = REGISTRATE + .blockEntity("material_pipe", MaterialPipeBlockEntity::new) + .validBlocks(Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), + GTBlocks.MATERIAL_PIPE_BLOCKS.values().stream()) .toArray(NonNullSupplier[]::new)) .register(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 77b9ff22cc..efd95a8ab7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -36,6 +36,7 @@ import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidPipeType; import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemPipeType; import com.gregtechceu.gtceu.core.mixins.BlockPropertiesAccessor; @@ -310,8 +311,14 @@ private static void generateCableBlocks() { } private static boolean allowCableBlock(Material material, CableStructure insulation) { - return material.hasProperty(PropertyKey.WIRE) && !insulation.prefix().isIgnored(material) && - !(insulation.isInsulated() && material.getProperty(PropertyKey.WIRE).isSuperconductor()); + if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES)) { + return material.getProperty(PropertyKey.PIPENET_PROPERTIES).hasProperty(MaterialEnergyProperties.KEY) && + !insulation.prefix().isIgnored(material) && + !(insulation.isInsulated() && material.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialEnergyProperties.KEY) + .isSuperconductor()); + } + return false; } private static void registerCableBlock(Material material, CableStructure insulation, GTRegistrate registrate) { @@ -341,8 +348,8 @@ private static void generateMaterialPipeBlocks() { for (MaterialRegistry registry : GTCEuAPI.materialManager.getRegistries()) { GTRegistrate registrate = registry.getRegistrate(); for (Material material : registry.getAllMaterials()) { - if (allowFluidPipeBlock(material, structure)) { - registerFluidPipeBlock(material, structure, registrate); + if (allowMaterialPipeBlock(material, structure)) { + registerMaterialPipeBlock(material, structure, registrate); } } } @@ -351,12 +358,12 @@ private static void generateMaterialPipeBlocks() { GTCEu.LOGGER.debug("Generating GTCEu Material Pipe Blocks... Complete!"); } - private static boolean allowFluidPipeBlock(Material material, MaterialPipeStructure fluidPipeType) { - return material.hasProperty(PropertyKey.FLUID_PIPE) && !fluidPipeType.prefix().isIgnored(material); + private static boolean allowMaterialPipeBlock(Material material, MaterialPipeStructure fluidPipeType) { + return material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && !fluidPipeType.prefix().isIgnored(material); } - private static void registerFluidPipeBlock(Material material, MaterialPipeStructure fluidPipeType, - GTRegistrate registrate) { + private static void registerMaterialPipeBlock(Material material, MaterialPipeStructure fluidPipeType, + GTRegistrate registrate) { var entry = registrate .block("%s_%s_pipe".formatted(material.getName(), fluidPipeType.name()), p -> new MaterialPipeBlock(p, fluidPipeType, material)) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java index ba5c378c1d..2927cea7eb 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java @@ -141,7 +141,7 @@ public static CoverDefinition register(String id, CoverDefinition.CoverBehaviour public static CoverDefinition register(String id, CoverDefinition.CoverBehaviourProvider behaviorCreator, ICoverRenderer coverRenderer) { var definition = new CoverDefinition(GTCEu.id(id), behaviorCreator, - (quads, side, rand, renderPlate, renderBackside, colorData) -> coverRenderer.renderCover(quads, side, + (quads, side, rand, renderPlate, renderBackside, modelData, colorData, renderType) -> coverRenderer.renderCover(quads, side, rand, null, null, null, null, null)); GTRegistries.COVERS.register(GTCEu.id(id), definition); return definition; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java index 167fa50dd5..c235e415b0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java @@ -35,6 +35,7 @@ import com.gregtechceu.gtceu.common.item.*; import com.gregtechceu.gtceu.common.item.armor.*; import com.gregtechceu.gtceu.common.item.tool.behavior.LighterBehavior; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialFluidProperties; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.data.lang.LangHandler; import com.gregtechceu.gtceu.data.recipe.CustomTags; @@ -546,7 +547,7 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 8, - GTMaterials.Steel.getProperty(PropertyKey.FLUID_PIPE).getMaxFluidTemperature(), true, false, + GTMaterials.Steel.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, false, false, true), new ItemFluidContainer())) .onRegister(materialInfo(new ItemMaterialInfo(new MaterialStack(GTMaterials.Steel, GTValues.M * 4)))) @@ -559,7 +560,7 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 32, - GTMaterials.Aluminium.getProperty(PropertyKey.FLUID_PIPE).getMaxFluidTemperature(), true, + GTMaterials.Aluminium.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, false, false, true), new ItemFluidContainer())) .onRegister(materialInfo(new ItemMaterialInfo(new MaterialStack(GTMaterials.Aluminium, GTValues.M * 4)))) @@ -572,7 +573,7 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 64, - GTMaterials.StainlessSteel.getProperty(PropertyKey.FLUID_PIPE).getMaxFluidTemperature(), + GTMaterials.StainlessSteel.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, false, false, true), new ItemFluidContainer())) .onRegister( @@ -586,7 +587,7 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 128, - GTMaterials.Titanium.getProperty(PropertyKey.FLUID_PIPE).getMaxFluidTemperature(), true, + GTMaterials.Titanium.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, false, false, true), new ItemFluidContainer())) .onRegister(materialInfo(new ItemMaterialInfo(new MaterialStack(GTMaterials.Titanium, GTValues.M * 6)))) @@ -600,7 +601,7 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 512, - GTMaterials.TungstenSteel.getProperty(PropertyKey.FLUID_PIPE).getMaxFluidTemperature(), + GTMaterials.TungstenSteel.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, false, false, true), new ItemFluidContainer())) .onRegister( diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java index 227897b1f2..d1fb98c2c9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java @@ -688,7 +688,8 @@ public static BiConsumer> createTankTooltips(String n var item = stack.getItem(); if (item instanceof DrumMachineItem drumItem && material != null) { if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES)) { - MaterialFluidProperties pipeprops = material.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY); + MaterialFluidProperties pipeprops = material.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialFluidProperties.KEY); pipeprops.appendTooltips(list, true, true); } } @@ -738,7 +739,7 @@ public static BiConsumer> createTankTooltips(String n public static final MultiblockMachineDefinition WOODEN_MULTIBLOCK_TANK = registerMultiblockTank( "wooden_multiblock_tank", "Wooden Multiblock Tank", 250 * 1000, CASING_WOOD_WALL, WOODEN_TANK_VALVE::getBlock, - new PropertyFluidFilter(340, false, false, false, false), + new PropertyFluidFilter(340, 121, false, false, false), (builder, overlay) -> builder.sidedWorkableCasingRenderer("block/casings/wood_wall", overlay)); public static final MachineDefinition STEEL_TANK_VALVE = registerTankValve( diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java index ffc027f95f..93621acf58 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java @@ -178,7 +178,7 @@ public static void register() { .appendFlags(EXT_METAL, GENERATE_ROTOR) .element(GTElements.Cr) .rotorStats(130, 155, 3.0f, 512) - .fluidPipeProperties(2180, 35, true, true, false, false) + .fluidPipeProperties(2180, 104, 35, true, false, false) .blastTemp(1700, GasTier.LOW) .hazard(HazardProperty.HazardTrigger.SKIN_CONTACT, GTMedicalConditions.CARCINOGEN) .buildAndRegister(); @@ -314,7 +314,7 @@ public static void register() { GENERATE_SPRING, GENERATE_SPRING_SMALL, GENERATE_FINE_WIRE, GENERATE_FOIL) .element(GTElements.Au) .cableProperties(GTValues.V[3], 3, 2) - .fluidPipeProperties(1671, 25, true, true, false, false) + .fluidPipeProperties(1671, 25, true, false, false) .buildAndRegister(); Hafnium = new Material.Builder(GTCEu.id("hafnium")) @@ -379,7 +379,7 @@ public static void register() { .appendFlags(EXT2_METAL, GENERATE_FINE_WIRE, GENERATE_GEAR, GENERATE_FRAME) .element(GTElements.Ir) .rotorStats(130, 115, 3.0f, 2560) - .fluidPipeProperties(3398, 250, true, false, true, false) + .fluidPipeProperties(3398, 5, 250, false, true, false) .blastTemp(4500, GasTier.HIGH, GTValues.VA[GTValues.IV], 1100) .buildAndRegister(); @@ -866,7 +866,7 @@ public static void register() { .element(GTElements.W) .rotorStats(130, 115, 3.0f, 2560) .cableProperties(GTValues.V[5], 2, 2) - .fluidPipeProperties(4618, 50, true, true, false, true) + .fluidPipeProperties(4618, 50, true, false, true) .blastTemp(3600, GasTier.MID, GTValues.VA[GTValues.EV], 1800) .buildAndRegister(); @@ -935,7 +935,7 @@ public static void register() { .element(GTElements.Nq) .rotorStats(160, 105, 4.0f, 1280) .cableProperties(GTValues.V[7], 2, 2) - .fluidPipeProperties(3776, 200, true, false, true, true) + .fluidPipeProperties(3776, 3, 200, false, true, true) .blastTemp(5000, GasTier.HIGH, GTValues.VA[GTValues.IV], 600) .buildAndRegister(); @@ -967,7 +967,7 @@ public static void register() { .toolStats(ToolProperty.Builder.of(180.0F, 100.0F, 65535, 6) .attackSpeed(0.5F).enchantability(33).magnetic().unbreakable().build()) .rotorStats(400, 250, 12.0f, 655360) - .fluidPipeProperties(100_000, 5000, true, true, true, true) + .fluidPipeProperties(100_000, 1, 5000, true, true, true) .radioactiveHazard(10) .buildAndRegister(); @@ -990,7 +990,7 @@ public static void register() { .element(GTElements.Dr) .toolStats(ToolProperty.Builder.of(14.0F, 12.0F, 8192, 5) .attackSpeed(0.3F).enchantability(33).magnetic().build()) - .fluidPipeProperties(9625, 500, true, true, true, true) + .fluidPipeProperties(9625, 1, 500, true, true, true) .buildAndRegister(); Trinium = new Material.Builder(GTCEu.id("trinium")) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java index 109ccc809f..45aa6b96af 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java @@ -599,7 +599,7 @@ public static void register() { .toolStats(ToolProperty.Builder.of(7.0F, 5.0F, 1024, 3) .enchantability(14).build()) .rotorStats(160, 115, 4.0f, 480) - .fluidPipeProperties(2428, 75, true, true, true, false) + .fluidPipeProperties(2428, 59, 75, true, true, false) .blastTemp(1700, GasTier.LOW, GTValues.VA[HV], 1100) .buildAndRegister(); @@ -1299,7 +1299,7 @@ public static void register() { .color(0xE1B454).secondaryColor(0x223033).iconSet(METALLIC) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Manganese, 1, Phosphorus, 1) - .cableProperties(GTValues.V[GTValues.LV], 2, 0, true, 78) + .cableProperties(GTValues.V[GTValues.LV], 2, GTValues.V[GTValues.ULV], 500) .blastTemp(1200, GasTier.LOW) .buildAndRegister(); @@ -1309,7 +1309,7 @@ public static void register() { .color(0x603c1a).secondaryColor(0x423e39).iconSet(METALLIC) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Magnesium, 1, Boron, 2) - .cableProperties(GTValues.V[MV], 4, 0, true, 78) + .cableProperties(GTValues.V[GTValues.MV], 4, GTValues.V[GTValues.LV], 500) .blastTemp(2500, GasTier.LOW, GTValues.VA[HV], 1000) .buildAndRegister(); @@ -1319,7 +1319,7 @@ public static void register() { .color(0x928547).secondaryColor(0x3f2e2e).iconSet(SHINY) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Mercury, 1, Barium, 2, Calcium, 2, Copper, 3, Oxygen, 8) - .cableProperties(GTValues.V[HV], 4, 0, true, 78) + .cableProperties(GTValues.V[GTValues.HV], 4, GTValues.V[GTValues.MV], 500) .blastTemp(3300, GasTier.LOW, GTValues.VA[HV], 1500) .buildAndRegister(); @@ -1329,7 +1329,7 @@ public static void register() { .color(0x457045).secondaryColor(0x66ff00).iconSet(RADIOACTIVE) .flags(DECOMPOSITION_BY_CENTRIFUGING) .components(Uranium238, 1, Platinum, 3) - .cableProperties(GTValues.V[GTValues.EV], 6, 0, true, 30) + .cableProperties(GTValues.V[GTValues.EV], 6, GTValues.V[GTValues.HV], 500) .blastTemp(4400, GasTier.MID, GTValues.VA[GTValues.EV], 1000) .buildAndRegister() .setFormula("UPt3", true); @@ -1340,7 +1340,7 @@ public static void register() { .color(0x850e85).secondaryColor(0x332f33).iconSet(SHINY) .flags(DECOMPOSITION_BY_CENTRIFUGING) .components(Samarium, 1, Iron, 1, Arsenic, 1, Oxygen, 1) - .cableProperties(GTValues.V[GTValues.IV], 6, 0, true, 30) + .cableProperties(GTValues.V[GTValues.IV], 6, GTValues.V[GTValues.EV], 500) .blastTemp(5200, GasTier.MID, GTValues.VA[GTValues.EV], 1500) .buildAndRegister(); @@ -1350,7 +1350,7 @@ public static void register() { .color(0x686760).secondaryColor(0x673300).iconSet(METALLIC) .flags(DECOMPOSITION_BY_ELECTROLYZING, GENERATE_FINE_WIRE) .components(Indium, 4, Tin, 2, Barium, 2, Titanium, 1, Copper, 7, Oxygen, 14) - .cableProperties(GTValues.V[GTValues.LuV], 8, 0, true, 5) + .cableProperties(GTValues.V[GTValues.LuV], 8, GTValues.V[GTValues.IV], 500) .blastTemp(6000, GasTier.HIGH, GTValues.VA[GTValues.IV], 1000) .buildAndRegister(); @@ -1360,7 +1360,7 @@ public static void register() { .color(0x232020).secondaryColor(0xff009c).iconSet(RADIOACTIVE) .flags(DECOMPOSITION_BY_CENTRIFUGING, GENERATE_FINE_WIRE) .components(Uranium238, 1, Rhodium, 1, Naquadah, 2) - .cableProperties(GTValues.V[GTValues.ZPM], 8, 0, true, 5) + .cableProperties(GTValues.V[GTValues.ZPM], 8, GTValues.V[LuV], 500) .blastTemp(9000, GasTier.HIGH, GTValues.VA[GTValues.IV], 1500) .buildAndRegister() .setFormula("URhNq2", true); @@ -1372,7 +1372,7 @@ public static void register() { .color(0xc6b083).secondaryColor(0x45063d).iconSet(METALLIC) .flags(DECOMPOSITION_BY_CENTRIFUGING, GENERATE_FINE_WIRE) .components(NaquadahEnriched, 4, Trinium, 3, Europium, 2, Duranium, 1) - .cableProperties(GTValues.V[GTValues.UV], 16, 0, true, 3) + .cableProperties(GTValues.V[GTValues.UV], 16, GTValues.V[GTValues.ZPM], 500) .blastTemp(9900, GasTier.HIGH, GTValues.VA[GTValues.LuV], 1000) .buildAndRegister(); @@ -1382,7 +1382,7 @@ public static void register() { .color(0x897b76).secondaryColor(0x00c0ff).iconSet(RADIOACTIVE) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Ruthenium, 1, Trinium, 2, Americium, 1, Neutronium, 2, Oxygen, 8) - .cableProperties(GTValues.V[GTValues.UHV], 24, 0, true, 3) + .cableProperties(GTValues.V[GTValues.UHV], 24, GTValues.V[GTValues.UV], 500) .blastTemp(10800, GasTier.HIGHER) .buildAndRegister(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/OrganicChemistryMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/OrganicChemistryMaterials.java index 545e3030f6..5644fe8598 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/OrganicChemistryMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/OrganicChemistryMaterials.java @@ -155,7 +155,7 @@ public static void register() { .toolStats( ToolProperty.Builder.of(1.0F, 1.0F, 512, 1, GTToolType.SOFT_MALLET, GTToolType.PLUNGER).build()) .components(Carbon, 2, Fluorine, 4) - .fluidPipeProperties(600, 100, true, true, false, false) + .fluidPipeProperties(600, 100, true, true, false) .buildAndRegister(); Sugar = new Material.Builder(GTCEu.id("sugar")) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java index e84809d2b4..8565875ea6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java @@ -304,7 +304,7 @@ public static void register() { .toolStats(ToolProperty.Builder.of(3.0F, 3.0F, 1536, 3) .attackSpeed(-0.2F).enchantability(5).build()) .rotorStats(130, 115, 3.0f, 1920) - .fluidPipeProperties(2073, 50, true, true, false, false) + .fluidPipeProperties(2073, 50, true, true, false) .blastTemp(1453, GasTier.LOW) .buildAndRegister(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java b/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java index 1b0cc7ee33..b949d8519c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/ColorSprayBehaviour.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.component.IAddInformation; import com.gregtechceu.gtceu.api.item.component.IDurabilityBar; import com.gregtechceu.gtceu.api.item.component.IInteractionItem; @@ -339,9 +340,9 @@ private boolean tryPaintSpecialBlock(Player player, Level world, BlockPos pos, B } // PipeBlockEntity special case - if (be instanceof PipeBlockEntity pipe) { + if (be instanceof PipeBlockEntity pipe) { if (pipe.getPaintingColor() != this.color.getTextColor()) { - pipe.setPaintingColor(this.color.getTextColor()); + pipe.setPaintingColor(this.color.getTextColor(), false); return true; } else return false; } @@ -442,9 +443,9 @@ private static boolean tryStripBlockColor(Player player, Level world, BlockPos p } // PipeBlockEntity special case - if (be instanceof PipeBlockEntity pipe) { + if (be instanceof PipeBlockEntity pipe) { if (pipe.isPainted()) { - pipe.setPaintingColor(pipe.getDefaultPaintingColor()); + pipe.setPaintingColor(pipe.getDefaultPaintingColor(), false); return true; } else return false; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index 4b9f2adc2f..2e594076f5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -8,6 +8,7 @@ import com.gregtechceu.gtceu.api.capability.IWorkable; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.data.worldgen.bedrockfluid.BedrockFluidVeinSavedData; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.component.IAddInformation; import com.gregtechceu.gtceu.api.item.component.IInteractionItem; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; @@ -24,6 +25,7 @@ import com.gregtechceu.gtceu.utils.FormattingUtil; import com.gregtechceu.gtceu.utils.GTUtil; +import com.simibubi.create.content.fluids.pipes.FluidPipeBlockEntity; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -358,10 +360,10 @@ else if (machine instanceof IDataInfoProvider) list.addAll(provider.getDataInfo(mode)); } - } else if (tileEntity instanceof PipeBlockEntity pipe) { + } else if (tileEntity instanceof PipeBlockEntity pipe) { // Pipes need special name handling - list.add(pipe.getPipeBlock().getName().withStyle(ChatFormatting.BLUE)); + list.add(pipe.getBlockType().getName().withStyle(ChatFormatting.BLUE)); // Pipe-specific info if (tileEntity instanceof IDataInfoProvider dataInfoProvider) { @@ -369,7 +371,7 @@ else if (machine instanceof IDataInfoProvider) list.addAll(dataInfoProvider.getDataInfo(mode)); } - if (tileEntity instanceof FluidPipeBlockEntity) { + if (tileEntity.getCapability(ForgeCapabilities.FLUID_HANDLER).isPresent()) { // Getting fluid info always costs 500 energyCost += 500; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java index ae71c861ea..e82c2062cc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.IControllable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java index 8d5f55b3a1..84bbd4050b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java @@ -13,6 +13,7 @@ import com.gregtechceu.gtceu.api.machine.feature.IInteractedMachine; import com.gregtechceu.gtceu.api.machine.trait.NotifiableFluidTank; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialFluidProperties; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.side.fluid.FluidActionResult; import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; @@ -95,7 +96,7 @@ public ManagedFieldHolder getFieldHolder() { protected NotifiableFluidTank createCacheFluidHandler(Object... args) { return new NotifiableFluidTank(this, 1, maxStoredFluids, IO.BOTH) - .setFilter(material.getProperty(PropertyKey.FLUID_PIPE)); + .setFilter(material.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY)); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index 0432ced2a1..c800524b4a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -3,7 +3,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.data.GTDamageTypes; @@ -27,7 +27,7 @@ import java.util.Map; -public class CableBlock extends PipeMaterialBlock implements IBurnable { +public class CableBlock extends MaterialPipeBlock implements IBurnable { private static final Map> CACHE = new Object2ObjectOpenHashMap<>(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index 9f252de3b1..5b1987ae6b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -4,9 +4,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IInsulatable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; +import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -75,6 +77,11 @@ public AbstractPipeModel getModel() { return model; } + @Override + public ResourceTexture getPipeTexture(boolean isBlock) { + return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; + } + @Override public boolean isPaintable() { return true; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java index 8e19254044..a5fe0205f8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java @@ -1,14 +1,13 @@ package com.gregtechceu.gtceu.common.pipelike.block.duct; import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; -import com.gregtechceu.gtceu.api.item.tool.GTToolType; -import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.handlers.DuctNetHandler; + import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; + import org.jetbrains.annotations.NotNull; public class DuctPipeBlock extends PipeBlock { @@ -23,7 +22,7 @@ protected String getConnectLangKey() { } @Override - protected boolean allowsBlocking() { + public boolean allowsBlocking() { return false; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java index c5b5972551..242154c7c2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -5,7 +5,9 @@ import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.DuctPipeModel; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; @@ -21,19 +23,6 @@ public record DuctStructure(String name, float renderThickness, float rateMultip PipeStructureRegistry.register(this); } - @Override - public boolean canConnectTo(Direction side, byte connectionMask) { - byte connectionCount = 0; - for (Direction facing : GTUtil.DIRECTIONS) { - if (facing == side) continue; - if (GTUtil.evalMask(facing, connectionMask)) { - connectionCount++; - } - if (connectionCount > 1) return false; - } - return true; - } - @Override public @NotNull String getSerializedName() { return name; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java index 9b19e83b9e..d4b075f68e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.block.laser; import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.ActivablePipeBlock; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.LaserNetHandler; @@ -12,7 +12,7 @@ import org.jetbrains.annotations.NotNull; -public class LaserPipeBlock extends PipeActivableBlock { +public class LaserPipeBlock extends ActivablePipeBlock { public LaserPipeBlock(BlockBehaviour.Properties properties, LaserStructure structure) { super(properties, structure); @@ -29,7 +29,7 @@ protected String getConnectLangKey() { } @Override - protected boolean allowsBlocking() { + public boolean allowsBlocking() { return false; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java index 61f53d6cb9..5f80da6dc3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.block.optical; import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeActivableBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.ActivablePipeBlock; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.DuctNetHandler; @@ -12,7 +12,7 @@ import org.jetbrains.annotations.NotNull; -public class OpticalPipeBlock extends PipeActivableBlock { +public class OpticalPipeBlock extends ActivablePipeBlock { public OpticalPipeBlock(BlockBehaviour.Properties properties, OpticalStructure structure) { super(properties, structure); @@ -29,7 +29,7 @@ protected String getConnectLangKey() { } @Override - protected boolean allowsBlocking() { + public boolean allowsBlocking() { return false; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java index f451940b49..3b855af001 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -3,11 +3,11 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import net.minecraft.world.level.block.state.BlockBehaviour; -public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, IFreezable { +public class MaterialPipeBlock extends com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock + implements IBurnable, IFreezable { public MaterialPipeBlock(BlockBehaviour.Properties properties, MaterialPipeStructure structure, Material material) { super(properties, structure, material); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java index 0d92e5a4dd..b402f60dda 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/DuctNetHandler.java @@ -4,14 +4,15 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctStructure; -import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.net.optical.WorldOpticalNet; + import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; + import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -56,4 +57,3 @@ public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNu tooltip.add(Component.translatable("block.gtceu.normal_optical_pipe.tooltip")); } } - diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java index e192754ecf..6dc6edf2bf 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java @@ -25,6 +25,7 @@ import com.gregtechceu.gtceu.common.pipelike.net.energy.VoltageLossLogic; import com.gregtechceu.gtceu.common.pipelike.net.energy.WorldEnergyNet; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; @@ -32,9 +33,10 @@ import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.material.Fluid; + +import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import snownee.jade.api.BlockAccessor; import java.util.List; @@ -46,6 +48,7 @@ public final class MaterialEnergyProperties implements PipeNetProperties.IPipeNe public static final MaterialPropertyKey KEY = new MaterialPropertyKey<>( "EnergyProperties"); + @Getter private final long voltageLimit; private final long amperageLimit; private int materialMeltTemperature; @@ -71,10 +74,6 @@ public MaterialEnergyProperties(long voltageLimit, long amperageLimit, long loss this.superconductorCriticalTemperature = superconductorCriticalTemperature; } - public long getVoltageLimit() { - return voltageLimit; - } - public static MaterialEnergyProperties create(long voltageLimit, long amperageLimit, long lossPerAmp, int superconductorCriticalTemperature) { return new MaterialEnergyProperties(voltageLimit, amperageLimit, lossPerAmp, @@ -85,8 +84,8 @@ public static MaterialEnergyProperties create(long voltageLimit, long amperageLi return new MaterialEnergyProperties(voltageLimit, amperageLimit, lossPerAmp, 0); } - public static TagPrefix.MaterialRecipeHandler registrationHandler(TagPrefix.MaterialRecipeHandler handler) { - return (orePrefix, material, properties, provider) -> { + public static TagPrefix.MaterialRecipeHandler registrationHandler(TagPrefix.PropertyMaterialRecipeHandler handler) { + return (orePrefix, material, provider) -> { if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && !material.hasFlag(NO_UNIFICATION) && material.getProperty(PropertyKey.PIPENET_PROPERTIES).hasProperty(KEY)) { handler.accept(orePrefix, material, @@ -210,7 +209,7 @@ private long getLoss(IPipeStructure structure) { } else return lossPerAmp; } - private long getAmperage(IPipeStructure structure) { + public long getAmperage(IPipeStructure structure) { if (structure instanceof CableStructure cable) { return amperageLimit * cable.material(); } else if (structure instanceof MaterialPipeStructure pipe) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java index 04a52860c8..b48a9b7714 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java @@ -20,19 +20,19 @@ import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidContainmentLogic; import com.gregtechceu.gtceu.common.pipelike.net.fluid.WorldFluidNet; import com.gregtechceu.gtceu.utils.FormattingUtil; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import lombok.Getter; + import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.UnmodifiableView; -import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Set; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java index a696bda81f..b10f652fe8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java @@ -13,12 +13,14 @@ import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; import com.gregtechceu.gtceu.common.pipelike.net.item.WorldItemNet; import com.gregtechceu.gtceu.utils.FormattingUtil; + import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java index f5bead17a3..bc51a9f5ef 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/DuctCapabilityObject.java @@ -14,14 +14,17 @@ import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.feature.IEnvironmentalHazardCleaner; import com.gregtechceu.gtceu.common.capability.EnvironmentalHazardSavedData; + import com.lowdragmc.lowdraglib.Platform; -import lombok.Setter; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.server.level.ServerLevel; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; + +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -67,7 +70,8 @@ public boolean inputsHazard(Direction side, MedicalCondition condition) { WorldPipeNetNode destination = path.getTargetNode(); for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { IHazardParticleContainer container = capability.getValue() - .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()) + .resolve() .orElse(null); if (container != null && container.inputsHazard(side, condition)) { return true; @@ -85,7 +89,8 @@ public float changeHazard(MedicalCondition condition, float differenceAmount) { WorldPipeNetNode destination = path.getTargetNode(); for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { IHazardParticleContainer handler = capability.getValue() - .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()) + .resolve() .orElse(null); if (handler == null) { if (net.getLevel().getBlockEntity(path.getTargetNode().getEquivalencyData() @@ -99,7 +104,8 @@ public float changeHazard(MedicalCondition condition, float differenceAmount) { savedData.addZone(path.getTargetNode().getEquivalencyData().relative(capability.getKey()), differenceAmount, true, HazardProperty.HazardTrigger.INHALATION, condition); total += differenceAmount; - emitPollutionParticles((ServerLevel) net.getLevel(), path.getTargetNode().getEquivalencyData(), capability.getKey()); + emitPollutionParticles((ServerLevel) net.getLevel(), path.getTargetNode().getEquivalencyData(), + capability.getKey()); break; } float change = handler.changeHazard(condition, differenceAmount); @@ -121,7 +127,8 @@ public float getHazardStored(MedicalCondition condition) { WorldPipeNetNode destination = path.getTargetNode(); for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { IHazardParticleContainer handler = capability.getValue() - .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()) + .resolve() .orElse(null); if (handler != null) { total += handler.getHazardStored(condition); @@ -139,7 +146,8 @@ public float getHazardCapacity(MedicalCondition condition) { WorldPipeNetNode destination = path.getTargetNode(); for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { IHazardParticleContainer handler = capability.getValue() - .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()).resolve() + .getCapability(GTCapability.CAPABILITY_HAZARD_CONTAINER, capability.getKey().getOpposite()) + .resolve() .orElse(null); if (handler != null) { total += handler.getHazardCapacity(condition); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java index 720caf4f1d..5c940b5e31 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java @@ -8,8 +8,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; + import net.minecraft.server.level.ServerLevel; import net.minecraftforge.common.capabilities.Capability; + import org.jetbrains.annotations.Nullable; import java.util.Iterator; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/AveragingPerTickCounter.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/AveragingPerTickCounter.java new file mode 100644 index 0000000000..888512749e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/AveragingPerTickCounter.java @@ -0,0 +1,83 @@ +package com.gregtechceu.gtceu.common.pipelike.net.energy; + +import java.util.Arrays; + +public class AveragingPerTickCounter { + + private final long defaultValue; + private final long[] values; + private long lastUpdatedWorldTime = 0; + private int currentIndex = 0; + private boolean dirty = true; + private double lastAverage = 0; + + public AveragingPerTickCounter() { + this(0, 20); + } + + /** + * Averages a value over a certain amount of ticks + * + * @param defaultValue self-explanatory + * @param length amount of ticks to average (20 for 1 second) + */ + public AveragingPerTickCounter(long defaultValue, int length) { + this.defaultValue = defaultValue; + this.values = new long[length]; + Arrays.fill(values, defaultValue); + } + + private void checkValueState(long currentWorldTime) { + if (currentWorldTime != lastUpdatedWorldTime) { + long dif = currentWorldTime - lastUpdatedWorldTime; + if (dif >= values.length || dif < 0) { + Arrays.fill(values, defaultValue); + currentIndex = 0; + } else { + for (int i = currentIndex + 1; i <= currentIndex + dif; i++) { + values[i % values.length] = defaultValue; + } + currentIndex += dif; + if (currentIndex >= values.length) + currentIndex = currentIndex % values.length; + } + this.lastUpdatedWorldTime = currentWorldTime; + dirty = true; + } + } + + /** + * @return the value from the current tick + */ + public long getLast(long currentTick) { + checkValueState(currentTick); + return values[currentIndex]; + } + + /** + * @return the average of all values + */ + public double getAverage(long currentTick) { + checkValueState(currentTick); + if (!dirty) + return lastAverage; + dirty = false; + return lastAverage = Arrays.stream(values).sum() / (double) (values.length); + } + + /** + * @param value the value to increment the current value by + */ + public void increment(long currentTick, long value) { + checkValueState(currentTick); + values[currentIndex] += value; + } + + /** + * @param value the value to set current value to + */ + public void set(long currentTick, long value) { + checkValueState(currentTick); + values[currentIndex] = value; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java index bec8654ea2..f9bd23c1b7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java @@ -8,6 +8,7 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import lombok.Getter; import org.jetbrains.annotations.NotNull; import java.util.Collections; @@ -17,23 +18,27 @@ public class EnergyFlowLogic extends NetLogicEntry { public static final EnergyFlowLogic INSTANCE = new EnergyFlowLogic(); + private final AveragingPerTickCounter averageVoltageCounter = new AveragingPerTickCounter(); + private final AveragingPerTickCounter averageAmperageCounter = new AveragingPerTickCounter(); + private static final int MEMORY_TICKS = 10; + @Getter + @NotNull private final Long2ObjectOpenHashMap> memory = new Long2ObjectOpenHashMap<>(); protected EnergyFlowLogic() { super("EnergyFlow"); } - public @NotNull Long2ObjectOpenHashMap> getMemory() { - return memory; - } - public @NotNull List getFlow(long tick) { return memory.getOrDefault(tick, Collections.emptyList()); } public void recordFlow(long tick, EnergyFlowData flow) { + averageVoltageCounter.increment(tick, flow.getEU()); + averageAmperageCounter.increment(tick, flow.amperage()); + updateMemory(tick); memory.compute(tick, (k, v) -> { if (v == null) v = new ObjectArrayList<>(); @@ -52,6 +57,14 @@ private void updateMemory(long tick) { } } + public double getAverageAmperage(long currentTick) { + return averageAmperageCounter.getAverage(currentTick); + } + + public double getAverageVoltage(long currentTick) { + return averageVoltageCounter.getAverage(currentTick); + } + @Override public ByteTag serializeNBT() { return ByteTag.valueOf((byte) 0); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java index d2bcf13ce3..acc7573251 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/IFluidTransferController.java @@ -32,7 +32,7 @@ public interface IFluidTransferController { IFluidTransferController NO_PASSAGE = new IFluidTransferController() { @Override - public long insertToHandler(@NotNull FluidTestObject testObject, int amount, + public long insertToHandler(@NotNull FluidTestObject testObject, long amount, @NotNull IFluidTransfer destHandler, boolean doFill) { return 0; } @@ -47,7 +47,7 @@ public long insertToHandler(@NotNull FluidTestObject testObject, int amount, /** * @return the amount filled. */ - default long insertToHandler(@NotNull FluidTestObject testObject, int amount, @NotNull IFluidTransfer destHandler, + default long insertToHandler(@NotNull FluidTestObject testObject, long amount, @NotNull IFluidTransfer destHandler, boolean doFill) { return destHandler.fill(testObject.recombine(amount), doFill); } diff --git a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java index e9fa2fb375..b02da3d259 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java @@ -99,9 +99,6 @@ public static void generateGTDynamicTags(Map { MixinHelpers.addMaterialBlockTags(tagMap, prefix, map); }); - GTBlocks.ITEM_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { - MixinHelpers.addMaterialBlockTags(tagMap, prefix, map); - }); GTRegistries.MACHINES.forEach(machine -> { ResourceLocation id = machine.getId(); tagMap.computeIfAbsent(GTToolType.WRENCH.harvestTags.get(0).location(), path -> new ArrayList<>()) @@ -249,9 +246,6 @@ public static void generateGTDynamicLoot(Map lootTa GTBlocks.MATERIAL_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { MixinHelpers.addMaterialBlockLootTables(lootTables, prefix, map); }); - GTBlocks.ITEM_PIPE_BLOCKS.rowMap().forEach((prefix, map) -> { - MixinHelpers.addMaterialBlockLootTables(lootTables, prefix, map); - }); GTBlocks.SURFACE_ROCK_BLOCKS.forEach((material, blockEntry) -> { ResourceLocation lootTableId = new ResourceLocation(blockEntry.getId().getNamespace(), "blocks/" + blockEntry.getId().getPath()); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PartsRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PartsRecipeHandler.java index b846c07bbb..c56b640e59 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PartsRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PartsRecipeHandler.java @@ -8,6 +8,7 @@ import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.common.data.GTMaterials; import com.gregtechceu.gtceu.common.item.TurbineRotorBehaviour; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; import com.gregtechceu.gtceu.data.recipe.builder.GTRecipeBuilder; @@ -149,7 +150,8 @@ public static void processFineWire(TagPrefix fineWirePrefix, Material material, VanillaRecipeHelper.addShapelessRecipe(provider, String.format("fine_wire_%s", material.getName()), fineWireStack, 'x', new UnificationEntry(foil, material)); - if (material.hasProperty(PropertyKey.WIRE)) { + if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && + material.getProperty(PropertyKey.PIPENET_PROPERTIES).hasProperty(MaterialEnergyProperties.KEY)) { WIREMILL_RECIPES.recipeBuilder("mill_" + material.getName() + "_wire_to_fine_wire") .inputItems(wireGtSingle, material) .outputItems(wireFine, material, 4) diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java index 5bb9065273..1c610837a6 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/PipeRecipeHandler.java @@ -12,6 +12,7 @@ import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; import com.gregtechceu.gtceu.utils.FormattingUtil; import com.gregtechceu.gtceu.utils.GTUtil; + import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.world.item.ItemStack; @@ -35,15 +36,21 @@ public static void init(Consumer provider) { pipeQuadruple.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeQuadruple); pipeNonuple.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processPipeNonuple); - pipeTinyRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); - pipeSmallRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + pipeTinyRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, + PipeRecipeHandler::processRestrictivePipe); + pipeSmallRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, + PipeRecipeHandler::processRestrictivePipe); pipeNormalRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); - pipeLargeRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); - pipeHugeRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + pipeLargeRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, + PipeRecipeHandler::processRestrictivePipe); + pipeHugeRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, + PipeRecipeHandler::processRestrictivePipe); - pipeQuadrupleRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); - pipeNonupleRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, PipeRecipeHandler::processRestrictivePipe); + pipeQuadrupleRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, + PipeRecipeHandler::processRestrictivePipe); + pipeNonupleRestrictive.executeHandler(provider, PropertyKey.PIPENET_PROPERTIES, + PipeRecipeHandler::processRestrictivePipe); addDuctRecipes(provider, Steel, 2); addDuctRecipes(provider, StainlessSteel, 4); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireCombiningHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireCombiningHandler.java index 7e1ae80325..2ef36bcac1 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireCombiningHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireCombiningHandler.java @@ -3,11 +3,10 @@ import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; import com.gregtechceu.gtceu.api.data.chemical.material.stack.UnificationEntry; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.common.data.GTMaterials; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; import net.minecraft.data.recipes.FinishedRecipe; @@ -36,20 +35,24 @@ public class WireCombiningHandler { public static void init(Consumer provider) { // Generate Wire Packer/Unpacker recipes - wireGtSingle.executeHandler(provider, PropertyKey.WIRE, WireCombiningHandler::processWireCompression); + wireGtSingle.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireCombiningHandler::processWireCompression)); // Generate manual recipes for combining Wires/Cables for (TagPrefix wirePrefix : WIRE_DOUBLING_ORDER) { - wirePrefix.executeHandler(provider, PropertyKey.WIRE, WireCombiningHandler::generateWireCombiningRecipe); + wirePrefix.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireCombiningHandler::generateWireCombiningRecipe)); } // Generate Cable -> Wire recipes in the unpacker for (TagPrefix cablePrefix : cableToWireMap.keySet()) { - cablePrefix.executeHandler(provider, PropertyKey.WIRE, WireCombiningHandler::processCableStripping); + cablePrefix.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireCombiningHandler::processCableStripping)); } } - private static void generateWireCombiningRecipe(TagPrefix wirePrefix, Material material, WireProperties property, + private static void generateWireCombiningRecipe(TagPrefix wirePrefix, Material material, + MaterialEnergyProperties property, Consumer provider) { int wireIndex = ArrayUtils.indexOf(WIRE_DOUBLING_ORDER, wirePrefix); @@ -79,7 +82,7 @@ private static void generateWireCombiningRecipe(TagPrefix wirePrefix, Material m } } - private static void processWireCompression(TagPrefix prefix, Material material, WireProperties property, + private static void processWireCompression(TagPrefix prefix, Material material, MaterialEnergyProperties property, Consumer provider) { for (int startTier = 0; startTier < 4; startTier++) { for (int i = 1; i < 5 - startTier; i++) { @@ -100,7 +103,7 @@ private static void processWireCompression(TagPrefix prefix, Material material, } } - private static void processCableStripping(TagPrefix prefix, Material material, WireProperties property, + private static void processCableStripping(TagPrefix prefix, Material material, MaterialEnergyProperties property, Consumer provider) { PACKER_RECIPES.recipeBuilder("strip_" + material.getName() + "_" + prefix.name) .inputItems(prefix, material) diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireRecipeHandler.java index ca88de6e84..d84ec49142 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/generated/WireRecipeHandler.java @@ -4,10 +4,10 @@ import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.WireProperties; import com.gregtechceu.gtceu.api.data.chemical.material.stack.UnificationEntry; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.common.data.GTItems; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; import com.gregtechceu.gtceu.data.recipe.VanillaRecipeHelper; import com.gregtechceu.gtceu.data.recipe.builder.GTRecipeBuilder; import com.gregtechceu.gtceu.utils.GTUtil; @@ -61,17 +61,23 @@ public static void init(Consumer provider) { // Wiremill: 1x Wire -> Fine // Extruder: Ingot -> 1x Wire // Wire Cutter: Plate -> 1x Wire - wireGtSingle.executeHandler(provider, PropertyKey.WIRE, WireRecipeHandler::processWires); + wireGtSingle.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireRecipeHandler::processWires)); // Generate Cable Covering Recipes - wireGtSingle.executeHandler(provider, PropertyKey.WIRE, WireRecipeHandler::generateCableCovering); - wireGtDouble.executeHandler(provider, PropertyKey.WIRE, WireRecipeHandler::generateCableCovering); - wireGtQuadruple.executeHandler(provider, PropertyKey.WIRE, WireRecipeHandler::generateCableCovering); - wireGtOctal.executeHandler(provider, PropertyKey.WIRE, WireRecipeHandler::generateCableCovering); - wireGtHex.executeHandler(provider, PropertyKey.WIRE, WireRecipeHandler::generateCableCovering); + wireGtSingle.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireRecipeHandler::generateCableCovering)); + wireGtDouble.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireRecipeHandler::generateCableCovering)); + wireGtQuadruple.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireRecipeHandler::generateCableCovering)); + wireGtOctal.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireRecipeHandler::generateCableCovering)); + wireGtHex.executeHandler(provider, + MaterialEnergyProperties.registrationHandler(WireRecipeHandler::generateCableCovering)); } - public static void processWires(TagPrefix wirePrefix, Material material, WireProperties property, + public static void processWires(TagPrefix wirePrefix, Material material, MaterialEnergyProperties property, Consumer provider) { TagPrefix prefix = material.hasProperty(PropertyKey.INGOT) ? ingot : material.hasProperty(PropertyKey.GEM) ? gem : dust; @@ -120,14 +126,14 @@ public static void processWires(TagPrefix wirePrefix, Material material, WirePro } } - public static void generateCableCovering(TagPrefix wirePrefix, Material material, WireProperties property, + public static void generateCableCovering(TagPrefix wirePrefix, Material material, MaterialEnergyProperties property, Consumer provider) { // Superconductors have no Cables, so exit early if (property.isSuperconductor()) return; int cableAmount = (int) (wirePrefix.getMaterialAmount(material) * 2 / M); TagPrefix cablePrefix = TagPrefix.get("cable" + wirePrefix.name().substring(4)); - int voltageTier = GTUtil.getTierByVoltage(property.getVoltage()); + int voltageTier = GTUtil.getTierByVoltage(property.getVoltageLimit()); int insulationAmount = INSULATION_AMOUNT.get(cablePrefix); // Generate hand-crafting recipes for ULV and LV cables diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java index bb532e2707..22ecab822c 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComponentRecipes.java @@ -488,12 +488,12 @@ public static void init(Consumer provider) { VanillaRecipeHelper.addShapedRecipe(provider, true, "cover_item_voiding", COVER_ITEM_VOIDING.asStack(), "SDS", "dPw", " E ", 'S', new UnificationEntry(screw, Steel), 'D', COVER_ITEM_DETECTOR.asStack(), 'P', - new UnificationEntry(pipeNormalItem, Brass), 'E', Items.ENDER_PEARL); + new UnificationEntry(pipeNormal, Brass), 'E', Items.ENDER_PEARL); ASSEMBLER_RECIPES.recipeBuilder("cover_item_voiding") .inputItems(screw, Steel, 2) .inputItems(COVER_ITEM_DETECTOR) - .inputItems(pipeNormalItem, Brass) + .inputItems(pipeNormal, Brass) .inputItems(Items.ENDER_PEARL) .outputItems(COVER_ITEM_VOIDING) .duration(100).EUt(VA[LV]).save(provider); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java index 75dd30b5d4..9e0b94254f 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityLoader.java @@ -1047,7 +1047,7 @@ public static void init(Consumer provider) { new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Polyethylene)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_mv", GTBlocks.HERMETIC_CASING_MV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.Aluminium), 'F', - new UnificationEntry(TagPrefix.pipeLargeItem, GTMaterials.PolyvinylChloride)); + new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.PolyvinylChloride)); VanillaRecipeHelper.addShapedRecipe(provider, true, "hermetic_casing_hv", GTBlocks.HERMETIC_CASING_HV.asStack(), "PPP", "PFP", "PPP", 'P', new UnificationEntry(TagPrefix.plate, GTMaterials.StainlessSteel), 'F', new UnificationEntry(TagPrefix.pipeLarge, GTMaterials.Polytetrafluoroethylene)); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java index 096c49db33..c51f823f36 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MetaTileEntityMachineRecipeLoader.java @@ -514,7 +514,7 @@ public static void init(Consumer provider) { // Long Distance Pipes ASSEMBLER_RECIPES.recipeBuilder("long_distance_item_endpoint") - .inputItems(pipeLargeItem, Tin, 2) + .inputItems(pipeLarge, Tin, 2) .inputItems(plate, Steel, 8) .inputItems(gear, Steel, 2) .circuitMeta(1) @@ -534,7 +534,7 @@ public static void init(Consumer provider) { .save(provider); ASSEMBLER_RECIPES.recipeBuilder("long_distance_item_pipe") - .inputItems(pipeLargeItem, Tin, 2) + .inputItems(pipeLarge, Tin, 2) .inputItems(plate, Steel, 8) .circuitMeta(2) .inputFluids(SolderingAlloy.getFluid(L / 2)) diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java index bbfd1684e6..6370913da9 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java @@ -1,6 +1,8 @@ package com.gregtechceu.gtceu.integration.jade; import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.integration.jade.provider.*; @@ -44,7 +46,7 @@ public void register(IWailaCommonRegistration registration) { registration.registerBlockDataProvider(new MEPatternBufferProvider(), BlockEntity.class); } - registration.registerFluidStorage(FluidPipeStorageProvider.INSTANCE, FluidPipeBlockEntity.class); + registration.registerFluidStorage(FluidPipeStorageProvider.INSTANCE, MaterialPipeBlockEntity.class); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java index 1867173ff7..316dca271a 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java @@ -2,14 +2,19 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeMaterialBlockEntity; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.WorldEnergyNet; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.block.entity.BlockEntity; import snownee.jade.api.BlockAccessor; @@ -51,19 +56,29 @@ public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPlugi public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccessor) { CompoundTag data = compoundTag.getCompound(getUid().toString()); if (blockAccessor.getBlock() instanceof CableBlock cableBlock) { - PipeMaterialBlockEntity cable = cableBlock.getBlockEntity(blockAccessor.getLevel(), - blockAccessor.getPosition()); - if (cable != null) { - var cableData = new CompoundTag(); - // TODO fix - /* - * cableData.putLong("maxVoltage", cable.getMaxVoltage()); - * cableData.putLong("currentVoltage", cable.getCurrentMaxVoltage()); - * cableData.putDouble("maxAmperage", cable.getMaxAmperage()); - * cableData.putDouble("currentAmperage", cable.getAverageAmperage()); - */ - data.put("cableData", cableData); + if (!(blockAccessor.getLevel() instanceof ServerLevel serverLevel)) { + compoundTag.put(getUid().toString(), data); + return; } + WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(blockAccessor.getPosition()); + EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + + long currentTick = serverLevel.getServer().getTickCount(); + long totalVoltage = 0L; + double averageAmperage = logic.getAverageAmperage(currentTick); + for (var flow : logic.getFlow(currentTick)) { + totalVoltage += flow.voltage(); + } + + var cableData = new CompoundTag(); + cableData.putLong("maxVoltage", cableBlock.material.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialEnergyProperties.KEY).getVoltageLimit()); + cableData.putLong("currentVoltage", totalVoltage); + cableData.putDouble("maxAmperage", cableBlock.material.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialEnergyProperties.KEY).getAmperage(cableBlock.getStructure())); + cableData.putDouble("currentAmperage", averageAmperage); + + data.put("cableData", cableData); } compoundTag.put(getUid().toString(), data); } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java index 3ce8297bc4..221cea60e3 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java @@ -2,12 +2,14 @@ import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import snownee.jade.api.Accessor; import snownee.jade.api.fluid.JadeFluidObject; @@ -16,7 +18,7 @@ import java.util.ArrayList; import java.util.List; -public enum FluidPipeStorageProvider implements IServerExtensionProvider, +public enum FluidPipeStorageProvider implements IServerExtensionProvider, IClientExtensionProvider { INSTANCE; @@ -32,15 +34,17 @@ public List> getClientGroups(Accessor accessor, Li } @Override - public @Nullable List> getGroups(ServerPlayer serverPlayer, ServerLevel serverLevel, - FluidPipeBlockEntity pipe, boolean showDetails) { + public @NotNull List> getGroups(ServerPlayer serverPlayer, ServerLevel serverLevel, + MaterialPipeBlockEntity pipe, boolean showDetails) { List> tanks = new ArrayList<>(); + /* for (var tank : pipe.getFluidTanks()) { if (tank.getFluidAmount() > 0) { tanks.add(new ViewGroup<>(List.of(FluidView.writeDefault( JadeFluidObject.of(tank.getFluid().getFluid(), tank.getFluidAmount()), tank.getCapacity())))); } } + */ return tanks; } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java index 7fdec9b942..12d93469b7 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.integration.jade.provider; import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MetaMachine; @@ -40,7 +41,7 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso int paintingColor = metaMachine.getPaintingColor(); compoundTag.putInt("StainedColor", paintingColor); } - } else if (blockAccessor.getBlockEntity() instanceof PipeBlockEntity pipe) { + } else if (blockAccessor.getBlockEntity() instanceof PipeBlockEntity pipe) { int paintingColor = pipe.getPaintingColor(); compoundTag.putInt("StainedColor", paintingColor); } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java index 373425ec23..7b5b3dc90d 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java @@ -1,14 +1,26 @@ package com.gregtechceu.gtceu.integration.top.provider; import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.WorldEnergyNet; +import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import mcjty.theoneprobe.api.*; +import static com.gregtechceu.gtceu.utils.FormattingUtil.DECIMAL_FORMAT_1F; + public class CableInfoProvider implements IProbeInfoProvider { @Override @@ -19,30 +31,38 @@ public ResourceLocation getID() { @Override public void addProbeInfo(ProbeMode probeMode, IProbeInfo iProbeInfo, Player player, Level level, BlockState blockState, IProbeHitData iProbeHitData) { - // TODO fix - /* - * if (blockState.getBlock() instanceof CableBlock cableBlock) { - * CableBlockEntity cable = (CableBlockEntity) cableBlock.getPipeTile(level, iProbeHitData.getPos()); - * if (cable != null) { - * long voltage = cable.getCurrentMaxVoltage(); - * double amperage = cable.getAverageAmperage(); - * IProbeInfo horizontalPane = iProbeInfo - * .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); - * horizontalPane.text(Component.translatable("gtceu.top.cable_voltage")); - * if (voltage != 0) { - * horizontalPane.text(GTValues.VNF[GTUtil.getTierByVoltage(voltage)]).text(" / "); - * } - * horizontalPane.text(GTValues.VNF[GTUtil.getTierByVoltage(cable.getMaxVoltage())]); - * - * horizontalPane = iProbeInfo - * .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); - * horizontalPane.text(Component.translatable("gtceu.top.cable_amperage")); - * if (amperage != 0) { - * horizontalPane.text(DECIMAL_FORMAT_1F.format(cable.getAverageAmperage()) + "A / "); - * } - * horizontalPane.text(DECIMAL_FORMAT_1F.format(cable.getMaxAmperage()) + "A"); - * } - * } - */ + if (blockState.getBlock() instanceof CableBlock cableBlock) { + if (!(level instanceof ServerLevel serverLevel)) { + return; + } + WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(iProbeHitData.getPos()); + EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + + long currentTick = serverLevel.getServer().getTickCount(); + long totalVoltage = 0L; + double averageAmperage = logic.getAverageAmperage(currentTick); + for (var flow : logic.getFlow(currentTick)) { + totalVoltage += flow.voltage(); + } + + IProbeInfo horizontalPane = iProbeInfo + .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); + horizontalPane.text(Component.translatable("gtceu.top.cable_voltage")); + if (totalVoltage != 0) { + horizontalPane.text(GTValues.VNF[GTUtil.getTierByVoltage(totalVoltage)]).text(" / "); + } + horizontalPane.text( + GTValues.VNF[GTUtil.getTierByVoltage(cableBlock.material.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialEnergyProperties.KEY).getVoltageLimit())]); + + horizontalPane = iProbeInfo + .horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)); + horizontalPane.text(Component.translatable("gtceu.top.cable_amperage")); + if (averageAmperage != 0) { + horizontalPane.text(DECIMAL_FORMAT_1F.format(averageAmperage) + "A / "); + } + horizontalPane.text(DECIMAL_FORMAT_1F.format(cableBlock.material.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialEnergyProperties.KEY).getAmperage(cableBlock.getStructure())) + "A"); + } } } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java index 49d131dda6..5241671cbd 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/StainedColorProvider.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.integration.top.provider; import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import net.minecraft.network.chat.Component; @@ -32,7 +33,7 @@ public void addProbeInfo(ProbeMode probeMode, IProbeInfo iProbeInfo, Player play int paintingColor = -1; if (blockEntity instanceof IMachineBlockEntity machineBlockEntity) { paintingColor = machineBlockEntity.getMetaMachine().getPaintingColor(); - } else if (blockEntity instanceof PipeBlockEntity pipe) { + } else if (blockEntity instanceof PipeBlockEntity pipe) { paintingColor = pipe.getPaintingColor(); } if (paintingColor != -1) { diff --git a/src/main/java/com/gregtechceu/gtceu/utils/TriConsumer.java b/src/main/java/com/gregtechceu/gtceu/utils/TriConsumer.java new file mode 100644 index 0000000000..f61650ded4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/utils/TriConsumer.java @@ -0,0 +1,7 @@ +package com.gregtechceu.gtceu.utils; + +@FunctionalInterface +public interface TriConsumer { + + void accept(T t, U u, S s); +} From a26d80064838b93f6d7d570b3d2792a9de14839c Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 24 Aug 2024 00:06:48 +0300 Subject: [PATCH 11/70] rendering does nnnnot work just yet, placing a block crashes because shadow is being a lil bitch --- dependencies.gradle | 3 +- gradle/scripts/jars.gradle | 7 + settings.gradle | 4 +- .../gtceu/api/cover/filter/Filter.java | 1 - .../gtceu/api/cover/filter/FluidFilter.java | 5 +- .../gtceu/api/cover/filter/ItemFilter.java | 5 +- .../api/cover/filter/SimpleFluidFilter.java | 2 +- .../api/cover/filter/TagFluidFilter.java | 2 +- .../gtceu/api/cover/filter/TagItemFilter.java | 3 +- .../pipenet/physical/IPipeStructure.java | 2 +- .../pipenet/physical/block/PipeBlock.java | 20 +-- .../physical/tile/PipeBlockEntity.java | 6 +- .../physical/tile/PipeCoverHolder.java | 77 +++++++++- .../gregtechceu/gtceu/client/ClientProxy.java | 19 ++- .../renderer/BlockHighLightRenderer.java | 3 +- .../renderer/cover/FacadeCoverRenderer.java | 2 - .../renderer/pipe/AbstractPipeModel.java | 4 + .../renderer/pipe/ActivablePipeModel.java | 2 +- .../client/renderer/pipe/CableModel.java | 2 +- .../client/renderer/pipe/DuctPipeModel.java | 2 +- .../gtceu/client/renderer/pipe/PipeModel.java | 2 +- .../renderer/pipe/UnbakedPipeModel.java | 49 +++++++ .../pipe/cover/CoverRendererBuilder.java | 1 - .../pipe/cover/CoverRendererPackage.java | 6 +- .../common/cover/ComputerMonitorCover.java | 2 +- .../gtceu/common/cover/ConveyorCover.java | 3 +- .../gtceu/common/cover/FluidFilterCover.java | 4 +- .../common/cover/FluidRegulatorCover.java | 43 +++--- .../common/cover/InfiniteWaterCover.java | 6 +- .../gtceu/common/cover/ItemFilterCover.java | 2 +- .../gtceu/common/cover/PumpCover.java | 1 - .../gtceu/common/cover/RobotArmCover.java | 38 ++--- .../gtceu/common/cover/ShutterCover.java | 2 +- .../cover/detector/ActivityDetectorCover.java | 6 +- .../cover/detector/EnergyDetectorCover.java | 4 +- .../cover/detector/FluidDetectorCover.java | 4 +- .../cover/detector/ItemDetectorCover.java | 4 +- .../detector/MaintenanceDetectorCover.java | 1 + .../voiding/AdvancedFluidVoidingCover.java | 6 +- .../cover/voiding/FluidVoidingCover.java | 9 +- .../gtceu/common/data/GTBlocks.java | 20 +-- .../gtceu/common/data/GTCovers.java | 5 +- .../gtceu/common/data/GTItems.java | 18 ++- .../gtceu/common/data/GTModels.java | 133 ++++++++++++++++++ .../common/item/PortableScannerBehavior.java | 1 - .../common/machine/storage/DrumMachine.java | 5 +- .../pipelike/block/cable/CableStructure.java | 21 +-- .../pipelike/block/duct/DuctStructure.java | 3 - .../block/pipe/MaterialPipeStructure.java | 28 ++-- .../gregtechceu/gtceu/core/MixinHelpers.java | 8 -- .../gtceu/core/mixins/ModelManagerMixin.java | 1 + .../mixins/SpriteResourceLoaderMixin.java | 40 ------ .../gtceu/integration/jade/GTJadePlugin.java | 1 - .../provider/FluidPipeStorageProvider.java | 18 ++- .../gtceu/utils/ReflectionUtils.java | 18 +++ .../resources/META-INF/accesstransformer.cfg | 2 + .../gtceu/blockstates/pipe_activable.json | 7 + .../assets/gtceu/blockstates/pipe_cable.json | 7 + .../assets/gtceu/blockstates/pipe_duct.json | 7 + .../gtceu/blockstates/pipe_material.json | 7 + .../models/block/pipe/cable_insulation_0.json | 3 + .../models/block/pipe/cable_insulation_1.json | 3 + .../models/block/pipe/cable_insulation_2.json | 3 + .../models/block/pipe/cable_insulation_3.json | 3 + .../models/block/pipe/cable_insulation_4.json | 3 + .../gtceu/models/block/pipe/cable_wire.json | 3 + .../assets/gtceu/models/block/pipe/duct.json | 3 + .../assets/gtceu/models/block/pipe/laser.json | 3 + .../gtceu/models/block/pipe/optical.json | 3 + .../models/block/pipe/pipe_0_restrictive.json | 3 + .../models/block/pipe/pipe_0_standard.json | 3 + .../models/block/pipe/pipe_1_restrictive.json | 3 + .../models/block/pipe/pipe_1_standard.json | 3 + .../models/block/pipe/pipe_2_restrictive.json | 3 + .../models/block/pipe/pipe_2_standard.json | 3 + .../models/block/pipe/pipe_3_restrictive.json | 3 + .../models/block/pipe/pipe_3_standard.json | 3 + .../models/block/pipe/pipe_4_restrictive.json | 3 + .../models/block/pipe/pipe_4_standard.json | 3 + .../models/block/pipe/pipe_5_restrictive.json | 3 + .../models/block/pipe/pipe_5_standard.json | 3 + .../models/block/pipe/pipe_6_restrictive.json | 3 + .../models/block/pipe/pipe_6_standard.json | 3 + src/main/resources/gtceu.mixins.json | 1 - 84 files changed, 574 insertions(+), 210 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java create mode 100644 src/main/java/com/gregtechceu/gtceu/utils/ReflectionUtils.java create mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_activable.json create mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_cable.json create mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_duct.json create mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_material.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/duct.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/laser.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/optical.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json create mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json diff --git a/dependencies.gradle b/dependencies.gradle index 0904d237c7..e313b42122 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -3,7 +3,8 @@ dependencies { // Shadowed Dependencies // Packages that aren't mods, and thus need to be included in the release files. - shadow(implementation('org.jgrapht:jgrapht-core:1.5.2')) // JGraphT 1.4.0 + + shadow('org.jgrapht:jgrapht-core:1.5.2') // JGraphT 1.5.2 // LDLib modApi(forge.ldlib.forge) { transitive = false } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 8b6678ee2e..1fbef17270 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -3,6 +3,13 @@ tasks.register('slimJar', Jar) { from sourceSets.main.output } +shadowJar { + configurations = [project.configurations.shadow] + archiveClassifier = "dev-shadow" + minimize() + relocate("org.jgrapht", "${maven_group}.repack.org.jgrapht") +} + obfuscation { reobfuscate(tasks.named('slimJar'), sourceSets.main) { archiveClassifier = "slim" diff --git a/settings.gradle b/settings.gradle index 5d5dc8d938..9af6be1cb1 100644 --- a/settings.gradle +++ b/settings.gradle @@ -52,7 +52,7 @@ dependencyResolutionManagement { // Libs def quiltMappingsVersion = "5" // https://lambdaurora.dev/tools/import_quilt.html def parchmentVersion = "2023.09.03" // https://parchmentmc.org/docs/getting-started - def shadowVersion = "7.1.2" + def shadowVersion = "8.3.0" def spotlessVersion = "6.25.0" def modDevGradleVersion = "2.0.61-beta-pr-118-legacy" def vineFlowerVersion = "1.+" @@ -151,7 +151,7 @@ dependencyResolutionManagement { library("minecraft", "com.mojang", "minecraft").versionRef(minecraft) def shadow = version("shadow", shadowVersion) - plugin("shadow", "com.github.johnrengelman.shadow").versionRef(shadow) + plugin("shadow", "com.gradleup.shadow").versionRef(shadow) def spotless = version("spotless", spotlessVersion) plugin("spotless", "com.diffplug.spotless").versionRef(spotless) diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java index 976dd1378a..853d7bdf1c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/Filter.java @@ -8,7 +8,6 @@ import net.minecraft.util.StringRepresentable; import lombok.RequiredArgsConstructor; -import net.minecraft.world.item.ItemStack; import java.util.function.Consumer; import java.util.function.Function; diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java index c97702d42e..97f0870ebc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/FluidFilter.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.cover.filter; import com.gregtechceu.gtceu.common.cover.filter.MatchResult; + import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; @@ -90,8 +91,6 @@ public int getMaxTransferSize() { } @Override - public void setMaxTransferSize(int maxTransferSize) { - - } + public void setMaxTransferSize(int maxTransferSize) {} }; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java index 44f3788687..65a05fc148 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/ItemFilter.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.cover.filter; import com.gregtechceu.gtceu.common.cover.filter.MatchResult; + import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import net.minecraft.nbt.CompoundTag; @@ -93,8 +94,6 @@ public int getMaxTransferSize() { } @Override - public void setMaxTransferSize(int maxTransferSize) { - - } + public void setMaxTransferSize(int maxTransferSize) {} }; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java index 9d9ef037db..7710db024d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/SimpleFluidFilter.java @@ -3,8 +3,8 @@ import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.ScrollablePhantomFluidWidget; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; - import com.gregtechceu.gtceu.common.cover.filter.MatchResult; + import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.misc.FluidStorage; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java index 500599f3c9..675138ac72 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagFluidFilter.java @@ -5,7 +5,6 @@ import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -import lombok.Getter; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; @@ -13,6 +12,7 @@ import it.unimi.dsi.fastutil.objects.Object2BooleanMap; import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; +import lombok.Getter; import java.util.function.Consumer; diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java index c43ffa947d..3f84fa23d4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/filter/TagItemFilter.java @@ -3,8 +3,6 @@ import com.gregtechceu.gtceu.common.cover.filter.MatchResult; import com.gregtechceu.gtceu.utils.OreDictExprFilter; -import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -import lombok.Getter; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.item.Item; @@ -12,6 +10,7 @@ import it.unimi.dsi.fastutil.objects.Object2BooleanMap; import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; +import lombok.Getter; import java.util.function.Consumer; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java index fb94b5e6b9..a5ecbe3b96 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -6,6 +6,7 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; + import net.minecraft.core.Direction; import net.minecraft.util.StringRepresentable; import net.minecraft.world.phys.shapes.Shapes; @@ -27,7 +28,6 @@ public interface IPipeStructure extends StringRepresentable { AbstractPipeModel getModel(); - default ResourceTexture getPipeTexture(boolean isBlock) { return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 85dafaa202..e9a61d71d7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; -import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.block.MaterialBlock; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; @@ -49,6 +48,7 @@ import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; @@ -67,14 +67,16 @@ import java.lang.ref.WeakReference; import java.util.*; +import static com.gregtechceu.gtceu.api.block.BlockProperties.SERVER_TICK; + public abstract class PipeBlock extends Block implements EntityBlock { - public static final BooleanProperty NORTH = BooleanProperty.create("north"); - public static final BooleanProperty EAST = BooleanProperty.create("east"); - public static final BooleanProperty SOUTH = BooleanProperty.create("south"); - public static final BooleanProperty WEST = BooleanProperty.create("west"); - public static final BooleanProperty UP = BooleanProperty.create("up"); - public static final BooleanProperty DOWN = BooleanProperty.create("down"); + public static final BooleanProperty NORTH = BlockStateProperties.NORTH; + public static final BooleanProperty EAST = BlockStateProperties.EAST; + public static final BooleanProperty SOUTH = BlockStateProperties.SOUTH; + public static final BooleanProperty WEST = BlockStateProperties.WEST; + public static final BooleanProperty UP = BlockStateProperties.UP; + public static final BooleanProperty DOWN = BlockStateProperties.DOWN; public static final EnumMap FACINGS = buildFacings(); @@ -478,7 +480,7 @@ public GTToolType getToolClass() { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED); + builder.add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED, SERVER_TICK); } public static BlockState writeConnectionMask(@NotNull BlockState state, byte connectionMask) { @@ -504,7 +506,7 @@ public static byte readConnectionMask(@NotNull BlockState state) { @Override public BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType blockEntityType) { - if (!level.isClientSide && state.getValue(BlockProperties.SERVER_TICK)) { + if (!level.isClientSide && state.getValue(SERVER_TICK)) { return (pLevel, pPos, pState, pTile) -> { if (pTile instanceof PipeBlockEntity pipeNode) { pipeNode.serverTick(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 4dd6ce92bc..d10cb66416 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -20,7 +20,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; -import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.api.machine.TickableSubscription; @@ -33,7 +32,6 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; -import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; @@ -170,7 +168,9 @@ public void getDrops(@NotNull List drops, @NotNull BlockState state) @Override public void clearRemoved() { super.clearRemoved(); - scheduleRenderUpdate(); + if (getLevel() instanceof ServerLevel serverLevel) { + serverLevel.getServer().tell(new TickTask(0, this::scheduleRenderUpdate)); + } } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java index 2a13c9aa4f..20834548de 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeCoverHolder.java @@ -1,25 +1,31 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.api.machine.TickableSubscription; +import com.gregtechceu.gtceu.api.registry.GTRegistries; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.gui.editor.runtime.PersistedParser; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; import com.lowdragmc.lowdraglib.side.item.IItemTransfer; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; -import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; -import com.lowdragmc.lowdraglib.syncdata.annotation.RequireRerender; +import com.lowdragmc.lowdraglib.syncdata.annotation.*; import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; +import com.lowdragmc.lowdraglib.syncdata.managed.IRef; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; @@ -33,6 +39,7 @@ import org.jetbrains.annotations.Nullable; import java.util.EnumMap; +import java.util.HashMap; public class PipeCoverHolder implements ICoverable, IEnhancedManaged { @@ -41,9 +48,10 @@ public class PipeCoverHolder implements ICoverable, IEnhancedManaged { private final FieldManagedStorage syncStorage = new FieldManagedStorage(this); private final PipeBlockEntity holder; - @Persisted - @DescSynced @RequireRerender + @ReadOnlyManaged(onDirtyMethod = "onCoversDirty", + serializeMethod = "serializeCovers", + deserializeMethod = "deserializeCovers") private final EnumMap covers = new EnumMap<>(Direction.class); private final int[] sidedRedstoneInput = new int[6]; @@ -282,4 +290,63 @@ public ManagedFieldHolder getFieldHolder() { public void onChanged() { holder.onChanged(); } + + @SuppressWarnings("unused") + private boolean onCoversDirty(EnumMap covers) { + for (CoverBehavior coverBehavior : covers.values()) { + if (coverBehavior != null) { + for (IRef ref : coverBehavior.getSyncStorage().getNonLazyFields()) { + ref.update(); + } + if (coverBehavior.getSyncStorage().hasDirtySyncFields() || + coverBehavior.getSyncStorage().hasDirtyPersistedFields()) { + return true; + } + } + } + return false; + } + + @SuppressWarnings("unused") + private CompoundTag serializeCovers(EnumMap covers) { + CompoundTag tagCompound = new CompoundTag(); + ListTag coversList = new ListTag(); + for (var entry : covers.entrySet()) { + CoverBehavior cover = entry.getValue(); + if (cover != null) { + CompoundTag tag = new CompoundTag(); + ResourceLocation coverId = cover.coverDefinition.getId(); + tag.putString("id", coverId.toString()); + tag.putByte("side", (byte) entry.getKey().get3DDataValue()); + PersistedParser.serializeNBT(tag, cover.getClass(), cover); + coversList.add(tag); + } + } + tagCompound.put("Covers", coversList); + return tagCompound; + } + + @SuppressWarnings("unused") + private EnumMap deserializeCovers(CompoundTag tagCompound) { + EnumMap map = new EnumMap<>(Direction.class); + + ListTag coversList = tagCompound.getList("Covers", Tag.TAG_COMPOUND); + for (int index = 0; index < coversList.size(); index++) { + CompoundTag tag = coversList.getCompound(index); + if (tag.contains("id", Tag.TAG_STRING)) { + Direction coverSide = Direction.from3DDataValue(tag.getByte("Side")); + ResourceLocation coverLocation = new ResourceLocation(tag.getString("CoverId")); + CoverDefinition coverDefinition = GTRegistries.COVERS.get(coverLocation); + if (coverDefinition == null) { + GTCEu.LOGGER.warn("Unable to find CoverDefinition for ResourceLocation {} at position {}", + coverLocation, holder.getBlockPos()); + } else { + CoverBehavior cover = coverDefinition.createCoverBehavior(this, coverSide); + PersistedParser.deserializeNBT(tag, new HashMap<>(), cover.getClass(), cover); + map.put(coverSide, cover); + } + } + } + return map; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index 3d8763a93c..f1df83be2d 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -12,6 +12,8 @@ import com.gregtechceu.gtceu.client.renderer.entity.GTExplosiveRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.UnbakedPipeModel; import com.gregtechceu.gtceu.common.CommonProxy; import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTEntityTypes; @@ -94,8 +96,23 @@ public void onRegisterParticleProviders(RegisterParticleProvidersEvent event) { } @SubscribeEvent - public void registerModifiedModels(ModelEvent.ModifyBakingResult event) { + public void modifyModels(ModelEvent.ModifyBakingResult event) { ActivablePipeModel.registerModels(event.getModels()::put); CableModel.registerModels(event.getModels()::put); + PipeModel.registerModels(event.getModels()::put); + ActivablePipeModel.registerModels(event.getModels()::put); + } + + @SubscribeEvent + public void registerAdditionalModels(ModelEvent.RegisterAdditional event) { + ActivablePipeModel.registerModels((id, $) -> event.register(id)); + CableModel.registerModels((id, $) -> event.register(id)); + PipeModel.registerModels((id, $) -> event.register(id)); + ActivablePipeModel.registerModels((id, $) -> event.register(id)); + } + + @SubscribeEvent + public void modelRegistry(final ModelEvent.RegisterGeometryLoaders e) { + e.register("pipe", UnbakedPipeModel.Loader.INSTANCE); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java index 21a133bf26..8e9b8fb5ef 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java @@ -143,7 +143,8 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, } // draw pipe connection grid highlight - var pipeStructure = held.getItem() instanceof PipeBlockItem pipeBlockItem ? pipeBlockItem.getBlock().getStructure() : + var pipeStructure = held.getItem() instanceof PipeBlockItem pipeBlockItem ? + pipeBlockItem.getBlock().getStructure() : null; if (pipeStructure != null && blockEntity instanceof PipeBlockEntity pipeBlockEntity && pipeBlockEntity.getStructure() == pipeStructure) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java index 26a2b0ccab..547f9f4785 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java @@ -27,7 +27,6 @@ import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; @@ -39,7 +38,6 @@ import org.joml.AxisAngle4d; import org.joml.Quaternionf; -import java.util.ArrayList; import java.util.LinkedList; import java.util.List; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index d9ab3b1866..5d202e5982 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -41,10 +41,13 @@ import java.util.Collections; import java.util.List; +import java.util.Map; @OnlyIn(Dist.CLIENT) public abstract class AbstractPipeModel implements BakedModel { + public static final Map> MODELS = new Object2ObjectOpenHashMap<>(); + public static ModelProperty THICKNESS_PROPERTY = new ModelProperty<>(); public static ModelProperty FRAME_MATERIAL_PROPERTY = new ModelProperty<>(); @@ -64,6 +67,7 @@ public abstract class AbstractPipeModel implements BakedMode public AbstractPipeModel(ModelResourceLocation loc) { this.loc = loc; + MODELS.put(loc, this); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java index 448b3370b0..e6304ad4a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -39,7 +39,7 @@ @OnlyIn(Dist.CLIENT) public class ActivablePipeModel extends AbstractPipeModel { - private static final ResourceLocation loc = GTCEu.id("block/pipe_activable"); + private static final ResourceLocation loc = GTCEu.id("pipe_activable"); public static final ModelProperty ACTIVE_PROPERTY = new ModelProperty<>(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java index 8df9399386..bd37c41782 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java @@ -38,7 +38,7 @@ public class CableModel extends AbstractPipeModel { public static final int DEFAULT_INSULATION_COLOR = 0xFF404040; - private static final ResourceLocation loc = GTCEu.id("block/cable"); + private static final ResourceLocation loc = GTCEu.id("pipe_cable"); public static final CableModel INSTANCE = new CableModel("wire"); public static final CableModel[] INSULATED_INSTANCES = new CableModel[5]; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java index 68e4704f92..0db0bffbb1 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java @@ -23,7 +23,7 @@ public class DuctPipeModel extends AbstractPipeModel { - private static final ResourceLocation loc = GTCEu.id("block/duct_pipe"); + private static final ResourceLocation loc = GTCEu.id("pipe_duct"); public static final DuctPipeModel INSTANCE = new DuctPipeModel(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java index c9436fe759..233ee2cbae 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -37,7 +37,7 @@ @OnlyIn(Dist.CLIENT) public class PipeModel extends AbstractPipeModel { - private static final ResourceLocation loc = GTCEu.id("block/pipe_material"); + private static final ResourceLocation loc = GTCEu.id("pipe_material"); public static final PipeModel[] INSTANCES = new PipeModel[7]; public static final PipeModel[] RESTRICTIVE_INSTANCES = new PipeModel[INSTANCES.length]; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java new file mode 100644 index 0000000000..0a1bd1e8eb --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java @@ -0,0 +1,49 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.*; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.GsonHelper; +import net.minecraftforge.client.model.geometry.IGeometryBakingContext; +import net.minecraftforge.client.model.geometry.IGeometryLoader; +import net.minecraftforge.client.model.geometry.IUnbakedGeometry; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import lombok.RequiredArgsConstructor; + +import java.util.function.Function; + +@RequiredArgsConstructor +public class UnbakedPipeModel implements IUnbakedGeometry { + + private final AbstractPipeModel model; + + @Override + public BakedModel bake(IGeometryBakingContext iGeometryBakingContext, ModelBaker baker, + Function function, ModelState arg2, ItemOverrides arg3, + ResourceLocation arg4) { + return model; + } + + public static final class Loader implements IGeometryLoader { + + public static final UnbakedPipeModel.Loader INSTANCE = new UnbakedPipeModel.Loader(); + + private Loader() {} + + @Override + public UnbakedPipeModel read(JsonObject jsonObject, + JsonDeserializationContext deserializationContext) throws JsonParseException { + if (!jsonObject.has("model_id")) + throw new JsonParseException("An UnbakedPipeModel must have an \"model_id\" member."); + + String[] id = GsonHelper.getAsString(jsonObject, "model_id").split("#"); + ResourceLocation modelId = new ModelResourceLocation(new ResourceLocation(id[0]), + id.length > 1 ? id[1] : ""); + return new UnbakedPipeModel(AbstractPipeModel.MODELS.get(modelId)); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java index c38c358727..cce7a599e3 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java @@ -20,7 +20,6 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java index 9d2c677cd9..33ef71ded2 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererPackage.java @@ -38,13 +38,15 @@ public void addRenderer(CoverRenderer renderer, @NotNull Direction facing) { plates.remove(facing); } - public void addQuads(List quads, RandomSource rand, ModelData modelData, ColorData data, RenderType renderType) { + public void addQuads(List quads, RandomSource rand, ModelData modelData, ColorData data, + RenderType renderType) { for (var renderer : renderers.entrySet()) { EnumSet plates = EnumSet.copyOf(this.plates); // force front and back plates to render plates.add(renderer.getKey()); plates.add(renderer.getKey().getOpposite()); - renderer.getValue().addQuads(quads, renderer.getKey(), rand, plates, renderBackside, modelData, data, renderType); + renderer.getValue().addQuads(quads, renderer.getKey(), rand, plates, renderBackside, modelData, data, + renderType); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java index bc88859865..35cf674a87 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ComputerMonitorCover.java @@ -3,8 +3,8 @@ import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; - import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; + import net.minecraft.core.Direction; public class ComputerMonitorCover extends CoverBehavior { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java index 00316b3d8b..29888b97af 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ConveyorCover.java @@ -285,7 +285,8 @@ protected int performTransfer(@NotNull IItemTransfer sourceHandler, @NotNull IIt @NotNull IntUnaryOperator maxTransfer, @Nullable BiConsumer transferReport) { ItemFilter filter = filterHandler.getFilter(); - byFilterSlot = byFilterSlot && getFilterHandler().isFilterPresent(); // can't be by filter slot if there is no filter + byFilterSlot = byFilterSlot && getFilterHandler().isFilterPresent(); // can't be by filter slot if there is no + // filter Int2IntArrayMap extractableByFilterSlot = new Int2IntArrayMap(); Int2ObjectArrayMap> filterSlotToMergability = new Int2ObjectArrayMap<>(); for (int i = 0; i < sourceHandler.getSlots(); i++) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java index fcd9be0ddf..e4074bb9b8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidFilterCover.java @@ -6,17 +6,17 @@ import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.IUICover; import com.gregtechceu.gtceu.api.cover.filter.FluidFilter; - import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; + import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; -import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.ForgeCapabilities; + import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java index c23d58953e..353531c6a3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java @@ -14,11 +14,11 @@ import com.gregtechceu.gtceu.api.gui.widget.NumberInputWidget; import com.gregtechceu.gtceu.common.cover.data.BucketMode; import com.gregtechceu.gtceu.common.cover.data.TransferMode; - import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidEQTraverseData; import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidRRTraverseData; import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidTraverseData; import com.gregtechceu.gtceu.common.pipelike.net.fluid.IFluidTransferController; + import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; @@ -27,18 +27,19 @@ import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; - -import lombok.Getter; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.fluids.capability.IFluidHandler; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import lombok.Getter; import org.jetbrains.annotations.NotNull; -import javax.annotation.ParametersAreNonnullByDefault; import java.util.function.IntToLongFunction; +import javax.annotation.ParametersAreNonnullByDefault; + @ParametersAreNonnullByDefault public class FluidRegulatorCover extends PumpCover { @@ -136,7 +137,7 @@ protected void performTransferOnUpdate(@NotNull IFluidTransfer sourceHandler, @N @Override protected long simpleInsert(@NotNull IFluidTransfer destHandler, FluidTestObject testObject, long count, - boolean simulate) { + boolean simulate) { if (transferMode == TransferMode.KEEP_EXACT) { assert getFilterHandler().isFilterPresent(); int kept = getFilterHandler().getFilter().getTransferLimit(testObject.recombine()); @@ -192,8 +193,9 @@ private long getCurrentBucketModeTransferSize() { } private void setCurrentBucketModeTransferSize(long transferSize) { - this.getFilterHandler().getFilter().setMaxTransferSize((int) Math.min(Math.max(transferSize * this.bucketMode.multiplier, 0), - MAX_STACK_SIZE)); + this.getFilterHandler().getFilter() + .setMaxTransferSize((int) Math.min(Math.max(transferSize * this.bucketMode.multiplier, 0), + MAX_STACK_SIZE)); } private void configureTransferSizeInput() { @@ -242,7 +244,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl IFluidHandler containerCap = capability.getValue() .getCapability(ForgeCapabilities.FLUID_HANDLER, - capability.getKey().getOpposite()).resolve().orElse(null); + capability.getKey().getOpposite()) + .resolve().orElse(null); if (containerCap != null) { IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); long contained = computeContained(container, getTestObject()); @@ -251,8 +254,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl if (contained >= kept) continue; availableFlow -= IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(kept - contained, availableFlow), container, - getSimulatorKey() == null); + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() == null); } } return flowReachingDestination - availableFlow; @@ -278,7 +281,8 @@ protected void compute(@NotNull WorldPipeNetNode destination) { IFluidHandler containerCap = capability.getValue() .getCapability(ForgeCapabilities.FLUID_HANDLER, - capability.getKey().getOpposite()).resolve().orElse(null); + capability.getKey().getOpposite()) + .resolve().orElse(null); if (containerCap != null) { IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); long contained = computeContained(container, getTestObject()); @@ -290,8 +294,8 @@ protected void compute(@NotNull WorldPipeNetNode destination) { maxMinFlow = Math.min(maxMinFlow, IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - kept - contained, - container, false)); + kept - contained, + container, false)); } } } @@ -306,7 +310,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl IFluidHandler containerCap = capability.getValue() .getCapability(ForgeCapabilities.FLUID_HANDLER, - capability.getKey().getOpposite()).resolve().orElse(null); + capability.getKey().getOpposite()) + .resolve().orElse(null); if (containerCap != null) { IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); long contained = computeContained(container, getTestObject()); @@ -315,8 +320,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl if (contained >= kept) continue; availableFlow -= IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(kept - contained, availableFlow), container, - getSimulatorKey() == null); + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() == null); } } return flowReachingDestination - availableFlow; @@ -347,8 +352,8 @@ public long finalizeAtDestination(@NotNull SimpleTileRoundRobinData= kept) continue; availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(kept - contained, availableFlow), container, - getSimulatorKey() != null); + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() != null); } } return flowReachingDestination - availableFlow; @@ -341,7 +344,8 @@ protected void compute(@NotNull WorldPipeNetNode destination) { IItemHandler containerCap = capability.getValue() .getCapability(ForgeCapabilities.ITEM_HANDLER, - capability.getKey().getOpposite()).resolve().orElse(null); + capability.getKey().getOpposite()) + .resolve().orElse(null); if (containerCap != null) { IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); int contained = computeContained(container, getTestObject()); @@ -354,7 +358,7 @@ protected void compute(@NotNull WorldPipeNetNode destination) { maxMinFlow = Math.min(maxMinFlow, test - IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), test, - container, true)); + container, true)); } } } @@ -369,7 +373,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl IItemHandler containerCap = capability.getValue() .getCapability(ForgeCapabilities.ITEM_HANDLER, - capability.getKey().getOpposite()).resolve().orElse(null); + capability.getKey().getOpposite()) + .resolve().orElse(null); if (containerCap != null) { IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); int contained = computeContained(container, getTestObject()); @@ -378,8 +383,8 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl if (contained >= kept) continue; availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(kept - contained, availableFlow), container, - getSimulatorKey() != null); + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() != null); } } return flowReachingDestination - availableFlow; @@ -412,11 +417,10 @@ public long finalizeAtDestination(@NotNull SimpleTileRoundRobinData= kept) return 0; availableFlow = IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(pointerFacing)).insertToHandler(getTestObject(), - (int) Math.min(kept - contained, availableFlow), container, - getSimulatorKey() != null); + (int) Math.min(kept - contained, availableFlow), container, + getSimulatorKey() != null); } return flowReachingDestination - availableFlow; } } } - diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java index 612f95399e..269b034fa0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java @@ -5,9 +5,9 @@ import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.cover.CoverDefinition; - import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; + import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java index 544a5b060a..9561bbce93 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ActivityDetectorCover.java @@ -5,11 +5,12 @@ import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.cover.CoverDefinition; - import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; + import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; @@ -24,7 +25,8 @@ public ActivityDetectorCover(CoverDefinition definition, ICoverable coverHolder, @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_activity_detector"), GTCEu.id("block/cover/overlay_activity_detector_emissive")).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_activity_detector"), + GTCEu.id("block/cover/overlay_activity_detector_emissive")).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java index 6190badd92..60cc061f3f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java @@ -8,7 +8,6 @@ import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; -import com.gregtechceu.gtceu.common.machine.multiblock.electric.PowerSubstationMachine; import com.gregtechceu.gtceu.utils.RedstoneUtil; import net.minecraft.core.Direction; @@ -24,7 +23,8 @@ public EnergyDetectorCover(CoverDefinition definition, ICoverable coverHolder, D @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_energy_detector"), GTCEu.id("block/cover/overlay_energy_detector_emissive")).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_energy_detector"), + GTCEu.id("block/cover/overlay_energy_detector_emissive")).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java index 39efc89ccb..2dea6a67f3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java @@ -13,6 +13,7 @@ import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.ForgeCapabilities; + import org.jetbrains.annotations.NotNull; public class FluidDetectorCover extends DetectorCover { @@ -23,7 +24,8 @@ public FluidDetectorCover(CoverDefinition definition, ICoverable coverHolder, Di @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_detector"), GTCEu.id("block/cover/overlay_fluid_detector_emissive")).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_detector"), + GTCEu.id("block/cover/overlay_fluid_detector_emissive")).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java index 82caf90293..4b2ee48909 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java @@ -12,6 +12,7 @@ import net.minecraft.core.Direction; import net.minecraftforge.common.capabilities.ForgeCapabilities; + import org.jetbrains.annotations.NotNull; public class ItemDetectorCover extends DetectorCover { @@ -27,7 +28,8 @@ public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_detector"), GTCEu.id("block/cover/overlay_item_detector_emissive")).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_detector"), + GTCEu.id("block/cover/overlay_item_detector_emissive")).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java index fd0e3de1cf..2149a5391a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/MaintenanceDetectorCover.java @@ -11,6 +11,7 @@ import com.gregtechceu.gtceu.config.ConfigHolder; import net.minecraft.core.Direction; + import org.jetbrains.annotations.NotNull; public class MaintenanceDetectorCover extends DetectorCover { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java index 8ee087b313..41bdade2f1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedFluidVoidingCover.java @@ -12,8 +12,8 @@ import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.BucketMode; import com.gregtechceu.gtceu.common.cover.data.VoidingMode; - import com.gregtechceu.gtceu.utils.GTTransferUtils; + import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; @@ -24,10 +24,10 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.Direction; - -import lombok.Getter; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.fluids.capability.IFluidHandler; + +import lombok.Getter; import org.jetbrains.annotations.NotNull; import java.util.function.Predicate; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java index 3cd546f680..c5e6b59c89 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/FluidVoidingCover.java @@ -8,8 +8,8 @@ import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.PumpCover; - import com.gregtechceu.gtceu.utils.GTTransferUtils; + import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; @@ -22,13 +22,11 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.Direction; - -import lombok.Getter; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.fluids.capability.IFluidHandler; -import org.jetbrains.annotations.NotNull; -import java.util.Map; +import lombok.Getter; +import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; @@ -60,7 +58,6 @@ protected boolean isSubscriptionActive() { // *********** COVER LOGIC ***********// ////////////////////////////////////////////// - @Override public void update() { if (isWorkingEnabled && coverHolder.getOffsetTimer() % 20 == 0) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index efd95a8ab7..bb35c72516 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -321,13 +321,13 @@ private static boolean allowCableBlock(Material material, CableStructure insulat return false; } - private static void registerCableBlock(Material material, CableStructure insulation, GTRegistrate registrate) { + private static void registerCableBlock(Material material, CableStructure structure, GTRegistrate registrate) { var entry = registrate - .block("%s_%s".formatted(material.getName(), insulation.name()), - p -> new com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock(p, insulation, material)) + .block("%s_%s".formatted(material.getName(), structure.name()), + p -> new com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock(p, structure, material)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> p.dynamicShape().noOcclusion().noLootTable().forceSolidOn()) - .transform(unificationBlock(insulation.prefix(), material)) + .transform(unificationBlock(structure.prefix(), material)) .blockstate(NonNullBiConsumer.noop()) .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) @@ -338,7 +338,7 @@ private static void registerCableBlock(Material material, CableStructure insulat .onRegister(compassNodeExist(GTCompassSections.MATERIALS, "wire_and_cable")) .build() .register(); - CABLE_BLOCKS_BUILDER.put(insulation.prefix(), material, entry); + CABLE_BLOCKS_BUILDER.put(structure.prefix(), material, entry); } // Fluid Pipe Blocks @@ -362,11 +362,11 @@ private static boolean allowMaterialPipeBlock(Material material, MaterialPipeStr return material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && !fluidPipeType.prefix().isIgnored(material); } - private static void registerMaterialPipeBlock(Material material, MaterialPipeStructure fluidPipeType, + private static void registerMaterialPipeBlock(Material material, MaterialPipeStructure pipeType, GTRegistrate registrate) { var entry = registrate - .block("%s_%s_pipe".formatted(material.getName(), fluidPipeType.name()), - p -> new MaterialPipeBlock(p, fluidPipeType, material)) + .block("%s_%s_pipe".formatted(pipeType.name(), material.getName()), + p -> new MaterialPipeBlock(p, pipeType, material)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> { if (doMetalPipe(material)) { @@ -374,7 +374,7 @@ private static void registerMaterialPipeBlock(Material material, MaterialPipeStr } return p.dynamicShape().noOcclusion().noLootTable().forceSolidOn(); }) - .transform(unificationBlock(fluidPipeType.prefix(), material)) + .transform(unificationBlock(pipeType.prefix(), material)) .blockstate(NonNullBiConsumer.noop()) .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) @@ -383,7 +383,7 @@ private static void registerMaterialPipeBlock(Material material, MaterialPipeStr .model(NonNullBiConsumer.noop()) .build() .register(); - MATERIAL_PIPE_BLOCKS_BUILDER.put(fluidPipeType.prefix(), material, entry); + MATERIAL_PIPE_BLOCKS_BUILDER.put(pipeType.prefix(), material, entry); } // Optical Pipe Blocks diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java index 2927cea7eb..fa2bbd92a5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java @@ -141,8 +141,9 @@ public static CoverDefinition register(String id, CoverDefinition.CoverBehaviour public static CoverDefinition register(String id, CoverDefinition.CoverBehaviourProvider behaviorCreator, ICoverRenderer coverRenderer) { var definition = new CoverDefinition(GTCEu.id(id), behaviorCreator, - (quads, side, rand, renderPlate, renderBackside, modelData, colorData, renderType) -> coverRenderer.renderCover(quads, side, - rand, null, null, null, null, null)); + (quads, side, rand, renderPlate, renderBackside, modelData, colorData, renderType) -> coverRenderer + .renderCover(quads, side, + rand, null, null, null, null, null)); GTRegistries.COVERS.register(GTCEu.id(id), definition); return definition; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java index c235e415b0..3c6799326f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java @@ -547,7 +547,9 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 8, - GTMaterials.Steel.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, + GTMaterials.Steel.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), + true, false, false, false, true), new ItemFluidContainer())) .onRegister(materialInfo(new ItemMaterialInfo(new MaterialStack(GTMaterials.Steel, GTValues.M * 4)))) @@ -560,7 +562,9 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 32, - GTMaterials.Aluminium.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, + GTMaterials.Aluminium.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), + true, false, false, false, true), new ItemFluidContainer())) .onRegister(materialInfo(new ItemMaterialInfo(new MaterialStack(GTMaterials.Aluminium, GTValues.M * 4)))) @@ -573,7 +577,8 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 64, - GTMaterials.StainlessSteel.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), + GTMaterials.StainlessSteel.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, false, false, true), new ItemFluidContainer())) .onRegister( @@ -587,7 +592,9 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 128, - GTMaterials.Titanium.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, + GTMaterials.Titanium.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), + true, false, false, false, true), new ItemFluidContainer())) .onRegister(materialInfo(new ItemMaterialInfo(new MaterialStack(GTMaterials.Titanium, GTValues.M * 6)))) @@ -601,7 +608,8 @@ public Component getItemName(ItemStack stack) { .onRegister(compassNodeExist(GTCompassSections.ITEMS, "empty_cell")) .onRegister(attach(cellName(), ThermalFluidStats.create((int) FluidHelper.getBucket() * 512, - GTMaterials.TungstenSteel.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), + GTMaterials.TungstenSteel.getProperty(PropertyKey.PIPENET_PROPERTIES) + .getProperty(MaterialFluidProperties.KEY).getMaxFluidTemperature(), true, false, false, false, true), new ItemFluidContainer())) .onRegister( diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java index 49cd489948..21bf6a026f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java @@ -2,15 +2,31 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTCEuAPI; +import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.block.ActiveBlock; import com.gregtechceu.gtceu.api.block.ICoilType; import com.gregtechceu.gtceu.api.block.IFilterType; import com.gregtechceu.gtceu.api.block.IFusionCasingType; import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconSet; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PipeNetProperties; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.fluids.GTFluid; import com.gregtechceu.gtceu.api.fluids.store.FluidStorage; import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.common.block.LampBlock; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; +import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctPipeBlock; +import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctStructure; +import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserPipeBlock; +import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserStructure; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalPipeBlock; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; import com.gregtechceu.gtceu.api.machine.multiblock.IBatteryData; import com.gregtechceu.gtceu.common.block.*; import com.gregtechceu.gtceu.core.MixinHelpers; @@ -18,6 +34,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.data.models.blockstates.*; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.GsonHelper; import net.minecraft.world.item.BlockItem; @@ -359,4 +376,120 @@ public static void registerMaterialFluidModels() { } } } + + public static void registerPipeModels() { + for (var material : GTCEuAPI.materialManager.getRegisteredMaterials()) { + PipeNetProperties properties = material.getProperty(PropertyKey.PIPENET_PROPERTIES); + if (properties == null) continue; + if (properties.hasProperty(MaterialEnergyProperties.KEY)) { + for (var structure : PipeStructureRegistry.getStructures(CableStructure.class)) { + if (!GTBlocks.CABLE_BLOCKS.contains(structure.prefix(), material)) { + continue; + } + + JsonObject json = new JsonObject(); + json.addProperty("loader", "gtceu:pipe"); + String modelId = structure.getModel().getLoc().toString(); + json.addProperty("model_id", modelId); + + CableBlock block = GTBlocks.CABLE_BLOCKS.get(structure.prefix(), material).get(); + ResourceLocation blockId = GTBlocks.CABLE_BLOCKS.get(structure.prefix(), material).getId(); + ResourceLocation blockModelId = blockId.withPrefix("block/"); + GTDynamicResourcePack.addBlockModel(blockModelId, json); + GTDynamicResourcePack.addItemModel(blockId, json); + + createPipeBlockState(blockId, blockModelId, block); + } + } + for (var structure : PipeStructureRegistry.getStructures(MaterialPipeStructure.class)) { + if (!GTBlocks.MATERIAL_PIPE_BLOCKS.contains(structure.prefix(), material)) { + continue; + } + + JsonObject json = new JsonObject(); + json.addProperty("loader", "gtceu:pipe"); + String modelId = structure.getModel().getLoc().toString(); + json.addProperty("model_id", modelId); + + MaterialPipeBlock block = GTBlocks.MATERIAL_PIPE_BLOCKS.get(structure.prefix(), material).get(); + ResourceLocation blockId = GTBlocks.MATERIAL_PIPE_BLOCKS.get(structure.prefix(), material).getId(); + ResourceLocation blockModelId = blockId.withPrefix("block/"); + GTDynamicResourcePack.addBlockModel(blockModelId, json); + GTDynamicResourcePack.addItemModel(blockId, json); + + createPipeBlockState(blockId, blockModelId, block); + } + } + for (var structure : PipeStructureRegistry.getStructures(DuctStructure.class)) { + JsonObject json = new JsonObject(); + json.addProperty("loader", "gtceu:pipe"); + String modelId = structure.getModel().getLoc().toString(); + json.addProperty("model_id", modelId); + + DuctPipeBlock block = GTBlocks.DUCT_PIPE_BLOCKS.get(structure).get(); + ResourceLocation blockId = GTBlocks.DUCT_PIPE_BLOCKS.get(structure).getId(); + ResourceLocation blockModelId = blockId.withPrefix("block/"); + GTDynamicResourcePack.addBlockModel(blockModelId, json); + GTDynamicResourcePack.addItemModel(blockId, json); + + createPipeBlockState(blockId, blockModelId, block); + } + { + JsonObject json = new JsonObject(); + json.addProperty("loader", "gtceu:pipe"); + String modelId = LaserStructure.NORMAL.getModel().getLoc().toString(); + json.addProperty("model_id", modelId); + + LaserPipeBlock block = GTBlocks.LASER_PIPE.get(); + ResourceLocation blockId = GTBlocks.LASER_PIPE.getId(); + ResourceLocation blockModelId = blockId.withPrefix("block/"); + GTDynamicResourcePack.addBlockModel(blockModelId, json); + GTDynamicResourcePack.addItemModel(blockId, json); + + createPipeBlockState(blockId, blockModelId, block); + } + { + JsonObject json = new JsonObject(); + json.addProperty("loader", "gtceu:pipe"); + String modelId = OpticalStructure.INSTANCE.getModel().getLoc().toString(); + json.addProperty("model_id", modelId); + + OpticalPipeBlock block = GTBlocks.OPTICAL_PIPE.get(); + ResourceLocation blockId = GTBlocks.OPTICAL_PIPE.getId(); + ResourceLocation blockModelId = blockId.withPrefix("block/"); + GTDynamicResourcePack.addBlockModel(blockModelId, json); + GTDynamicResourcePack.addItemModel(blockId, json); + + createPipeBlockState(blockId, blockModelId, block); + } + } + + private static void createPipeBlockState(ResourceLocation blockId, ResourceLocation blockModelId, Block block) { + Variant variant = Variant.variant().with(VariantProperties.MODEL, blockModelId); + GTDynamicResourcePack.addBlockState(blockId, MultiVariantGenerator.multiVariant(block) + .with(PropertyDispatch.property(PipeBlock.NORTH) + .select(true, variant) + .select(false, variant)) + .with(PropertyDispatch.property(PipeBlock.SOUTH) + .select(true, variant) + .select(false, variant)) + .with(PropertyDispatch.property(PipeBlock.WEST) + .select(true, variant) + .select(false, variant)) + .with(PropertyDispatch.property(PipeBlock.EAST) + .select(true, variant) + .select(false, variant)) + .with(PropertyDispatch.property(PipeBlock.UP) + .select(true, variant) + .select(false, variant)) + .with(PropertyDispatch.property(PipeBlock.DOWN) + .select(true, variant) + .select(false, variant)) + .with(PropertyDispatch.property(PipeBlock.FRAMED) + .select(true, variant) + .select(false, variant)) + .with(PropertyDispatch.property(BlockProperties.SERVER_TICK) + .select(true, variant) + .select(false, variant))); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index 2e594076f5..b43600aa2d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -25,7 +25,6 @@ import com.gregtechceu.gtceu.utils.FormattingUtil; import com.gregtechceu.gtceu.utils.GTUtil; -import com.simibubi.create.content.fluids.pipes.FluidPipeBlockEntity; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java index 84bbd4050b..7cf5376962 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/DrumMachine.java @@ -12,8 +12,8 @@ import com.gregtechceu.gtceu.api.machine.feature.IDropSaveMachine; import com.gregtechceu.gtceu.api.machine.feature.IInteractedMachine; import com.gregtechceu.gtceu.api.machine.trait.NotifiableFluidTank; - import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialFluidProperties; + import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.side.fluid.FluidActionResult; import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; @@ -96,7 +96,8 @@ public ManagedFieldHolder getFieldHolder() { protected NotifiableFluidTank createCacheFluidHandler(Object... args) { return new NotifiableFluidTank(this, 1, maxStoredFluids, IO.BOTH) - .setFilter(material.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY)); + .setFilter( + material.getProperty(PropertyKey.PIPENET_PROPERTIES).getProperty(MaterialFluidProperties.KEY)); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index 5b1987ae6b..93d544141f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -9,6 +9,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -21,26 +22,26 @@ public record CableStructure(String name, int material, int costFactor, TagPrefi public static final int INSULATION_BURN_TEMP = 1000; - public static final CableStructure WIRE_SINGLE = new CableStructure("wire_single", 1, 2, TagPrefix.wireGtSingle, + public static final CableStructure WIRE_SINGLE = new CableStructure("single_wire", 1, 2, TagPrefix.wireGtSingle, null, null, 0.125f, CableModel.INSTANCE); - public static final CableStructure WIRE_DOUBLE = new CableStructure("wire_double", 2, 2, TagPrefix.wireGtDouble, + public static final CableStructure WIRE_DOUBLE = new CableStructure("double_wire", 2, 2, TagPrefix.wireGtDouble, null, null, 0.25f, CableModel.INSTANCE); - public static final CableStructure WIRE_QUADRUPLE = new CableStructure("wire_quadruple", 4, 3, + public static final CableStructure WIRE_QUADRUPLE = new CableStructure("quadruple_wire", 4, 3, TagPrefix.wireGtQuadruple, null, null, 0.375f, CableModel.INSTANCE); - public static final CableStructure WIRE_OCTAL = new CableStructure("wire_octal", 8, 3, TagPrefix.wireGtOctal, null, + public static final CableStructure WIRE_OCTAL = new CableStructure("octal_wire", 8, 3, TagPrefix.wireGtOctal, null, null, 0.5f, CableModel.INSTANCE); - public static final CableStructure WIRE_HEX = new CableStructure("wire_hex", 16, 3, TagPrefix.wireGtHex, null, null, + public static final CableStructure WIRE_HEX = new CableStructure("hex_wire", 16, 3, TagPrefix.wireGtHex, null, null, 0.75f, CableModel.INSTANCE); - public static final CableStructure CABLE_SINGLE = new CableStructure("cable_single", 1, 1, TagPrefix.cableGtSingle, + public static final CableStructure CABLE_SINGLE = new CableStructure("single_cable", 1, 1, TagPrefix.cableGtSingle, WIRE_SINGLE, INSULATION_BURN_TEMP, 0.25f, CableModel.INSULATED_INSTANCES[0]); - public static final CableStructure CABLE_DOUBLE = new CableStructure("cable_double", 2, 1, TagPrefix.cableGtDouble, + public static final CableStructure CABLE_DOUBLE = new CableStructure("double_cable", 2, 1, TagPrefix.cableGtDouble, WIRE_DOUBLE, INSULATION_BURN_TEMP, 0.375f, CableModel.INSULATED_INSTANCES[1]); - public static final CableStructure CABLE_QUADRUPLE = new CableStructure("cable_quadruple", 4, 1, + public static final CableStructure CABLE_QUADRUPLE = new CableStructure("quadruple_cable", 4, 1, TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, CableModel.INSULATED_INSTANCES[2]); - public static final CableStructure CABLE_OCTAL = new CableStructure("cable_octal", 8, 1, TagPrefix.cableGtOctal, + public static final CableStructure CABLE_OCTAL = new CableStructure("octal_cable", 8, 1, TagPrefix.cableGtOctal, WIRE_OCTAL, INSULATION_BURN_TEMP, 0.75f, CableModel.INSULATED_INSTANCES[3]); - public static final CableStructure CABLE_HEX = new CableStructure("cable_hex", 16, 1, TagPrefix.cableGtHex, + public static final CableStructure CABLE_HEX = new CableStructure("hex_cable", 16, 1, TagPrefix.cableGtHex, WIRE_HEX, INSULATION_BURN_TEMP, 1f, CableModel.INSULATED_INSTANCES[4]); public CableStructure(String name, int material, int costFactor, TagPrefix prefix, diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java index 242154c7c2..35064c06d5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -4,9 +4,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.DuctPipeModel; -import com.gregtechceu.gtceu.utils.GTUtil; - -import net.minecraft.core.Direction; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java index 406fd83d9f..2d81c55601 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -15,50 +15,50 @@ public record MaterialPipeStructure(String name, int material, int channelCount, float renderThickness, PipeModel model) implements IPipeMaterialStructure, IPipeChanneledStructure { - public static final MaterialPipeStructure TINY = new MaterialPipeStructure("pipe_tiny", 1, 1, false, + public static final MaterialPipeStructure TINY = new MaterialPipeStructure("tiny", 1, 1, false, TagPrefix.pipeTiny, 0.25f, PipeModel.INSTANCES[0]); - public static final MaterialPipeStructure SMALL = new MaterialPipeStructure("pipe_small", 2, 1, false, + public static final MaterialPipeStructure SMALL = new MaterialPipeStructure("small", 2, 1, false, TagPrefix.pipeSmall, 0.375f, PipeModel.INSTANCES[1]); - public static final MaterialPipeStructure NORMAL = new MaterialPipeStructure("pipe_normal", 6, 1, false, + public static final MaterialPipeStructure NORMAL = new MaterialPipeStructure("normal", 6, 1, false, TagPrefix.pipeNormal, 0.5f, PipeModel.INSTANCES[2]); - public static final MaterialPipeStructure LARGE = new MaterialPipeStructure("pipe_large", 12, 1, false, + public static final MaterialPipeStructure LARGE = new MaterialPipeStructure("large", 12, 1, false, TagPrefix.pipeLarge, 0.75f, PipeModel.INSTANCES[3]); - public static final MaterialPipeStructure HUGE = new MaterialPipeStructure("pipe_huge", 24, 1, false, + public static final MaterialPipeStructure HUGE = new MaterialPipeStructure("huge", 24, 1, false, TagPrefix.pipeHuge, 0.875f, PipeModel.INSTANCES[4]); - public static final MaterialPipeStructure QUADRUPLE = new MaterialPipeStructure("pipe_quadruple", 8, 4, false, + public static final MaterialPipeStructure QUADRUPLE = new MaterialPipeStructure("quadruple", 8, 4, false, TagPrefix.pipeQuadruple, 0.95f, PipeModel.INSTANCES[5]); - public static final MaterialPipeStructure NONUPLE = new MaterialPipeStructure("pipe_nonuple", 18, 9, false, + public static final MaterialPipeStructure NONUPLE = new MaterialPipeStructure("nonuple", 18, 9, false, TagPrefix.pipeNonuple, 0.95f, PipeModel.INSTANCES[6]); - public static final MaterialPipeStructure TINY_RESTRICTIVE = new MaterialPipeStructure("pipe_tiny_restrictive", 1, + public static final MaterialPipeStructure TINY_RESTRICTIVE = new MaterialPipeStructure("tiny_restrictive", 1, 1, true, TagPrefix.pipeTinyRestrictive, 0.25f, PipeModel.RESTRICTIVE_INSTANCES[0]); - public static final MaterialPipeStructure SMALL_RESTRICTIVE = new MaterialPipeStructure("pipe_small_restrictive", 2, + public static final MaterialPipeStructure SMALL_RESTRICTIVE = new MaterialPipeStructure("small_restrictive", 2, 1, true, TagPrefix.pipeSmallRestrictive, 0.375f, PipeModel.RESTRICTIVE_INSTANCES[1]); - public static final MaterialPipeStructure NORMAL_RESTRICTIVE = new MaterialPipeStructure("pipe_normal_restrictive", + public static final MaterialPipeStructure NORMAL_RESTRICTIVE = new MaterialPipeStructure("normal_restrictive", 6, 1, true, TagPrefix.pipeNormalRestrictive, 0.5f, PipeModel.RESTRICTIVE_INSTANCES[2]); - public static final MaterialPipeStructure LARGE_RESTRICTIVE = new MaterialPipeStructure("pipe_large_restrictive", + public static final MaterialPipeStructure LARGE_RESTRICTIVE = new MaterialPipeStructure("large_restrictive", 12, 1, true, TagPrefix.pipeLargeRestrictive, 0.75f, PipeModel.RESTRICTIVE_INSTANCES[3]); - public static final MaterialPipeStructure HUGE_RESTRICTIVE = new MaterialPipeStructure("pipe_huge_restrictive", 24, + public static final MaterialPipeStructure HUGE_RESTRICTIVE = new MaterialPipeStructure("huge_restrictive", 24, 1, true, TagPrefix.pipeHugeRestrictive, 0.875f, PipeModel.RESTRICTIVE_INSTANCES[4]); public static final MaterialPipeStructure QUADRUPLE_RESTRICTIVE = new MaterialPipeStructure( - "pipe_quadruple_restrictive", 8, 4, true, + "quadruple_restrictive", 8, 4, true, TagPrefix.pipeQuadrupleRestrictive, 0.95f, PipeModel.RESTRICTIVE_INSTANCES[5]); public static final MaterialPipeStructure NONUPLE_RESTRICTIVE = new MaterialPipeStructure( - "pipe_nonuple_restrictive", 18, 9, true, + "nonuple_restrictive", 18, 9, true, TagPrefix.pipeNonupleRestrictive, 0.95f, PipeModel.RESTRICTIVE_INSTANCES[6]); public MaterialPipeStructure(String name, int material, int channelCount, boolean restrictive, TagPrefix prefix, diff --git a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java index b02da3d259..be3aa8f63f 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java @@ -30,7 +30,6 @@ import net.minecraft.tags.TagEntry; import net.minecraft.tags.TagKey; import net.minecraft.tags.TagLoader; -import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantments; @@ -54,7 +53,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.function.Consumer; import java.util.function.Supplier; public class MixinHelpers { @@ -286,10 +284,4 @@ public static void addFluidTexture(Material material, FluidStorage.FluidEntry va } } } - - public static void loadBakedModelTextures(ResourceLocation atlas, Consumer consumer) { - if (atlas.equals(InventoryMenu.BLOCK_ATLAS)) { - - } - } } diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java index af815c8acd..465cd5fc3a 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java @@ -40,6 +40,7 @@ public abstract class ModelManagerMixin { ToolItemRenderer.reinitModels(); SurfaceRockRenderer.reinitModels(); GTModels.registerMaterialFluidModels(); + GTModels.registerPipeModels(); GTCEu.LOGGER.info("GregTech Model loading took {}ms", System.currentTimeMillis() - startTime); } } diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java deleted file mode 100644 index ca8528c862..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/SpriteResourceLoaderMixin.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.gregtechceu.gtceu.core.mixins; - -import com.gregtechceu.gtceu.core.MixinHelpers; - -import net.minecraft.client.renderer.texture.atlas.SpriteResourceLoader; -import net.minecraft.client.renderer.texture.atlas.SpriteSource; -import net.minecraft.client.renderer.texture.atlas.sources.SingleFile; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -@Mixin(SpriteResourceLoader.class) -public class SpriteResourceLoaderMixin { - - // try to load all renderer textures - @Inject(method = "load", - at = @At(value = "RETURN"), - locals = LocalCapture.CAPTURE_FAILHARD) - private static void injectLoad(ResourceManager resourceManager, ResourceLocation location, - CallbackInfoReturnable cir, ResourceLocation resourceLocation, - List list) { - ResourceLocation atlas = new ResourceLocation(location.getNamespace(), - "textures/atlas/%s.png".formatted(location.getPath())); - Set sprites = new HashSet<>(); - MixinHelpers.loadBakedModelTextures(atlas, sprites::add); - for (ResourceLocation sprite : sprites) { - list.add(new SingleFile(sprite, Optional.empty())); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java index 6370913da9..abf772f9d4 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.integration.jade.provider.*; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java index 221cea60e3..e20f69e1d3 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java @@ -1,8 +1,8 @@ package com.gregtechceu.gtceu.integration.jade.provider; import com.gregtechceu.gtceu.GTCEu; - import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; + import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -10,9 +10,7 @@ import net.minecraft.server.level.ServerPlayer; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import snownee.jade.api.Accessor; -import snownee.jade.api.fluid.JadeFluidObject; import snownee.jade.api.view.*; import java.util.ArrayList; @@ -38,13 +36,13 @@ public List> getClientGroups(Accessor accessor, Li MaterialPipeBlockEntity pipe, boolean showDetails) { List> tanks = new ArrayList<>(); /* - for (var tank : pipe.getFluidTanks()) { - if (tank.getFluidAmount() > 0) { - tanks.add(new ViewGroup<>(List.of(FluidView.writeDefault( - JadeFluidObject.of(tank.getFluid().getFluid(), tank.getFluidAmount()), tank.getCapacity())))); - } - } - */ + * for (var tank : pipe.getFluidTanks()) { + * if (tank.getFluidAmount() > 0) { + * tanks.add(new ViewGroup<>(List.of(FluidView.writeDefault( + * JadeFluidObject.of(tank.getFluid().getFluid(), tank.getFluidAmount()), tank.getCapacity())))); + * } + * } + */ return tanks; } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/ReflectionUtils.java b/src/main/java/com/gregtechceu/gtceu/utils/ReflectionUtils.java new file mode 100644 index 0000000000..d7cab02206 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/utils/ReflectionUtils.java @@ -0,0 +1,18 @@ +package com.gregtechceu.gtceu.utils; + +import java.lang.reflect.Field; + +public class ReflectionUtils { + + public static O getOuterClassObject(I innerClass, Class outerClassType) { + try { + for (Field field : innerClass.getClass().getDeclaredFields()) { + if (field.getType().isAssignableFrom(outerClassType)) { + field.setAccessible(true); + return (O) field.get(innerClass); + } + } + } catch (IllegalAccessException ignored) {} + return null; + } +} diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index e416b85be7..030667f7bd 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -25,3 +25,5 @@ public net.minecraft.world.entity.vehicle.Boat f_38285_ # DATA_ID_TYPE # for AE2 to be able to load (idk why but it needs these?) public net.minecraft.world.level.block.Blocks m_50774_(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z # always public net.minecraft.world.level.block.Blocks m_50805_(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z # never + +public net.minecraft.client.resources.model.ModelBakery$ModelBakerImpl diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_activable.json b/src/main/resources/assets/gtceu/blockstates/pipe_activable.json new file mode 100644 index 0000000000..9d0c0a3397 --- /dev/null +++ b/src/main/resources/assets/gtceu/blockstates/pipe_activable.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "gtceu:block/pipe/optical" + } + } +} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_cable.json b/src/main/resources/assets/gtceu/blockstates/pipe_cable.json new file mode 100644 index 0000000000..5afffd2675 --- /dev/null +++ b/src/main/resources/assets/gtceu/blockstates/pipe_cable.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "gtceu:block/pipe/cable_wire" + } + } +} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_duct.json b/src/main/resources/assets/gtceu/blockstates/pipe_duct.json new file mode 100644 index 0000000000..dfb59a8466 --- /dev/null +++ b/src/main/resources/assets/gtceu/blockstates/pipe_duct.json @@ -0,0 +1,7 @@ +{ + "variants": { + "duct_pipe": { + "model": "gtceu:block/pipe/duct" + } + } +} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_material.json b/src/main/resources/assets/gtceu/blockstates/pipe_material.json new file mode 100644 index 0000000000..c483b723bf --- /dev/null +++ b/src/main/resources/assets/gtceu/blockstates/pipe_material.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "gtceu:block/pipe/pipe_0_standard" + } + } +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/duct.json b/src/main/resources/assets/gtceu/models/block/pipe/duct.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/duct.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/laser.json b/src/main/resources/assets/gtceu/models/block/pipe/laser.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/laser.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/optical.json b/src/main/resources/assets/gtceu/models/block/pipe/optical.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/optical.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json new file mode 100644 index 0000000000..2c6047defb --- /dev/null +++ b/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json @@ -0,0 +1,3 @@ +{ + "loader": "forge:empty" +} diff --git a/src/main/resources/gtceu.mixins.json b/src/main/resources/gtceu.mixins.json index dcc6c476cc..ec71dfef3b 100644 --- a/src/main/resources/gtceu.mixins.json +++ b/src/main/resources/gtceu.mixins.json @@ -16,7 +16,6 @@ "LevelRendererMixin", "ModelManagerMixin", "MultiPlayerGameModeMixin", - "SpriteResourceLoaderMixin", "rei.FluidEntryRendererMixin" ], "mixins": [ From 6c0de356b336ad5eee4c63f314e7e38cc55fad81 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 24 Aug 2024 13:39:23 +0300 Subject: [PATCH 12/70] it works now yay --- dependencies.gradle | 3 ++- gradle/scripts/jars.gradle | 9 +++++++ .../pipenet/physical/IPipeStructure.java | 3 +-- .../pipenet/physical/block/PipeBlock.java | 27 +++++++++++-------- .../physical/tile/PipeBlockEntity.java | 7 ----- .../api/machine/IMachineBlockEntity.java | 18 ------------- 6 files changed, 28 insertions(+), 39 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index e313b42122..dee7d72e4a 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -4,7 +4,8 @@ dependencies { // Shadowed Dependencies // Packages that aren't mods, and thus need to be included in the release files. - shadow('org.jgrapht:jgrapht-core:1.5.2') // JGraphT 1.5.2 + api(shadow('org.jgrapht:jgrapht-core:1.5.2')) // JGraphT 1.5.2 + forgeRuntimeLibrary('org.jgrapht:jgrapht-core:1.5.2') // LDLib modApi(forge.ldlib.forge) { transitive = false } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 1fbef17270..0602a7e19e 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -4,10 +4,13 @@ tasks.register('slimJar', Jar) { } shadowJar { + dependsOn shadowJar.configurations configurations = [project.configurations.shadow] archiveClassifier = "dev-shadow" minimize() relocate("org.jgrapht", "${maven_group}.repack.org.jgrapht") + relocate("org.jheaps", "${maven_group}.repack.org.jheaps") + relocate("org.apfloat", "${maven_group}.repack.org.apfloat") } obfuscation { @@ -16,6 +19,12 @@ obfuscation { } } +jar { + exclude ".cache/*" + + archiveClassifier = "dev" +} + tasks.register('sourcesJar', Jar) { from delombok.outputs.files dependsOn delombok diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java index a5ecbe3b96..ac042478ee 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -48,8 +48,7 @@ default VoxelShape getPipeBoxes(@NotNull PipeBlockEntity tileContext) { pipeBoxes = Shapes.or(pipeBoxes, getSideBox(null, thickness)); } for (Direction facing : GTUtil.DIRECTIONS) { - if (tileContext.isConnected(facing)) - pipeBoxes = Shapes.or(pipeBoxes, getSideBox(facing, thickness)); + if (tileContext.isConnected(facing)) pipeBoxes = Shapes.or(pipeBoxes, getSideBox(facing, thickness)); } return pipeBoxes; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index e9a61d71d7..f2bd3ca383 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -55,12 +55,12 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.EntityCollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.Getter; -import org.apache.commons.lang3.mutable.MutableObject; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -416,18 +416,23 @@ public void entityInside(BlockState state, Level level, BlockPos pos, Entity ent @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - MutableObject shape = new MutableObject<>(Shapes.empty()); - PipeBlockEntity tile = getBlockEntity(level, pos); - if (tile != null) { - tile.getCoverBoxes(bb -> shape.setValue(Shapes.or(shape.getValue(), bb))); - if (tile.getFrameMaterial() != null) { - shape.setValue(Shapes.or(shape.getValue(), Shapes.block())); + if (context instanceof EntityCollisionContext entityCtx && entityCtx.getEntity() instanceof Player player) { + if (hasPipeCollisionChangingItem(level, pos, player)) { + return Shapes.block(); } - shape.setValue(Shapes.or(shape.getValue(), getStructure().getPipeBoxes(tile))); - } else { - shape.setValue(Shapes.block()); } - return shape.getValue(); + + PipeBlockEntity tile = getBlockEntity(level, pos); + if (tile == null) { + return Shapes.block(); + } + if (tile.getFrameMaterial() != null) { + return Shapes.block(); + } + List shapes = new ArrayList<>(); + shapes.add(getStructure().getPipeBoxes(tile)); + tile.getCoverBoxes(shapes::add); + return shapes.stream().reduce(Shapes.empty(), Shapes::or); } public boolean hasPipeCollisionChangingItem(BlockGetter world, BlockPos pos, Entity entity) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index d10cb66416..63e3dd671e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -631,13 +631,6 @@ public void spawnParticles(Direction direction, ParticleOptions particleType, in // misc overrides // - @Override - public void notifyBlockUpdate() { - if (getLevel() != null) { - getLevel().updateNeighborsAt(getBlockPos(), getLevel().getBlockState(getBlockPos()).getBlock()); - } - } - public void scheduleNeighborShapeUpdate() { Level level = getLevel(); BlockPos pos = getBlockPos(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java index 44e5478437..ee445c4928 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/IMachineBlockEntity.java @@ -35,24 +35,6 @@ default BlockPos pos() { return self().getBlockPos(); } - default void notifyBlockUpdate() { - if (level() != null) { - level().updateNeighborsAt(pos(), level().getBlockState(pos()).getBlock()); - } - } - - default void scheduleRenderUpdate() { - var pos = pos(); - if (level() != null) { - var state = level().getBlockState(pos); - if (level().isClientSide) { - level().sendBlockUpdated(pos, state, state, 1 << 3); - } else { - level().blockEvent(pos, state.getBlock(), 1, 0); - } - } - } - default long getOffsetTimer() { return level() == null ? getOffset() : (level().getGameTime() + getOffset()); } From 918fcad6295cf75b2f14a44dce2fec6a06fcaef7 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 24 Aug 2024 14:02:27 +0300 Subject: [PATCH 13/70] actually fix #1650 --- .../com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java | 1 + .../gregtechceu/gtceu/common/machine/storage/BufferMachine.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java b/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java index aaa2fd32a9..f7a922e5cc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java @@ -50,6 +50,7 @@ import it.unimi.dsi.fastutil.ints.Int2LongFunction; import lombok.Getter; import lombok.Setter; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import java.util.*; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java index bf898c51fa..3e81e25ee0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java @@ -37,6 +37,7 @@ import lombok.Getter; import lombok.Setter; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import java.util.Set; From f55c36b475b381cb393c2a72b5efe925caec7289 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 24 Aug 2024 14:15:18 +0300 Subject: [PATCH 14/70] allow blocks without block entities to do grid highlights as well --- .../physical/tile/PipeBlockEntity.java | 27 +++++++++++++++++++ .../api/machine/SimpleTieredMachine.java | 1 - .../common/machine/storage/BufferMachine.java | 1 - 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 63e3dd671e..8c75780f2f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -32,6 +32,7 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; @@ -731,6 +732,32 @@ public void setNeighborsToFire() { } } + @Override + public boolean shouldRenderGrid(Player player, BlockPos pos, BlockState state, ItemStack held, + Set toolTypes) { + if (toolTypes.contains(getBlockType().getToolClass()) || toolTypes.contains(GTToolType.SCREWDRIVER)) + return true; + for (CoverBehavior cover : covers.getCovers()) { + if (cover.shouldRenderGrid(player, pos, state, held, toolTypes)) return true; + } + return false; + } + + public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, Set toolTypes, Direction side) { + if (toolTypes.contains(getBlockType().getToolClass())) { + if (player.isShiftKeyDown() && this.getBlockType().allowsBlocking()) { + return getStructure().getPipeTexture(isBlocked(side)); + } else { + return getStructure().getPipeTexture(isConnected(side)); + } + } + var cover = covers.getCoverAtSide(side); + if (cover != null) { + return cover.sideTips(player, pos, state, toolTypes, side); + } + return null; + } + @Override public Pair<@Nullable GTToolType, InteractionResult> onToolClick(@NotNull Set toolTypes, ItemStack itemStack, UseOnContext context) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java b/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java index f7a922e5cc..aaa2fd32a9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/SimpleTieredMachine.java @@ -50,7 +50,6 @@ import it.unimi.dsi.fastutil.ints.Int2LongFunction; import lombok.Getter; import lombok.Setter; -import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import java.util.*; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java index 3e81e25ee0..bf898c51fa 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/BufferMachine.java @@ -37,7 +37,6 @@ import lombok.Getter; import lombok.Setter; -import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import java.util.Set; From ae1b6104b7c5334a76f8b1a9047972a93eece884 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 24 Aug 2024 14:20:59 +0300 Subject: [PATCH 15/70] fix world pipe nets not having their level set correctly --- .../api/graphnet/pipenet/WorldPipeNet.java | 7 ---- .../api/graphnet/servernet/ServerNet.java | 34 ++++++++++--------- .../pipelike/block/duct/DuctPipeBlock.java | 5 --- .../pipelike/net/duct/WorldDuctNet.java | 10 +++--- .../pipelike/net/energy/WorldEnergyNet.java | 10 +++--- .../pipelike/net/fluid/WorldFluidNet.java | 10 +++--- .../pipelike/net/item/WorldItemNet.java | 10 +++--- .../pipelike/net/laser/WorldLaserNet.java | 10 +++--- .../pipelike/net/optical/WorldOpticalNet.java | 10 +++--- 9 files changed, 54 insertions(+), 52 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index b736543a8e..13f2d9b9d8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -174,13 +174,6 @@ public void synchronizeNode(WorldPipeNetNode node) { }); } - public static String getDataID(final String baseID, final Level world) { - if (world == null || world.isClientSide) - throw new RuntimeException("WorldPipeNets should only be created on the server!"); - ResourceKey dimension = world.dimension(); - return baseID + '/' + dimension.location(); - } - /** * Get the network ID for this net. Must be unique and deterministic between server and client, but can change * between mod versions. diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java index 4f167a4adb..18a2724ff4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java @@ -6,10 +6,13 @@ import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import com.gregtechceu.gtceu.api.graphnet.graph.NetDirectedGraph; +import com.gregtechceu.gtceu.api.graphnet.graph.NetUndirectedGraph; import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; import net.minecraft.core.GlobalPos; import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.saveddata.SavedData; import org.jetbrains.annotations.NotNull; @@ -25,22 +28,21 @@ public abstract class ServerNet extends SavedData implements IGraphNet { protected final GraphNetBacker backer; - /* - * public static ServerNet get(String name, ServerLevel level, Function graphBuilder, - * AlgorithmBuilder... algorithmBuilder) { - * return level.getDataStorage().computeIfAbsent(tag -> new ServerNet(tag, graphBuilder, algorithmBuilder), () -> - * new ServerNet(graphBuilder, algorithmBuilder), name); - * } - * - * public static ServerNet get(String name, ServerLevel level, boolean directed, AlgorithmBuilder... - * algorithmBuilders) { - * return get(name, level, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), - * algorithmBuilders); - * } - */ - - public ServerNet(Function graphBuilder, - AlgorithmBuilder... algorithmBuilders) { +// USERS: ADD THESE METHODS TO YOUR CLASS +// public static ServerNet get(ServerLevel level, Function graphBuilder, +// AlgorithmBuilder... algorithmBuilder) { +// return level.getDataStorage().computeIfAbsent(tag -> new ServerNet(tag, graphBuilder, algorithmBuilder), () -> +// new ServerNet(graphBuilder, algorithmBuilder), name); +// } +// +// public static ServerNet get(ServerLevel level, boolean directed, AlgorithmBuilder... +// algorithmBuilders) { +// return get(level, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), +// algorithmBuilders); +// } + + + public ServerNet(Function graphBuilder, AlgorithmBuilder... algorithmBuilders) { this.backer = new GraphNetBacker(this, graphBuilder.apply(this), algorithmBuilders); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java index a5fe0205f8..a42822ac42 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java @@ -21,11 +21,6 @@ protected String getConnectLangKey() { return "gregtech.tool_action.wrench.connect"; } - @Override - public boolean allowsBlocking() { - return false; - } - @Override protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { return DuctNetHandler.INSTANCE; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java index 5c940b5e31..2875869a0e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/duct/WorldDuctNet.java @@ -23,11 +23,13 @@ public class WorldDuctNet extends WorldPipeNet implements BasicWorldPipeNetPath. private static final String DATA_ID = "gtceu_world_laser_net"; public static WorldDuctNet getWorldNet(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> { - WorldDuctNet net = new WorldDuctNet(); - net.load(tag); - return net; + WorldDuctNet net = serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldDuctNet netx = new WorldDuctNet(); + netx.load(tag); + return netx; }, WorldDuctNet::new, DATA_ID); + net.setLevel(serverLevel); + return net; } public WorldDuctNet() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java index f585a91e5c..21ea893831 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/WorldEnergyNet.java @@ -26,11 +26,13 @@ public final class WorldEnergyNet extends WorldPipeNet implements FlowWorldPipeN private static final String DATA_ID = "gtceu_world_energy_net"; public static WorldEnergyNet getWorldNet(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> { - WorldEnergyNet net = new WorldEnergyNet(); - net.load(tag); - return net; + WorldEnergyNet net = serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldEnergyNet netx = new WorldEnergyNet(); + netx.load(tag); + return netx; }, WorldEnergyNet::new, DATA_ID); + net.setLevel(serverLevel); + return net; } public WorldEnergyNet() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java index e1423f6391..babb727da8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java @@ -34,11 +34,13 @@ public class WorldFluidNet extends WorldPipeNet implements FlowWorldPipeNetPath. private static final String DATA_ID = "gtceu_world_fluid_net"; public static WorldFluidNet getWorldNet(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> { - WorldFluidNet net = new WorldFluidNet(); - net.load(tag); - return net; + WorldFluidNet net = serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldFluidNet netx = new WorldFluidNet(); + netx.load(tag); + return netx; }, WorldFluidNet::new, DATA_ID); + net.setLevel(serverLevel); + return net; } public WorldFluidNet() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java index 5bf88ef33a..f77aa329f2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java @@ -35,11 +35,13 @@ public class WorldItemNet extends WorldPipeNet implements FlowWorldPipeNetPath.P private static final String DATA_ID = "gtceu_world_item_net"; public static WorldItemNet getWorldNet(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> { - WorldItemNet net = new WorldItemNet(); - net.load(tag); - return net; + WorldItemNet net = serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldItemNet netx = new WorldItemNet(); + netx.load(tag); + return netx; }, WorldItemNet::new, DATA_ID); + net.setLevel(serverLevel); + return net; } public WorldItemNet() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java index b08e473c57..307e9ed5c1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/laser/WorldLaserNet.java @@ -23,11 +23,13 @@ public class WorldLaserNet extends WorldPipeNet implements BasicWorldPipeNetPath private static final String DATA_ID = "gtceu_world_laser_net"; public static WorldLaserNet getWorldNet(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> { - WorldLaserNet net = new WorldLaserNet(); - net.load(tag); - return net; + WorldLaserNet net = serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldLaserNet netx = new WorldLaserNet(); + netx.load(tag); + return netx; }, WorldLaserNet::new, DATA_ID); + net.setLevel(serverLevel); + return net; } public WorldLaserNet() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java index f0f8abe8f7..7833eeb0db 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/WorldOpticalNet.java @@ -23,11 +23,13 @@ public class WorldOpticalNet extends WorldPipeNet implements BasicWorldPipeNetPa private static final String DATA_ID = "gtceu_world_optical_net"; public static WorldOpticalNet getWorldNet(ServerLevel serverLevel) { - return serverLevel.getDataStorage().computeIfAbsent(tag -> { - WorldOpticalNet net = new WorldOpticalNet(); - net.load(tag); - return net; + WorldOpticalNet net = serverLevel.getDataStorage().computeIfAbsent(tag -> { + WorldOpticalNet netx = new WorldOpticalNet(); + netx.load(tag); + return netx; }, WorldOpticalNet::new, DATA_ID); + net.setLevel(serverLevel); + return net; } public WorldOpticalNet() { From 7bd7a6e3c30906cff000a2742ab21d721bfaeeaa Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 24 Aug 2024 14:26:09 +0300 Subject: [PATCH 16/70] clean up JAVD compat because it annoyed me --- .../gtceu/core/mixins/IHolderReferenceAccessor.java | 12 ------------ .../java/com/gregtechceu/gtceu/utils/GTUtil.java | 11 ++++++----- src/main/resources/gtceu.mixins.json | 1 - 3 files changed, 6 insertions(+), 18 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/IHolderReferenceAccessor.java diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/IHolderReferenceAccessor.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/IHolderReferenceAccessor.java deleted file mode 100644 index 3a2bc3bdbe..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/IHolderReferenceAccessor.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.gregtechceu.gtceu.core.mixins; - -import net.minecraft.core.Holder; - -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(Holder.Reference.class) -public interface IHolderReferenceAccessor extends Holder { - - // @Invoker - // void invokeBind(ResourceKey key, T value); -} diff --git a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java index a88889f821..e89914fa21 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java @@ -21,11 +21,11 @@ import net.minecraft.core.Direction; import net.minecraft.core.Holder; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; 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.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BiomeTags; import net.minecraft.util.RandomSource; @@ -520,7 +520,8 @@ public static boolean canSeeSunClearly(Level world, BlockPos blockPos) { return false; } - Biome biome = world.getBiome(blockPos.above()).value(); + Holder biomeHolder = world.getBiome(blockPos.above()); + Biome biome = biomeHolder.value(); if (world.isRaining()) { if (biome.warmEnoughToRain(blockPos.above()) || biome.coldEnoughToSnow(blockPos.above())) { return false; @@ -531,9 +532,9 @@ public static boolean canSeeSunClearly(Level world, BlockPos blockPos) { return false; } - ResourceLocation javdVoidBiome = new ResourceLocation("javd", "void"); - if (GTCEu.isJAVDLoaded() && - world.registryAccess().registryOrThrow(Registries.BIOME).getKey(biome).equals(javdVoidBiome)) { + ResourceLocation javdVoidBiome = new ResourceLocation(GTValues.MODID_JAVD, "void"); + if (GTCEu.isJAVDLoaded() && javdVoidBiome + .equals(biomeHolder.unwrapKey().map(ResourceKey::location).orElse(null))) { return !world.isDay(); } else return world.isDay(); } diff --git a/src/main/resources/gtceu.mixins.json b/src/main/resources/gtceu.mixins.json index ec71dfef3b..67db6275ee 100644 --- a/src/main/resources/gtceu.mixins.json +++ b/src/main/resources/gtceu.mixins.json @@ -28,7 +28,6 @@ "CreeperMixin", "EntityMixin", "IFoliagePlacerTypeAccessor", - "IHolderReferenceAccessor", "IngredientAccessor", "IntersectionIngredientAccessor", "InventoryMixin", From 70cb63a097e215a840e76a814adc59b58f0ea465 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 24 Aug 2024 23:24:38 +0300 Subject: [PATCH 17/70] everything works, except: - placing machines on cables connecting - placing cables on machines connecting - fancy glow effect on cable melt --- dependencies.gradle | 2 +- .../gtceu/api/block/MetaMachineBlock.java | 5 +- ...Entity.java => BaseSyncedBlockEntity.java} | 12 +- .../gtceu/api/blockentity/INeighborCache.java | 7 +- .../blockentity/NeighborCacheBlockEntity.java | 9 +- .../gtceu/api/graphnet/NetNode.java | 21 +- .../api/graphnet/logic/NetLogicData.java | 2 - .../pipenet/logic/TemperatureLogic.java | 6 +- .../graphnet/pipenet/physical/IBurnable.java | 1 - .../physical/block/ActivablePipeBlock.java | 15 +- .../physical/block/MaterialPipeBlockItem.java | 20 +- .../pipenet/physical/block/PipeBlock.java | 62 ++++- .../pipenet/physical/block/PipeBlockItem.java | 29 +- ...lPipeBlock.java => PipeMaterialBlock.java} | 10 +- .../tile/ActivablePipeBlockEntity.java | 34 +++ .../tile/MaterialPipeBlockEntity.java | 51 +--- .../tile/PipeActivableBlockEntity.java | 56 ---- .../physical/tile/PipeBlockEntity.java | 107 +++++--- .../pipenet/predicate/FilterPredicate.java | 19 -- .../api/graphnet/servernet/ServerNet.java | 28 +- .../gtceu/api/item/MetaMachineItem.java | 3 +- .../api/machine/MachineCoverContainer.java | 10 +- .../client/particle/GTOverheatParticle.java | 57 +++- .../gtceu/client/particle/GTParticle.java | 16 +- .../client/particle/GTParticleManager.java | 21 +- .../renderer/pipe/AbstractPipeModel.java | 8 +- .../renderer/pipe/ActivablePipeModel.java | 57 ++-- .../client/renderer/pipe/CableModel.java | 49 ++-- .../gtceu/client/renderer/pipe/PipeModel.java | 26 +- .../pipe/cover/CoverRendererBuilder.java | 3 +- .../renderer/pipe/quad/PipeQuadHelper.java | 3 +- .../client/renderer/pipe/quad/QuadHelper.java | 110 +------- .../pipe/quad/RecolorableBakedQuad.java | 85 ++---- .../pipe/util/SpriteInformationWrapper.java | 36 --- .../client/util/EffectRenderContext.java | 20 +- .../gtceu/client/util/RenderBufferHelper.java | 6 +- .../gtceu/client/util/StaticFaceBakery.java | 131 ++++++--- .../KineticMachineBlockEntity.java | 3 +- .../cover/filter/BaseFilterContainer.java | 256 ------------------ .../gtceu/common/data/GTBlockEntities.java | 12 +- .../gtceu/common/data/GTBlocks.java | 14 +- .../pipelike/block/cable/CableBlock.java | 4 +- .../pipelike/block/laser/LaserStructure.java | 7 + .../block/optical/OpticalStructure.java | 7 + .../block/pipe/MaterialPipeBlock.java | 4 +- .../common/pipelike/net/SlowActiveWalker.java | 4 +- .../jade/provider/CableBlockProvider.java | 2 +- .../jade/provider/StainedColorProvider.java | 5 +- .../gtceu/utils/DummyMachineBlockEntity.java | 5 +- .../gtceu/utils/SupplierMemoizer.java | 6 + .../gtceu/blockstates/pipe_activable.json | 7 - .../assets/gtceu/blockstates/pipe_cable.json | 7 - .../assets/gtceu/blockstates/pipe_duct.json | 7 - .../gtceu/blockstates/pipe_material.json | 7 - .../models/block/pipe/cable_insulation_0.json | 3 - .../models/block/pipe/cable_insulation_1.json | 3 - .../models/block/pipe/cable_insulation_2.json | 3 - .../models/block/pipe/cable_insulation_3.json | 3 - .../models/block/pipe/cable_insulation_4.json | 3 - .../gtceu/models/block/pipe/cable_wire.json | 3 - .../assets/gtceu/models/block/pipe/duct.json | 3 - .../assets/gtceu/models/block/pipe/laser.json | 3 - .../gtceu/models/block/pipe/optical.json | 3 - .../models/block/pipe/pipe_0_restrictive.json | 3 - .../models/block/pipe/pipe_0_standard.json | 3 - .../models/block/pipe/pipe_1_restrictive.json | 3 - .../models/block/pipe/pipe_1_standard.json | 3 - .../models/block/pipe/pipe_2_restrictive.json | 3 - .../models/block/pipe/pipe_2_standard.json | 3 - .../models/block/pipe/pipe_3_restrictive.json | 3 - .../models/block/pipe/pipe_3_standard.json | 3 - .../models/block/pipe/pipe_4_restrictive.json | 3 - .../models/block/pipe/pipe_4_standard.json | 3 - .../models/block/pipe/pipe_5_restrictive.json | 3 - .../models/block/pipe/pipe_5_standard.json | 3 - .../models/block/pipe/pipe_6_restrictive.json | 3 - .../models/block/pipe/pipe_6_standard.json | 3 - .../gtceu/models/item/invar_lighter.json | 2 +- .../gtceu/models/item/platinum_lighter.json | 2 +- 79 files changed, 570 insertions(+), 997 deletions(-) rename src/main/java/com/gregtechceu/gtceu/api/blockentity/{SyncedBlockEntity.java => BaseSyncedBlockEntity.java} (88%) rename src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/{MaterialPipeBlock.java => PipeMaterialBlock.java} (86%) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/ActivablePipeBlockEntity.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java delete mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_activable.json delete mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_cable.json delete mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_duct.json delete mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_material.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/duct.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/laser.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/optical.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json delete mode 100644 src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json diff --git a/dependencies.gradle b/dependencies.gradle index dee7d72e4a..97321c2a82 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -63,7 +63,7 @@ dependencies { jarJar(forge.configuration) // Shimmer - modCompileOnly(forge.shimmer.forge) { transitive = false } + modImplementation(forge.shimmer.forge) { transitive = false } modCompileOnly("maven.modrinth:embeddium:0.3.19+mc1.20.1") modCompileOnly("maven.modrinth:oculus:1.20.1-1.7.0") diff --git a/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java b/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java index f2cffcfaa9..2789997b40 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java @@ -262,9 +262,7 @@ public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState machineLife.onMachineRemoved(); } if (machine != null) { - for (Direction direction : GTUtil.DIRECTIONS) { - machine.getCoverContainer().removeCover(direction, null); - } + machine.getCoverContainer().dropAllCovers(); } pLevel.updateNeighbourForOutputSignal(pPos, this); @@ -366,6 +364,7 @@ public void neighborChanged(BlockState state, Level level, BlockPos pos, Block b var machine = getMachine(level, pos); if (machine != null) { machine.onNeighborChanged(block, fromPos, isMoving); + machine.getCoverContainer().updateInputRedstoneSignals(); } super.neighborChanged(state, level, pos, block, fromPos, isMoving); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/SyncedBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/BaseSyncedBlockEntity.java similarity index 88% rename from src/main/java/com/gregtechceu/gtceu/api/blockentity/SyncedBlockEntity.java rename to src/main/java/com/gregtechceu/gtceu/api/blockentity/BaseSyncedBlockEntity.java index 7217941ea5..84b2750580 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/SyncedBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/BaseSyncedBlockEntity.java @@ -26,11 +26,11 @@ import java.util.Arrays; import java.util.function.Consumer; -public abstract class SyncedBlockEntity extends BlockEntity implements ISyncedBlockEntity, INeighborCache { +public abstract class BaseSyncedBlockEntity extends BlockEntity implements ISyncedBlockEntity, INeighborCache { private final PacketDataList updates = new PacketDataList(); - public SyncedBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { + public BaseSyncedBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); } @@ -53,7 +53,7 @@ public final void writeCustomData(int discriminator, @NotNull Consumer<@NotNull * * @param syncedBlockEntity other synced tile entity */ - public void addPacketsFrom(SyncedBlockEntity syncedBlockEntity) { + public void addPacketsFrom(BaseSyncedBlockEntity syncedBlockEntity) { if (this == syncedBlockEntity || syncedBlockEntity.updates.isEmpty()) return; boolean wasEmpty = this.updates.isEmpty(); this.updates.addAll(syncedBlockEntity.updates); @@ -87,7 +87,7 @@ public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { receiveCustomData(Integer.parseInt(discriminatorKey), new FriendlyByteBuf(backedBuffer)); if (backedBuffer.readableBytes() != 0) { GTCEu.LOGGER.error( - "Class {} failed to finish reading receiveCustomData with discriminator {} and {} bytes remaining", + "Block entity {} failed to finish reading receiveCustomData with discriminator {} and {} bytes remaining", BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(this.getType()), discriminatorKey, backedBuffer.readableBytes()); } @@ -97,7 +97,7 @@ public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { @Override public final @NotNull CompoundTag getUpdateTag() { - CompoundTag updateTag = super.getUpdateTag(); + CompoundTag updateTag = super.saveWithoutMetadata(); ByteBuf backedBuffer = Unpooled.buffer(); writeInitialSyncData(new FriendlyByteBuf(backedBuffer)); byte[] updateData = Arrays.copyOfRange(backedBuffer.array(), 0, backedBuffer.writerIndex()); @@ -112,7 +112,7 @@ public final void handleUpdateTag(@NotNull CompoundTag tag) { ByteBuf backedBuffer = Unpooled.copiedBuffer(updateData); receiveInitialSyncData(new FriendlyByteBuf(backedBuffer)); if (backedBuffer.readableBytes() != 0) { - GTCEu.LOGGER.error("Class {} failed to finish reading initialSyncData with {} bytes remaining", + GTCEu.LOGGER.error("Block entity {} failed to finish reading initialSyncData with {} bytes remaining", BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(this.getType()), backedBuffer.readableBytes()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java index bf77251371..6361cf2a33 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/INeighborCache.java @@ -2,6 +2,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import org.jetbrains.annotations.NotNull; @@ -28,7 +29,9 @@ public interface INeighborCache extends IHasWorldObjectAndCoords { /** * Called when an adjacent neighboring block has changed at a side in some way * - * @param facing the side at which the neighbor has changed + * @param fromBlock + * @param fromPos the side at which the neighbor has changed + * @param isMoving */ - void onNeighborChanged(@NotNull Direction facing); + void onNeighborChanged(Block fromBlock, BlockPos fromPos, boolean isMoving); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java index 0e780dc71f..46942cd200 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.api.blockentity; +import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IRPCBlockEntity; @@ -7,6 +8,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -17,7 +19,7 @@ import java.util.Arrays; -public abstract class NeighborCacheBlockEntity extends SyncedBlockEntity implements INeighborCache, +public abstract class NeighborCacheBlockEntity extends BaseSyncedBlockEntity implements INeighborCache, IAsyncAutoSyncBlockEntity, IRPCBlockEntity, IAutoPersistBlockEntity { private final BlockEntity[] neighbors = new BlockEntity[6]; @@ -88,7 +90,8 @@ public void onChunkUnloaded() { return neighbor; } - public void onNeighborChanged(@NotNull Direction facing) { - this.neighbors[facing.get3DDataValue()] = this; + public void onNeighborChanged(Block fromBlock, BlockPos fromPos, boolean isMoving) { + Direction facing = GTUtil.getFacingToNeighbor(this.getBlockPos(), fromPos); + if (facing != null) this.neighbors[facing.get3DDataValue()] = this; } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java index 42a48fa7fc..d531b2d8d8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetNode.java @@ -34,9 +34,15 @@ public abstract class NetNode implements ITagSerializable, IContent @ApiStatus.Internal public GraphVertex wrapper; + /** + * Determines whether the node should be treated as a valid destination of pathing algorithms + */ + @Getter private boolean isActive = false; + @Getter private final @NotNull IGraphNet net; + @Getter private final @NotNull NetLogicData data; private @Nullable NetGroup group = null; @@ -48,17 +54,6 @@ public NetNode(@NotNull IGraphNet net) { this.data = net.getDefaultNodeData(); } - public @NotNull IGraphNet getNet() { - return net; - } - - /** - * Determines whether the node should be treated as a valid destination of pathing algorithms - */ - public boolean isActive() { - return isActive; - } - /** * Sets whether the node should be treated as a valid destination of pathing algorithms */ @@ -74,10 +69,6 @@ public void setActive(boolean active) { } } - public @NotNull NetLogicData getData() { - return data; - } - public boolean traverse(long queryTick, boolean simulate) { return true; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index 571c25ec6e..18682a5c5d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -201,7 +201,6 @@ public void deserializeNBT(ListTag nbt) { } } - // @Override public void encode(FriendlyByteBuf buf) { buf.writeVarInt(getEntries().size()); for (NetLogicEntry entry : getEntries()) { @@ -214,7 +213,6 @@ public void encode(FriendlyByteBuf buf) { } } - // @Override public void decode(FriendlyByteBuf buf) { this.logicEntrySet.clear(); int entryCount = buf.readVarInt(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index 3e04e322a4..f90b0d1676 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -24,6 +24,7 @@ import org.jetbrains.annotations.Nullable; import java.lang.ref.WeakReference; +import java.util.Objects; public final class TemperatureLogic extends NetLogicEntry { @@ -304,10 +305,7 @@ public void encode(FriendlyByteBuf buf, boolean fullChange) { buf.writeVarInt(this.thermalMass); this.temperatureLossFunction.encode(buf); buf.writeVarInt(this.functionPriority); - // laughs in java 9 - // noinspection ReplaceNullCheck - if (this.partialBurnTemperature == null) buf.writeVarInt(-1); - else buf.writeVarInt(this.partialBurnTemperature); + buf.writeVarInt(Objects.requireNonNullElse(this.partialBurnTemperature, -1)); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java index 6a622a24cf..a1ec86632f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IBurnable.java @@ -17,7 +17,6 @@ default void partialBurn(BlockState state, Level world, BlockPos pos) {} * Called when the block should be fully burned. */ default void fullyBurn(BlockState state, Level world, BlockPos pos) { - assert Blocks.FIRE != null; world.setBlockAndUpdate(pos, Blocks.FIRE.defaultBlockState()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java index d90965840d..bf7f179ed3 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java @@ -1,14 +1,16 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeActivableBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.ActivablePipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.common.data.GTBlockEntities; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -21,13 +23,18 @@ public ActivablePipeBlock(BlockBehaviour.Properties properties, IPipeStructure s } @Override - public @Nullable PipeActivableBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull BlockPos pos) { + public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return new ActivablePipeBlockEntity(GTBlockEntities.ACTIVABLE_PIPE.get(), pos, state); + } + + @Override + public @Nullable ActivablePipeBlockEntity getBlockEntity(@NotNull BlockGetter world, @NotNull BlockPos pos) { if (lastTilePos.get().equals(pos)) { PipeBlockEntity tile = lastTile.get().get(); - if (tile != null && !tile.isRemoved()) return (PipeActivableBlockEntity) tile; + if (tile != null && !tile.isRemoved()) return (ActivablePipeBlockEntity) tile; } BlockEntity tile = world.getBlockEntity(pos); - if (tile instanceof PipeActivableBlockEntity pipe) { + if (tile instanceof ActivablePipeBlockEntity pipe) { lastTilePos.set(pos.immutable()); lastTile.set(new WeakReference<>(pipe)); return pipe; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index 54f82592f7..e1f5f40578 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -10,13 +10,13 @@ public class MaterialPipeBlockItem extends PipeBlockItem { - public MaterialPipeBlockItem(MaterialPipeBlock block, Item.Properties properties) { + public MaterialPipeBlockItem(PipeMaterialBlock block, Item.Properties properties) { super(block, properties); } @Override - public @NotNull MaterialPipeBlock getBlock() { - return (MaterialPipeBlock) super.getBlock(); + public @NotNull PipeMaterialBlock getBlock() { + return (PipeMaterialBlock) super.getBlock(); } @Override @@ -25,4 +25,18 @@ public Component getName(ItemStack stack) { return material == null ? Component.literal("unnamed") : getBlock().getStructure().getPrefix().getLocalizedName(material); } + + @Override + public Component getDescription() { + Material material = getBlock().material; + return material == null ? Component.literal("unnamed") : + getBlock().getStructure().getPrefix().getLocalizedName(material); + } + + @Override + public String getDescriptionId() { + Material material = getBlock().material; + return material == null ? "unnamed" : + getBlock().getStructure().getPrefix().getUnlocalizedName(material); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index f2bd3ca383..412ef748d8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -104,6 +104,15 @@ public abstract class PipeBlock extends Block implements EntityBlock { public PipeBlock(BlockBehaviour.Properties properties, IPipeStructure structure) { super(properties); this.structure = structure; + this.registerDefaultState(this.defaultBlockState() + .setValue(NORTH, false) + .setValue(EAST, false) + .setValue(SOUTH, false) + .setValue(WEST, false) + .setValue(UP, false) + .setValue(DOWN, false) + .setValue(FRAMED, false) + .setValue(SERVER_TICK, false)); } // net logic // @@ -414,6 +423,22 @@ public void entityInside(BlockState state, Level level, BlockPos pos, Entity ent // collision boxes // + @SuppressWarnings("deprecation") + @Override + public @NotNull VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { + var tile = getBlockEntity(level, pos); + if (tile == null) { + return super.getCollisionShape(state, level, pos, context); + } + if (tile.getFrameMaterial() != null) { + return MaterialBlock.FRAME_COLLISION_BOX; + } + List shapes = new ArrayList<>(); + shapes.add(getStructure().getPipeBoxes(tile)); + tile.getCoverBoxes(shapes::add); + return shapes.stream().reduce(Shapes.empty(), Shapes::or); + } + @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { if (context instanceof EntityCollisionContext entityCtx && entityCtx.getEntity() instanceof Player player) { @@ -427,7 +452,7 @@ public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, Co return Shapes.block(); } if (tile.getFrameMaterial() != null) { - return Shapes.block(); + return MaterialBlock.FRAME_COLLISION_BOX; } List shapes = new ArrayList<>(); shapes.add(getStructure().getPipeBoxes(tile)); @@ -435,13 +460,15 @@ public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, Co return shapes.stream().reduce(Shapes.empty(), Shapes::or); } - public boolean hasPipeCollisionChangingItem(BlockGetter world, BlockPos pos, Entity entity) { - if (entity instanceof Player player) { - return hasPipeCollisionChangingItem(world, pos, player.getMainHandItem()) || - hasPipeCollisionChangingItem(world, pos, player.getOffhandItem()) || - entity.isShiftKeyDown() && isHoldingPipe(player); - } - return false; + @Override + public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor level, BlockPos pos, BlockPos neighborPos) { + return super.updateShape(state, direction, neighborState, level, pos, neighborPos); + } + + public boolean hasPipeCollisionChangingItem(BlockGetter world, BlockPos pos, Player player) { + return hasPipeCollisionChangingItem(world, pos, player.getMainHandItem()) || + hasPipeCollisionChangingItem(world, pos, player.getOffhandItem()) || + player.isShiftKeyDown() && isHoldingPipe(player); } public boolean isHoldingPipe(Player player) { @@ -488,6 +515,15 @@ protected void createBlockStateDefinition(StateDefinition.Builder type, BlockPos pos, BlockState blockState) { + super(type, pos, blockState); + } + + @Override + public ManagedFieldHolder getFieldHolder() { + return MANAGED_FIELD_HOLDER; + } + + // do not save activeness to nbt, it should go away on world save & load. +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java index e2e03ddbdc..ce5794c6d9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java @@ -1,17 +1,10 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; -import com.gregtechceu.gtceu.common.data.GTMaterials; import com.gregtechceu.gtceu.utils.GTUtil; -import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; - import net.minecraft.core.BlockPos; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; @@ -20,55 +13,21 @@ public class MaterialPipeBlockEntity extends PipeBlockEntity { - @Persisted - @DescSynced - private Material material; - public MaterialPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); } @Override - protected void initialize() { - // prevent initialization when we don't know our material; - // this specifically happens right after we have been - // placed and placedBy() has yet to be called. - if (material != null) super.initialize(); - } - - @Override - public void placedBy(ItemStack stack, Player player) { - super.placedBy(stack, player); - setMaterial(getBlockType().material); - initialize(); - } - - @Override - public @NotNull MaterialPipeBlock getBlockType() { - return (MaterialPipeBlock) super.getBlockType(); - } - - public void setMaterial(Material material) { - this.material = material; - } - - public Material getMaterial() { - if (material == null) return GTMaterials.Aluminium; - return material; - } - - @Override - public ItemStack getMainDrop(@NotNull BlockState state) { - return new ItemStack(getBlockType().asItem(), 1); + public @NotNull PipeMaterialBlock getBlockType() { + return (PipeMaterialBlock) super.getBlockType(); } @Override public int getDefaultPaintingColor() { - return GTUtil.convertRGBtoARGB(getMaterial().getMaterialRGB()); + return GTUtil.convertRGBtoARGB(getBlockType().material.getMaterialRGB()); } - @Override public @NotNull ModelData getModelData() { - return super.getModelData().derive().with(AbstractPipeModel.MATERIAL_PROPERTY, getMaterial()).build(); + return super.getModelData().derive().with(AbstractPipeModel.MATERIAL_PROPERTY, getBlockType().material).build(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java deleted file mode 100644 index b719f8deee..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeActivableBlockEntity.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; - -import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; - -import lombok.Getter; -import org.jetbrains.annotations.NotNull; - -public class PipeActivableBlockEntity extends PipeBlockEntity implements IActivable { - - private static final int PIPE_ACTIVE = 2; - - @Getter - private boolean active; - - public PipeActivableBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState); - } - - @Override - public void setActive(boolean active) { - if (this.active != active) { - this.active = active; - writeCustomData(PIPE_ACTIVE, buf -> buf.writeBoolean(active)); - markDirty(); - } - } - - @Override - public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { - super.receiveCustomData(discriminator, buf); - if (discriminator == PIPE_ACTIVE) { - boolean active = buf.readBoolean(); - if (this.active != active) { - this.active = active; - scheduleRenderUpdate(); - } - } - } - - @Override - public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { - buf.writeBoolean(active); - super.writeInitialSyncData(buf); - } - - @Override - public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { - active = buf.readBoolean(); - super.receiveInitialSyncData(buf); - } - - // do not save activeness to nbt, it should go away on world save & load. -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 8c75780f2f..f6eb4a6966 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -78,7 +78,6 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import lombok.Getter; -import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -123,7 +122,6 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity private int paintingColor = -1; @Getter - @Setter @DescSynced private @Nullable Material frameMaterial; @@ -133,11 +131,12 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity @Persisted @DescSynced @Getter - protected final PipeCoverHolder covers = new PipeCoverHolder(this); + protected final PipeCoverHolder coverHolder = new PipeCoverHolder(this); private final Object2ObjectOpenHashMap, IPipeCapabilityObject> capabilities = new Object2ObjectOpenHashMap<>(); private final Object2ObjectOpenCustomHashMap netCapabilities = WorldPipeNet .getSensitiveHashMap(); + @Getter @Nullable private TemperatureLogic temperatureLogic; @OnlyIn(Dist.CLIENT) @@ -167,16 +166,20 @@ public void getDrops(@NotNull List drops, @NotNull BlockState state) } @Override - public void clearRemoved() { - super.clearRemoved(); - if (getLevel() instanceof ServerLevel serverLevel) { - serverLevel.getServer().tell(new TickTask(0, this::scheduleRenderUpdate)); - } + public void scheduleRenderUpdate() { + super.scheduleRenderUpdate(); + requestModelDataUpdate(); } @Override - public void scheduleRenderUpdate() { - super.scheduleRenderUpdate(); + public boolean triggerEvent(int id, int type) { + if (id == 1) { // chunk re render + if (level != null && level.isClientSide) { + scheduleRenderUpdate(); + } + return true; + } + return false; } @Override @@ -218,12 +221,14 @@ public void setConnected(Direction facing, boolean renderClosed) { } else { this.renderMask &= ~(1 << facing.ordinal()); } + getLevel().setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FACINGS.get(facing), true)); } public void setDisconnected(Direction facing) { this.connectionMask &= ~(1 << facing.ordinal()); this.renderMask &= ~(1 << facing.ordinal()); updateActiveStatus(facing, false); + getLevel().setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FACINGS.get(facing), false)); } public boolean isConnected(Direction side) { @@ -242,16 +247,28 @@ public boolean renderClosed(Direction facing) { public void setBlocked(Direction facing) { this.blockedMask |= (byte) (1 << facing.ordinal()); + scheduleRenderUpdate(); } public void setUnblocked(Direction facing) { this.blockedMask &= (byte) ~(1 << facing.ordinal()); + scheduleRenderUpdate(); } public boolean isBlocked(Direction facing) { return (this.blockedMask & 1 << facing.ordinal()) > 0; } + public void setFrameMaterial(@Nullable Material frameMaterial) { + this.frameMaterial = frameMaterial; + if (frameMaterial != null) { + level.setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FRAMED, true)); + } else { + level.setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FRAMED, false)); + } + scheduleRenderUpdate(); + } + // paint // public int getPaintingColor() { @@ -263,6 +280,7 @@ public void setPaintingColor(int paintingColor, boolean alphaSensitive) { paintingColor |= 0xFF000000; } this.paintingColor = paintingColor; + scheduleRenderUpdate(); } public boolean isPainted() { @@ -324,14 +342,18 @@ public final void serverTick() { @Override public void onLoad() { super.onLoad(); - initialize(); + if (getLevel() instanceof ServerLevel serverLevel) { + serverLevel.getServer().tell(new TickTask(0, this::initialize)); + } } // activeness // @Override - public void onNeighborChanged(@NotNull Direction facing) { - super.onNeighborChanged(facing); + public void onNeighborChanged(Block fromBlock, BlockPos fromPos, boolean isMoving) { + super.onNeighborChanged(fromBlock, fromPos, isMoving); + Direction facing = GTUtil.getFacingToNeighbor(this.getBlockPos(), fromPos); + coverHolder.onNeighborChanged(fromBlock, fromPos, isMoving); updateActiveStatus(facing, false); } @@ -367,11 +389,6 @@ public PipeCapabilityWrapper getWrapperForNode(WorldPipeNetNode node) { return netCapabilities.get(node); } - @Override - public @NotNull PipeCoverHolder getCoverHolder() { - return covers; - } - /** * Updates the pipe's active status based on the tile entity connected to the side. * @@ -436,7 +453,7 @@ public LazyOptional getCapabilityCoverQuery(@NotNull Capability capabi @Override public LazyOptional getCapability(@NotNull Capability capability, @Nullable Direction facing) { if (capability == GTCapability.CAPABILITY_COVERABLE) { - return GTCapability.CAPABILITY_COVERABLE.orEmpty(capability, LazyOptional.of(this::getCovers)); + return GTCapability.CAPABILITY_COVERABLE.orEmpty(capability, LazyOptional.of(this::getCoverHolder)); } LazyOptional pipeCapability; IPipeCapabilityObject object = capabilities.get(capability); @@ -522,8 +539,8 @@ protected void initialize() { @Override public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { buf.writeVarInt(netLogicDatas.size()); - for (var entry : netLogicDatas.entrySet()) { - buf.writeVarInt(entry.getKey()); + for (var entry : netLogicDatas.int2ObjectEntrySet()) { + buf.writeVarInt(entry.getIntKey()); entry.getValue().encode(buf); } } @@ -570,7 +587,11 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { NetLogicEntry entry = data.getLogicEntryNullable(identifier); if (entry != null) entry.decode(buf, false); data.markLogicEntryAsUpdated(entry, false); - } else return; + } else { + // FIXME fix the issue that causes 4 bytes from the server to not be read correctly. + buf.readerIndex(buf.writerIndex()); + return; + } } if (identifier.equals(TemperatureLogic.INSTANCE.getSerializedName())) { TemperatureLogic tempLogic = this.netLogicDatas.get(networkID) @@ -580,6 +601,8 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { } } } + // FIXME fix the issue that causes 4 bytes from the server to not be read correctly. + buf.readerIndex(buf.writerIndex()); } // particle // @@ -599,10 +622,6 @@ public void updateTemperatureLogic(@NotNull TemperatureLogic logic) { } } - public @Nullable TemperatureLogic getTemperatureLogic() { - return temperatureLogic; - } - @OnlyIn(Dist.CLIENT) public void killOverheatParticle() { if (overheatParticle != null) { @@ -642,20 +661,17 @@ public void scheduleNeighborShapeUpdate() { level.getBlockState(pos).updateNeighbourShapes(level, pos, Block.UPDATE_ALL); } - @SuppressWarnings("ConstantConditions") // yes this CAN actually be null - public void markDirty() { - if (getLevel() != null && getBlockPos() != null) { - getLevel().setBlocksDirty(getBlockPos(), this.getBlockState(), this.getBlockState()); - } - } - @Override + @SuppressWarnings("ConstantConditions") // yes this CAN actually be null public void markAsDirty() { - markDirty(); + if (hasLevel()) { + level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_KNOWN_SHAPE); + } // this most notably gets called when the covers of a pipe get updated, aka the edge predicates need syncing. for (var node : this.netCapabilities.keySet()) { node.getNet().updatePredication(node, this); } + this.setChanged(); } public static @Nullable PipeBlockEntity getTileNoLoading(BlockPos pos, ResourceKey dimension) { @@ -737,13 +753,14 @@ public boolean shouldRenderGrid(Player player, BlockPos pos, BlockState state, I Set toolTypes) { if (toolTypes.contains(getBlockType().getToolClass()) || toolTypes.contains(GTToolType.SCREWDRIVER)) return true; - for (CoverBehavior cover : covers.getCovers()) { + for (CoverBehavior cover : coverHolder.getCovers()) { if (cover.shouldRenderGrid(player, pos, state, held, toolTypes)) return true; } return false; } - public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, Set toolTypes, Direction side) { + public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, Set toolTypes, + Direction side) { if (toolTypes.contains(getBlockType().getToolClass())) { if (player.isShiftKeyDown() && this.getBlockType().allowsBlocking()) { return getStructure().getPipeTexture(isBlocked(side)); @@ -751,7 +768,7 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, S return getStructure().getPipeTexture(isConnected(side)); } } - var cover = covers.getCoverAtSide(side); + var cover = coverHolder.getCoverAtSide(side); if (cover != null) { return cover.sideTips(player, pos, state, toolTypes, side); } @@ -769,7 +786,7 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, S var hitResult = new BlockHitResult(context.getClickLocation(), context.getClickedFace(), context.getClickedPos(), false); Direction gridSide = ICoverable.determineGridSideHit(hitResult); - CoverBehavior coverBehavior = gridSide == null ? null : covers.getCoverAtSide(gridSide); + CoverBehavior coverBehavior = gridSide == null ? null : coverHolder.getCoverAtSide(gridSide); if (gridSide == null) gridSide = hitResult.getDirection(); // Prioritize covers where they apply (Screwdriver, Soft Mallet) @@ -785,16 +802,16 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, S if (playerIn.isShiftKeyDown() && this.getBlockType().allowsBlocking()) { boolean isBlocked = this.isBlocked(gridSide); if (isBlocked) { - this.setUnblocked(gridSide); + PipeBlock.unblockTile(this, this.getPipeNeighbor(gridSide, true), gridSide); } else { - this.setBlocked(gridSide); + PipeBlock.blockTile(this, this.getPipeNeighbor(gridSide, true), gridSide); } } else { boolean isOpen = this.isConnected(gridSide); if (isOpen) { - this.setDisconnected(gridSide); + PipeBlock.disconnectTile(this, this.getPipeNeighbor(gridSide, true), gridSide); } else { - this.setConnected(gridSide, true); + PipeBlock.connectTile(this, this.getPipeNeighbor(gridSide, true), gridSide); } } playerIn.swing(hand); @@ -802,7 +819,7 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, S } else if (toolTypes.contains(GTToolType.CROWBAR)) { if (coverBehavior != null) { if (isServerSide()) { - covers.removeCover(gridSide, playerIn); + coverHolder.removeCover(gridSide, playerIn); playerIn.swing(hand); return Pair.of(GTToolType.CROWBAR, InteractionResult.CONSUME); } @@ -826,7 +843,9 @@ public ManagedFieldHolder getFieldHolder() { } @Override - public void onChanged() {} + public void onChanged() { + this.markAsDirty(); + } @Override public IManagedStorage getRootStorage() { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java index 49e36a9b7a..ef71ea2888 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java @@ -3,10 +3,8 @@ import com.gregtechceu.gtceu.api.cover.filter.Filter; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; -import com.gregtechceu.gtceu.common.cover.filter.BaseFilterContainer; import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.item.ItemStack; import lombok.Setter; import org.jetbrains.annotations.NotNull; @@ -64,23 +62,6 @@ public boolean test(IPredicateTestObject object) { return targetFilter == null || targetFilter.testGeneric(test); } - private static class GenericFilterContainer extends BaseFilterContainer { - - protected GenericFilterContainer() { - super(() -> {}); - } - - @Override - protected boolean isItemValid(ItemStack stack) { - return true; - } - - @Override - protected String getFilterName() { - return ""; - } - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java index 18a2724ff4..c21aa4db0d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java @@ -6,13 +6,10 @@ import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; -import com.gregtechceu.gtceu.api.graphnet.graph.NetDirectedGraph; -import com.gregtechceu.gtceu.api.graphnet.graph.NetUndirectedGraph; import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; import net.minecraft.core.GlobalPos; import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.saveddata.SavedData; import org.jetbrains.annotations.NotNull; @@ -28,19 +25,18 @@ public abstract class ServerNet extends SavedData implements IGraphNet { protected final GraphNetBacker backer; -// USERS: ADD THESE METHODS TO YOUR CLASS -// public static ServerNet get(ServerLevel level, Function graphBuilder, -// AlgorithmBuilder... algorithmBuilder) { -// return level.getDataStorage().computeIfAbsent(tag -> new ServerNet(tag, graphBuilder, algorithmBuilder), () -> -// new ServerNet(graphBuilder, algorithmBuilder), name); -// } -// -// public static ServerNet get(ServerLevel level, boolean directed, AlgorithmBuilder... -// algorithmBuilders) { -// return get(level, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), -// algorithmBuilders); -// } - + // USERS: ADD THESE METHODS TO YOUR CLASS + // public static ServerNet get(ServerLevel level, Function graphBuilder, + // AlgorithmBuilder... algorithmBuilder) { + // return level.getDataStorage().computeIfAbsent(tag -> new ServerNet(tag, graphBuilder, algorithmBuilder), () -> + // new ServerNet(graphBuilder, algorithmBuilder), name); + // } + // + // public static ServerNet get(ServerLevel level, boolean directed, AlgorithmBuilder... + // algorithmBuilders) { + // return get(level, directed ? NetDirectedGraph.standardBuilder() : NetUndirectedGraph.standardBuilder(), + // algorithmBuilders); + // } public ServerNet(Function graphBuilder, AlgorithmBuilder... algorithmBuilders) { this.backer = new GraphNetBacker(this, graphBuilder.apply(this), algorithmBuilders); diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java index b4a20311d4..cf126d3b34 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java @@ -21,6 +21,7 @@ import org.jetbrains.annotations.Nullable; import javax.annotation.ParametersAreNonnullByDefault; +import java.nio.channels.Pipe; /** * @author KilaBash @@ -59,7 +60,7 @@ protected boolean placeBlock(BlockPlaceContext context, BlockState state) { if (block instanceof PipeBlock pipeBlock) { PipeBlockEntity pipeTile = pipeBlock.getBlockEntity(level, possiblePipe); if (pipeTile != null && pipeTile.canConnectTo(side.getOpposite())) { - pipeTile.setConnected(side, true); + PipeBlock.connectTile(pipeTile, null, side); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java index 1df7fcab96..b63df22011 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java @@ -22,6 +22,8 @@ import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.TickTask; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.shapes.VoxelShape; @@ -82,8 +84,12 @@ public void onChanged() { @Override public void onLoad() { ICoverable.super.onLoad(); - for (Direction side : GTUtil.DIRECTIONS) { - this.sidedRedstoneInput[side.get3DDataValue()] = GTUtil.getRedstonePower(getLevel(), getPos(), side); + if (getLevel() instanceof ServerLevel serverLevel) { + serverLevel.getServer().tell(new TickTask(0, () -> { + for (Direction side : GTUtil.DIRECTIONS) { + this.sidedRedstoneInput[side.get3DDataValue()] = GTUtil.getRedstonePower(getLevel(), getPos(), side); + } + })); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java index 0ec81af238..edb14f72a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java @@ -5,6 +5,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.client.renderer.GTRenderTypes; +import com.gregtechceu.gtceu.client.renderer.IRenderSetup; import com.gregtechceu.gtceu.client.util.BloomUtils; import com.gregtechceu.gtceu.client.util.DrawUtil; import com.gregtechceu.gtceu.client.util.EffectRenderContext; @@ -12,16 +13,19 @@ import com.lowdragmc.lowdraglib.Platform; -import net.minecraft.client.renderer.MultiBufferSource; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.*; +import lombok.Setter; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; @@ -146,6 +150,7 @@ public static int getBlackBodyColor(int temperature) { } private final PipeBlockEntity tileEntity; + @Setter private @NotNull TemperatureLogic temperatureLogic; protected VoxelShape pipeBoxes; @@ -178,10 +183,6 @@ public void updatePipeBoxes(@NotNull VoxelShape pipeBoxes) { .optimize(); } - public void setTemperatureLogic(@NotNull TemperatureLogic logic) { - this.temperatureLogic = logic; - } - @Override public void onUpdate() { if (tileEntity.isRemoved() || !tileEntity.isOverheatParticleAlive()) { @@ -232,23 +233,53 @@ public String toString() { '}'; } + @Nullable + @Override + public IRenderSetup getRenderSetup() { + return SETUP; + } + @Override - public void renderParticle(@NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) { + public void renderParticle(@NotNull PoseStack poseStack, @NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) { + if (insulated) { + return; + } + if (GTCEu.isShimmerLoaded()) { - BloomUtils.entityBloom(source -> renderBloomEffect(source, context)); + BloomUtils.entityBloom(source -> renderBloomEffect(poseStack, source.getBuffer(GTRenderTypes.getBloomQuad()), context)); + } else { + renderBloomEffect(poseStack, buffer, context); } } - public void renderBloomEffect(@NotNull MultiBufferSource source, @NotNull EffectRenderContext context) { + public void renderBloomEffect(@NotNull PoseStack poseStack, @NotNull VertexConsumer buffer, @NotNull EffectRenderContext context) { float red = ((color >> 16) & 0xFF) / 255f; float green = ((color >> 8) & 0xFF) / 255f; float blue = (color & 0xFF) / 255f; - VertexConsumer buffer = source.getBuffer(GTRenderTypes.getBloomQuad()); - - // buffer.setTranslation(posX - context.cameraX(), posY - context.cameraY(), posZ - context.cameraZ()); + poseStack.pushPose(); + poseStack.translate(posX - context.cameraX(), posY - context.cameraY(), posZ - context.cameraZ()); for (AABB cuboid : pipeBoxes.toAabbs()) { + cuboid.inflate(0.01); RenderBufferHelper.renderCubeFace(buffer, cuboid, red, green, blue, alpha, true); } + poseStack.popPose(); } + private static final IRenderSetup SETUP = new IRenderSetup() { + + @Override + @OnlyIn(Dist.CLIENT) + public void preDraw(@NotNull BufferBuilder buffer) { + RenderSystem.setShaderColor(1, 1, 1, 1); + RenderSystem.enableBlend(); + buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + } + + @Override + @OnlyIn(Dist.CLIENT) + public void postDraw(@NotNull BufferBuilder buffer) { + Tesselator.getInstance().end(); + RenderSystem.disableBlend(); + } + }; } diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java index 493c153174..b748880a9d 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.client.renderer.IRenderSetup; import com.gregtechceu.gtceu.client.util.EffectRenderContext; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -38,6 +39,7 @@ public abstract class GTParticle { @Getter private double squaredRenderRange = -1; + @Getter private boolean expired; protected GTParticle(double posX, double posY, double posZ) { @@ -56,10 +58,6 @@ public final boolean isAlive() { return !expired; } - public final boolean isExpired() { - return expired; - } - public final void setExpired() { if (this.expired) return; this.expired = true; @@ -69,8 +67,7 @@ public final void setExpired() { /** * @return {@code true} to render the particle with * {@link com.mojang.blaze3d.systems.RenderSystem#depthMask(boolean) depth mask} feature disabled; in - * other - * words, render the particle without modifying depth buffer. + * other words, render the particle without modifying depth buffer. */ public boolean shouldDisableDepth() { return false; @@ -104,10 +101,11 @@ protected void onExpired() {} * called between a {@link IRenderSetup#preDraw(BufferBuilder)} call and a * {@link IRenderSetup#postDraw(BufferBuilder)} call. * - * @param buffer buffer builder - * @param context render context + * @param poseStack + * @param buffer buffer builder + * @param context render context */ - public void renderParticle(@NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) {} + public void renderParticle(@NotNull PoseStack poseStack, @NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) {} /** * @return Render setup for this particle, if exists diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java index e0b3ab0adc..f2d636086b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java @@ -4,9 +4,12 @@ import com.gregtechceu.gtceu.client.renderer.IRenderSetup; import com.gregtechceu.gtceu.client.util.EffectRenderContext; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.ChatFormatting; +import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; import net.minecraftforge.api.distmarker.Dist; @@ -31,7 +34,7 @@ * Singleton class responsible for managing, updating and rendering {@link GTParticle} instances. */ @OnlyIn(Dist.CLIENT) -@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = GTCEu.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE) +@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = GTCEu.MOD_ID) public class GTParticleManager { public static final GTParticleManager INSTANCE = new GTParticleManager(); @@ -83,7 +86,7 @@ private void updateQueue(Map> renderQueue) try { particle.onUpdate(); } catch (RuntimeException exception) { - GTCEu.LOGGER.error("particle update error: {}", particle.toString(), exception); + GTCEu.LOGGER.error("particle update error: {}", particle, exception); particle.setExpired(); } if (particle.isAlive()) continue; @@ -118,10 +121,10 @@ public void clearAllEffects(boolean cleanNewQueue) { depthDisabledParticles.clear(); } - public void renderParticles(@NotNull Entity renderViewEntity, float partialTicks) { + public void renderParticles(@NotNull PoseStack poseStack, @NotNull Entity renderViewEntity, Camera camera, Frustum frustum, float partialTicks) { if (depthEnabledParticles.isEmpty() && depthDisabledParticles.isEmpty()) return; - EffectRenderContext instance = EffectRenderContext.getInstance().update(renderViewEntity, partialTicks); + EffectRenderContext instance = EffectRenderContext.getInstance().update(renderViewEntity, camera, frustum, partialTicks); RenderSystem.enableBlend(); RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); @@ -129,17 +132,17 @@ public void renderParticles(@NotNull Entity renderViewEntity, float partialTicks if (!depthDisabledParticles.isEmpty()) { RenderSystem.depthMask(false); - renderGlParticlesInLayer(depthDisabledParticles, instance); + renderGlParticlesInLayer(poseStack, depthDisabledParticles, instance); RenderSystem.depthMask(true); } - renderGlParticlesInLayer(depthEnabledParticles, instance); + renderGlParticlesInLayer(poseStack, depthEnabledParticles, instance); RenderSystem.disableBlend(); } - private static void renderGlParticlesInLayer(@NotNull Map<@Nullable IRenderSetup, ArrayDeque> renderQueue, + private static void renderGlParticlesInLayer(@NotNull PoseStack poseStack, @NotNull Map<@Nullable IRenderSetup, ArrayDeque> renderQueue, @NotNull EffectRenderContext context) { for (var e : renderQueue.entrySet()) { @Nullable @@ -158,7 +161,7 @@ private static void renderGlParticlesInLayer(@NotNull Map<@Nullable IRenderSetup handler.preDraw(buffer); } } - particle.renderParticle(buffer, context); + particle.renderParticle(poseStack, buffer, context); } catch (Throwable throwable) { GTCEu.LOGGER.error("particle render error: {}", particle, throwable); particle.setExpired(); @@ -192,7 +195,7 @@ public static void clientTick(TickEvent.ClientTickEvent event) { public static void renderWorld(RenderLevelStageEvent event) { if (event.getStage() == RenderLevelStageEvent.Stage.AFTER_LEVEL) { Entity entity = Minecraft.getInstance().getCameraEntity(); - INSTANCE.renderParticles(entity == null ? Minecraft.getInstance().player : entity, event.getPartialTick()); + INSTANCE.renderParticles(event.getPoseStack(), entity == null ? Minecraft.getInstance().player : entity, event.getCamera(), event.getFrustum(), event.getPartialTick()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index 5d202e5982..059d9d0021 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -169,7 +169,7 @@ public TextureAtlasSprite getParticleTexture(int paintColor, @Nullable Material @Override public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { - return getParticleTexture(data.get(COLOR_PROPERTY), data.get(MATERIAL_PROPERTY)); + return getParticleTexture(safeInt(data.get(COLOR_PROPERTY)), data.get(MATERIAL_PROPERTY)); } public abstract SpriteInformation getParticleSprite(@Nullable Material material); @@ -204,7 +204,7 @@ public TextureAtlasSprite getParticleIcon() { @Override public @NotNull ItemOverrides getOverrides() { - return FakeItemOverrideList.INSTANCE; + return FakeItemOverrides.INSTANCE; } @Override @@ -213,9 +213,9 @@ public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull Ran return ChunkRenderTypeSet.of(RenderType.cutoutMipped()); } - protected static class FakeItemOverrideList extends ItemOverrides { + protected static class FakeItemOverrides extends ItemOverrides { - public static final FakeItemOverrideList INSTANCE = new FakeItemOverrideList(); + public static final FakeItemOverrides INSTANCE = new FakeItemOverrides(); @Nullable @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java index e6304ad4a7..241f1a1050 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -44,21 +44,22 @@ public class ActivablePipeModel extends AbstractPipeModel { public static final ModelProperty ACTIVE_PROPERTY = new ModelProperty<>(); public static final ActivablePipeModel OPTICAL = new ActivablePipeModel( - () -> GTCEu.id("block/pipe/pipe_optical_in"), - () -> GTCEu.id("block/pipe/pipe_optical_side"), - () -> GTCEu.id("block/pipe/pipe_optical_side_overlay"), - () -> GTCEu.id("block/pipe/pipe_optical_side_overlay_active"), + GTCEu.id("block/pipe/pipe_optical_in"), + GTCEu.id("block/pipe/pipe_optical_side"), + GTCEu.id("block/pipe/pipe_optical_side_overlay"), + GTCEu.id("block/pipe/pipe_optical_side_overlay_active"), false, "optical"); - public static final ActivablePipeModel LASER = new ActivablePipeModel(() -> GTCEu.id("block/pipe/pipe_laser_in"), - () -> GTCEu.id("block/pipe/pipe_laser_side"), - () -> GTCEu.id("block/pipe/pipe_laser_side_overlay"), - () -> GTCEu.id("block/pipe/pipe_laser_side_overlay_emissive"), + public static final ActivablePipeModel LASER = new ActivablePipeModel( + GTCEu.id("block/pipe/pipe_laser_in"), + GTCEu.id("block/pipe/pipe_laser_side"), + GTCEu.id("block/pipe/pipe_laser_side_overlay"), + GTCEu.id("block/pipe/pipe_laser_side_overlay_emissive"), true, "laser"); - private final SupplierMemoizer.MemoizedSupplier inTex; - private final SupplierMemoizer.MemoizedSupplier sideTex; - private final SupplierMemoizer.MemoizedSupplier overlayTex; - private final SupplierMemoizer.MemoizedSupplier overlayActiveTex; + private final ResourceLocation inTex; + private final ResourceLocation sideTex; + private final ResourceLocation overlayTex; + private final ResourceLocation overlayActiveTex; private SpriteInformation inSprite; private SpriteInformation sideSprite; @@ -67,15 +68,16 @@ public class ActivablePipeModel extends AbstractPipeModel { private final boolean emissiveActive; - public ActivablePipeModel(@NotNull Supplier inTex, @NotNull Supplier sideTex, - @NotNull Supplier overlayTex, - @NotNull Supplier overlayActiveTex, boolean emissiveActive, + public ActivablePipeModel(@NotNull ResourceLocation inTex, + @NotNull ResourceLocation sideTex, + @NotNull ResourceLocation overlayTex, + @NotNull ResourceLocation overlayActiveTex, boolean emissiveActive, String variant) { super(new ModelResourceLocation(loc, variant)); - this.inTex = SupplierMemoizer.memoize(inTex); - this.sideTex = SupplierMemoizer.memoize(sideTex); - this.overlayTex = SupplierMemoizer.memoize(overlayTex); - this.overlayActiveTex = SupplierMemoizer.memoize(overlayActiveTex); + this.inTex = inTex; + this.sideTex = sideTex; + this.overlayTex = overlayTex; + this.overlayActiveTex = overlayActiveTex; this.emissiveActive = emissiveActive; } @@ -83,7 +85,6 @@ public ActivablePipeModel(@NotNull Supplier inTex, @NotNull Su public @NotNull List getQuads(ActivableCacheKey key, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, @Nullable Material frameMaterial, byte frameMask, byte coverMask) { - // don't render the main shape to the bloom layer List quads = super.getQuads(key, connectionMask, closedMask, blockedMask, data, frameMaterial, frameMask, coverMask); @@ -114,17 +115,17 @@ public SpriteInformation getParticleSprite(@Nullable Material material) { @Override protected StructureQuadCache constructForKey(ActivableCacheKey key) { - if (inSprite == null && inTex != null) { - inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex.get()), -1); + if (inSprite == null) { + inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex), -1); } - if (sideSprite == null && sideTex != null) { - sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex.get()), -1); + if (sideSprite == null) { + sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex), -1); } - if (overlaySprite == null && overlayTex != null) { - overlaySprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayTex.get()), 0); + if (overlaySprite == null) { + overlaySprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayTex), 0); } - if (overlayActiveSprite == null && overlayActiveTex != null) { - overlayActiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayActiveTex.get()), 0); + if (overlayActiveSprite == null) { + overlayActiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayActiveTex), 0); } return ActivableSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, sideSprite, diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java index bd37c41782..67c1ec7ce3 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java @@ -2,9 +2,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconSet; -import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.client.renderer.pipe.cache.ExtraCappedSQC; @@ -14,25 +12,22 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; -import com.gregtechceu.gtceu.utils.SupplierMemoizer; import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.block.model.ItemOverrides; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.model.data.ModelData; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.function.BiConsumer; -import java.util.function.Supplier; public class CableModel extends AbstractPipeModel { @@ -40,41 +35,37 @@ public class CableModel extends AbstractPipeModel { private static final ResourceLocation loc = GTCEu.id("pipe_cable"); + public static final ResourceLocation WIRE = GTCEu.id("block/cable/wire"); + public static final ResourceLocation INSULATION_FULL = GTCEu.id("block/cable/insulation_5"); + public static final CableModel INSTANCE = new CableModel("wire"); public static final CableModel[] INSULATED_INSTANCES = new CableModel[5]; - @OnlyIn(Dist.CLIENT) - public static final Supplier WIRE = () -> MaterialIconType.wire - .getBlockTexturePath(MaterialIconSet.DULL, true).withSuffix("_side"); - @OnlyIn(Dist.CLIENT) - public static final Supplier INSULATION_FULL = () -> GTCEu.id("block/cable/insulation_5"); - static { for (int i = 0; i < INSULATED_INSTANCES.length; i++) { - final int finalI = i; - INSULATED_INSTANCES[i] = new CableModel(() -> GTCEu.id("block/cable/insulation_%s".formatted(finalI)), + INSULATED_INSTANCES[i] = new CableModel(GTCEu.id("block/cable/insulation_%s".formatted(i)), INSULATION_FULL, "insulated_" + i); } } - private final SupplierMemoizer.MemoizedSupplier wireTex; - private final SupplierMemoizer.MemoizedSupplier insulationTex; - private final SupplierMemoizer.MemoizedSupplier fullInsulationTex; + private final ResourceLocation wireTex; + private final ResourceLocation insulationTex; + private final ResourceLocation fullInsulationTex; private SpriteInformation wireSprite; private SpriteInformation insulationSprite; private SpriteInformation fullInsulationSprite; - public CableModel(@NotNull Supplier wireTex, @Nullable Supplier insulationTex, - @Nullable Supplier fullInsulationTex, String variant) { + public CableModel(@NotNull ResourceLocation wireTex, @Nullable ResourceLocation insulationTex, + @Nullable ResourceLocation fullInsulationTex, String variant) { super(new ModelResourceLocation(loc, variant)); - this.wireTex = SupplierMemoizer.memoize(wireTex); - this.insulationTex = SupplierMemoizer.memoize(insulationTex); - this.fullInsulationTex = SupplierMemoizer.memoize(fullInsulationTex); + this.wireTex = wireTex; + this.insulationTex = insulationTex; + this.fullInsulationTex = fullInsulationTex; } - public CableModel(@Nullable Supplier insulationTex, - @Nullable Supplier fullInsulationTex, String variant) { + public CableModel(@Nullable ResourceLocation insulationTex, + @Nullable ResourceLocation fullInsulationTex, String variant) { this(WIRE, insulationTex, fullInsulationTex, variant); } @@ -111,13 +102,13 @@ public SpriteInformation getParticleSprite(@Nullable Material material) { @Override protected StructureQuadCache constructForKey(CacheKey key) { if (fullInsulationSprite == null && fullInsulationTex != null) { - fullInsulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(fullInsulationTex.get()), 1); + fullInsulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(fullInsulationTex), 1); } if (insulationSprite == null && insulationTex != null) { - insulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(insulationTex.get()), 1); + insulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(insulationTex), 1); } if (wireSprite == null && wireTex != null) { - wireSprite = new SpriteInformation(ModelFactory.getBlockSprite(wireTex.get()), 0); + wireSprite = new SpriteInformation(ModelFactory.getBlockSprite(wireTex), 0); } SpriteInformation sideTex = fullInsulationSprite != null ? fullInsulationSprite : wireSprite; @@ -134,7 +125,7 @@ protected StructureQuadCache constructForKey(CacheKey key) { LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; - Material mater = block instanceof MaterialPipeBlock mat ? mat.material : null; + Material mater = block instanceof PipeMaterialBlock mat ? mat.material : null; return new PipeItemModel<>(this, new CacheKey(block.getStructure().getRenderThickness()), new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : PipeBlockEntity.DEFAULT_COLOR, DEFAULT_INSULATION_COLOR)); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java index 233ee2cbae..de2f7d3dfd 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -3,7 +3,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.client.renderer.pipe.cache.BlockableSQC; @@ -43,13 +43,13 @@ public class PipeModel extends AbstractPipeModel { public static final PipeModel[] RESTRICTIVE_INSTANCES = new PipeModel[INSTANCES.length]; static { - model(0, wood -> GTCEu.id("blocks/pipe/pipe_tiny_in")); - model(1, wood -> wood ? GTCEu.id("blocks/pipe/pipe_small_in_wood") : GTCEu.id("blocks/pipe/pipe_small_in")); - model(2, wood -> wood ? GTCEu.id("blocks/pipe/pipe_normal_in_wood") : GTCEu.id("blocks/pipe/pipe_normal_in")); - model(3, wood -> wood ? GTCEu.id("blocks/pipe/pipe_large_in_wood") : GTCEu.id("blocks/pipe/pipe_large_in")); - model(4, wood -> GTCEu.id("blocks/pipe/pipe_huge_in")); - model(5, wood -> GTCEu.id("blocks/pipe/pipe_quadruple_in")); - model(6, wood -> GTCEu.id("blocks/pipe/pipe_nonuple_in")); + model(0, wood -> GTCEu.id("block/pipe/pipe_tiny_in")); + model(1, wood -> wood ? GTCEu.id("block/pipe/pipe_small_in_wood") : GTCEu.id("block/pipe/pipe_small_in")); + model(2, wood -> wood ? GTCEu.id("block/pipe/pipe_normal_in_wood") : GTCEu.id("block/pipe/pipe_normal_in")); + model(3, wood -> wood ? GTCEu.id("block/pipe/pipe_large_in_wood") : GTCEu.id("block/pipe/pipe_large_in")); + model(4, wood -> GTCEu.id("block/pipe/pipe_huge_in")); + model(5, wood -> GTCEu.id("block/pipe/pipe_quadruple_in")); + model(6, wood -> GTCEu.id("block/pipe/pipe_nonuple_in")); } private static void model(int i, PipeSpriteWoodClarifier clarifier) { @@ -79,8 +79,8 @@ public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, @NotNull PipeSpriteWood public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, @NotNull PipeSpriteWoodClarifier sideTex, boolean restrictive, String variant) { - this(inTex, sideTex, restrictive ? wood -> GTCEu.id("blocks/pipe/pipe_restrictive") : null, - wood -> GTCEu.id("blocks/pipe/pipe_blocked"), variant); + this(inTex, sideTex, restrictive ? wood -> GTCEu.id("block/pipe/pipe_restrictive") : null, + wood -> GTCEu.id("block/pipe/pipe_blocked"), variant); } public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, boolean restrictive, String variant) { @@ -98,10 +98,6 @@ public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { return getParticleSprite(null).sprite(); } - public @NotNull TextureAtlasSprite getParticleTexture(Material material) { - return sideSprite.sprite(); - } - @Override protected @NotNull WoodCacheKey toKey(@NotNull ModelData state) { return WoodCacheKey.of(state.get(THICKNESS_PROPERTY), state.get(MATERIAL_PROPERTY)); @@ -139,7 +135,7 @@ protected StructureQuadCache constructForKey(WoodCacheKey key) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; Material mater = null; - boolean wood = block instanceof MaterialPipeBlock mat && (mater = mat.material) != null && + boolean wood = block instanceof PipeMaterialBlock mat && (mater = mat.material) != null && mater.hasProperty(PropertyKey.WOOD); return new PipeItemModel<>(this, new WoodCacheKey(block.getStructure().getRenderThickness(), wood), new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java index cce7a599e3..1470421436 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java @@ -23,7 +23,6 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; @@ -88,7 +87,7 @@ protected static SubListAddress buildPlates(List quads, Di int start = quads.size(); Pair box = PLATE_BOXES.get(facing); for (Direction dir : Direction.values()) { - quads.add(QuadHelper.buildQuad(dir, box, mapper, sprite, DefaultVertexFormat.BLOCK)); + quads.add(QuadHelper.buildQuad(dir, box, mapper, sprite)); } return new SubListAddress(start, quads.size()); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java index f4e3a5e288..b8227c8ffa 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -8,7 +8,6 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Contract; @@ -136,7 +135,7 @@ public RecolorableBakedQuad visitCapper(Direction facing, int overlayLayer) { } public RecolorableBakedQuad visitQuad(Direction normal, Pair box, UVMapper uv) { - return QuadHelper.buildQuad(normal, box, uv, targetSprite, DefaultVertexFormat.BLOCK); + return QuadHelper.buildQuad(normal, box, uv, targetSprite); } public static List createFrame(TextureAtlasSprite sprite) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java index 33b5bebd71..bee31876be 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -5,7 +5,6 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.BlockElementFace; -import net.minecraft.client.renderer.block.model.FaceBakery; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.BlockModelRotation; import net.minecraft.core.Direction; @@ -13,9 +12,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; +import net.minecraftforge.client.model.ForgeFaceData; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Contract; @@ -23,27 +20,17 @@ import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - @OnlyIn(Dist.CLIENT) public final class QuadHelper { - private static final FaceBakery BAKERY = new FaceBakery(); - private QuadHelper() {} public static RecolorableBakedQuad buildQuad(Direction normal, Pair box, - UVMapper uv, SpriteInformation targetSprite, - VertexFormat format) { + UVMapper uv, SpriteInformation targetSprite) { BlockElementFace face = new BlockElementFace(null, -1, targetSprite.sprite().contents().name().toString(), - uv.map(normal, box)); - BakedQuad quad = StaticFaceBakery.bakeQuad(box.getLeft(), box.getRight(), face, targetSprite.sprite(), normal, - BlockModelRotation.X0_Y0, null, false, 15); - RecolorableBakedQuad.Builder builder = new RecolorableBakedQuad.Builder(format); - builder.setTexture(targetSprite); - putBakedQuad(builder, quad); - return builder.build(); + uv.map(normal, box), ForgeFaceData.DEFAULT); + return StaticFaceBakery.bakeRecolorableQuad(box.getLeft(), box.getRight(), face, targetSprite, normal, + BlockModelRotation.X0_Y0, null, true, 0); } public static BakedQuad buildQuad(Direction normal, Pair box, @@ -121,91 +108,4 @@ public static BakedQuad buildQuad(Direction normal, Pair box float z2, float g) { return toPair(x1 - g, y1 - g, z1 - g, x2 + g, y2 + g, z2 + g); } - - public static void putBakedQuad(RecolorableBakedQuad.Builder consumer, BakedQuad quad) { - consumer.setQuadOrientation(quad.getDirection()); - if (quad.isTinted()) { - consumer.setQuadTint(quad.getTintIndex()); - } - consumer.setShade(quad.isShade()); - int[] data = new int[4]; - VertexFormat formatFrom = consumer.getVertexFormat(); - VertexFormat formatTo = DefaultVertexFormat.BLOCK; - int countFrom = formatFrom.getElements().size(); - int countTo = formatTo.getElements().size(); - int[] eMap = mapFormats(formatFrom, formatTo); - for (int v = 0; v < 4; v++) { - for (int e = 0; e < countFrom; e++) { - if (eMap[e] != countTo) { - unpack(quad.getVertices(), data, formatTo, v, eMap[e]); - consumer.put(e, data); - } else { - consumer.put(e); - } - } - } - } - - private static final ConcurrentMap, int[]> formatMaps = new ConcurrentHashMap<>(); - - public static int[] mapFormats(VertexFormat from, VertexFormat to) { - return formatMaps.computeIfAbsent(Pair.of(from, to), pair -> generateMapping(pair.getLeft(), pair.getRight())); - } - - private static int[] generateMapping(VertexFormat from, VertexFormat to) { - int fromCount = from.getElements().size(); - int toCount = to.getElements().size(); - int[] eMap = new int[fromCount]; - - for (int e = 0; e < fromCount; e++) { - VertexFormatElement expected = from.getElements().get(e); - int e2; - for (e2 = 0; e2 < toCount; e2++) { - VertexFormatElement current = to.getElements().get(e2); - if (expected.getUsage() == current.getUsage() && expected.getIndex() == current.getIndex()) { - break; - } - } - eMap[e] = e2; - } - return eMap; - } - - public static void unpack(int[] from, int[] to, VertexFormat formatFrom, int v, int e) { - int length = 4 < to.length ? 4 : to.length; - VertexFormatElement element = formatFrom.getElements().get(e); - int vertexStart = v * formatFrom.getIntegerSize() + formatFrom.getOffset(e); - int count = element.getElementCount(); - VertexFormatElement.Type type = element.getType(); - int size = type.getSize(); - int mask = (256 << (8 * (size - 1))) - 1; - for (int i = 0; i < length; i++) { - if (i < count) { - int pos = vertexStart + size * i; - int index = pos >> 2; - int offset = pos & 3; - int bits = from[index]; - bits = bits >>> (offset * 8); - if ((pos + size - 1) / 4 != index) { - bits |= from[index + 1] << ((4 - offset) * 8); - } - bits &= mask; - if (type == VertexFormatElement.Type.FLOAT) { - to[i] = bits; - } else if (type == VertexFormatElement.Type.UBYTE || type == VertexFormatElement.Type.USHORT) { - to[i] = Float.floatToRawIntBits((float) bits / mask); - } else if (type == VertexFormatElement.Type.UINT) { - to[i] = Float.floatToRawIntBits((float) ((double) (bits & 0xFFFFFFFFL) / 0xFFFFFFFFL)); - } else if (type == VertexFormatElement.Type.BYTE) { - to[i] = Float.floatToRawIntBits(((float) (byte) bits) / (mask >> 1)); - } else if (type == VertexFormatElement.Type.SHORT) { - to[i] = Float.floatToRawIntBits(((float) (short) bits) / (mask >> 1)); - } else if (type == VertexFormatElement.Type.INT) { - to[i] = Float.floatToRawIntBits((float) ((double) (bits & 0xFFFFFFFFL) / (0xFFFFFFFFL >> 1))); - } - } else { - to[i] = 0; - } - } - } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java index e2333451d0..aaf4c78d4e 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; @@ -11,62 +12,35 @@ import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormatElement; import lombok.Getter; import lombok.Setter; +import lombok.experimental.Accessors; +import net.minecraftforge.client.model.QuadTransformers; import static net.minecraftforge.client.model.IQuadTransformer.*; +@MethodsReturnNonnullByDefault @OnlyIn(Dist.CLIENT) public class RecolorableBakedQuad extends BakedQuad { private final SpriteInformation spriteInformation; - private final VertexFormat format; public RecolorableBakedQuad(int[] unpackedData, int tint, Direction orientation, - SpriteInformation texture, boolean applyDiffuseLighting, boolean hasAmbientOcclusion, - VertexFormat format) { + SpriteInformation texture, boolean applyDiffuseLighting, boolean hasAmbientOcclusion) { super(unpackedData, tint, orientation, texture.sprite(), applyDiffuseLighting, hasAmbientOcclusion); this.spriteInformation = texture; - this.format = format; } - public RecolorableBakedQuad withColor(ColorData data) { + public BakedQuad withColor(ColorData data) { if (!spriteInformation.colorable()) return this; int argb = data.colorsARGB()[spriteInformation.colorID()]; - - int[] newData = new int[format.getIntegerSize() * 4]; - - float a = ((argb >> 24) & 0xFF) / 255f; // alpha - float r = ((argb >> 16) & 0xFF) / 255f; // red - float g = ((argb >> 8) & 0xFF) / 255f; // green - float b = ((argb) & 0xFF) / 255f; // blue - float[] array = new float[] { r, g, b, a }; - for (int v = 0; v < 4; v++) { - for (int e = 0; e < format.getElements().size(); e++) { - if (format.getElements().get(e).getUsage() == VertexFormatElement.Usage.COLOR) { - newData[v * format.getIntegerSize() + IQuadTransformer.COLOR] = argb; - } else { - int offset = findOffset(format.getElements().get(e)); - newData[v * format.getIntegerSize() + offset] = this.vertices[v * format.getIntegerSize() + offset]; - } - } - } - return new RecolorableBakedQuad(newData, this.tintIndex, this.direction, this.spriteInformation, - this.isShade(), this.hasAmbientOcclusion(), this.format); - } - - public static RecolorableBakedQuad.Builder of(BakedQuad quad, VertexFormat format) { - Builder builder = new Builder(format); - QuadHelper.putBakedQuad(builder, quad); - return builder; + return QuadTransformers.applyingColor(argb).process(this); } + @Accessors(chain = true) public static class Builder implements VertexConsumer { - @Getter - private final VertexFormat vertexFormat; private final int[] unpackedData; @Setter private int quadTint = -1; @@ -82,16 +56,16 @@ public static class Builder implements VertexConsumer { private int vertices = 0; private int elements = 0; private boolean full = false; + @Setter private boolean contractUVs = false; - public Builder(VertexFormat vertexFormat) { - this.vertexFormat = vertexFormat; - unpackedData = new int[vertexFormat.getIntegerSize() * 4]; + public Builder() { + unpackedData = new int[STRIDE * 4]; } @Override public VertexConsumer vertex(double x, double y, double z) { - int offset = vertices * vertexFormat.getIntegerSize() + POSITION; + int offset = vertices * STRIDE + POSITION; unpackedData[offset] = Float.floatToRawIntBits((float) x); unpackedData[offset + 1] = Float.floatToRawIntBits((float) y); unpackedData[offset + 2] = Float.floatToRawIntBits((float) z); @@ -101,7 +75,7 @@ public VertexConsumer vertex(double x, double y, double z) { @Override public VertexConsumer color(int red, int green, int blue, int alpha) { - int offset = vertices * vertexFormat.getIntegerSize() + COLOR; + int offset = vertices * STRIDE + COLOR; unpackedData[offset] = ((alpha & 0xFF) << 24) | ((blue & 0xFF) << 16) | ((green & 0xFF) << 8) | @@ -112,7 +86,7 @@ public VertexConsumer color(int red, int green, int blue, int alpha) { @Override public VertexConsumer uv(float u, float v) { - int offset = vertices * vertexFormat.getIntegerSize() + UV0; + int offset = vertices * STRIDE + UV0; unpackedData[offset] = Float.floatToRawIntBits(u); unpackedData[offset + 1] = Float.floatToRawIntBits(v); addElement(); @@ -122,7 +96,7 @@ public VertexConsumer uv(float u, float v) { @Override public VertexConsumer overlayCoords(int u, int v) { if (UV1 >= 0) { - int offset = vertices * vertexFormat.getIntegerSize() + UV1; + int offset = vertices * STRIDE + UV1; unpackedData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16); addElement(); } @@ -131,7 +105,7 @@ public VertexConsumer overlayCoords(int u, int v) { @Override public VertexConsumer uv2(int u, int v) { - int offset = vertices * vertexFormat.getIntegerSize() + UV2; + int offset = vertices * STRIDE + UV2; unpackedData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16); addElement(); return this; @@ -139,7 +113,7 @@ public VertexConsumer uv2(int u, int v) { @Override public VertexConsumer normal(float x, float y, float z) { - int offset = vertices * vertexFormat.getIntegerSize() + NORMAL; + int offset = vertices * STRIDE + NORMAL; unpackedData[offset] = ((int) (x * 127.0f) & 0xFF) | (((int) (y * 127.0f) & 0xFF) << 8) | (((int) (z * 127.0f) & 0xFF) << 16); @@ -159,9 +133,9 @@ public void unsetDefaultColor() {} public void put(int element, int... data) { for (int i = 0; i < 4; i++) { if (i < data.length) { - unpackedData[vertices * vertexFormat.getIntegerSize() + element] = data[i]; + unpackedData[vertices * STRIDE + element] = data[i]; } else { - unpackedData[vertices * vertexFormat.getIntegerSize() + element] = 0; + unpackedData[vertices * STRIDE + element] = 0; } } addElement(); @@ -169,7 +143,7 @@ public void put(int element, int... data) { private void addElement() { elements++; - if (elements == vertexFormat.getElements().size()) { + if (elements == DefaultVertexFormat.BLOCK.getElements().size()) { vertices++; elements = 0; } @@ -190,26 +164,15 @@ public RecolorableBakedQuad build() { float tY = texture.sprite().contents().height() / (texture.sprite().getV1() - texture.sprite().getV0()); float tS = Math.max(tX, tY); float ep = 1f / (tS * 0x100); - int uve = 0; - while (uve < vertexFormat.getElements().size()) { - VertexFormatElement e = vertexFormat.getElements().get(uve); - if (e.getUsage() == VertexFormatElement.Usage.UV && e.getIndex() == 0) { - break; - } - uve++; - } - if (uve == vertexFormat.getElements().size()) { - throw new IllegalStateException("Can't contract UVs: format doesn't contain UVs"); - } float[] uvc = new float[4]; for (int v = 0; v < 4; v++) { for (int i = 0; i < 4; i++) { - uvc[i] += Float.intBitsToFloat(unpackedData[v * uve + i] / 4); + uvc[i] += Float.intBitsToFloat(unpackedData[v * STRIDE + i] / 4); } } for (int v = 0; v < 4; v++) { for (int i = 0; i < 4; i++) { - float uo = Float.intBitsToFloat(unpackedData[v * uve + i]); + float uo = Float.intBitsToFloat(unpackedData[v * STRIDE + i]); float eps = 1f / 0x100; float un = uo * (1 - eps) + uvc[i] * eps; float ud = uo - un; @@ -227,12 +190,12 @@ public RecolorableBakedQuad build() { un = uo + (ud < 0 ? ep : -ep); } } - unpackedData[v * uve + i] = Float.floatToRawIntBits(un); + unpackedData[v * STRIDE + i] = Float.floatToRawIntBits(un); } } } return new RecolorableBakedQuad(unpackedData, quadTint, quadOrientation, texture, shade, - hasAmbientOcclusion, vertexFormat); + hasAmbientOcclusion); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java deleted file mode 100644 index 2ad598de29..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/SpriteInformationWrapper.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.pipe.util; - -import net.minecraft.client.renderer.texture.TextureAtlasSprite; - -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class SpriteInformationWrapper implements Supplier, Consumer, - BiConsumer { - - private SpriteInformation sprite; - - @Override - public void accept(TextureAtlasSprite sprite, Integer colorID) { - accept(new SpriteInformation(sprite, colorID)); - } - - @Override - public void accept(SpriteInformation spriteInformation) { - this.sprite = spriteInformation; - } - - @Override - public SpriteInformation get() { - return this.sprite; - } - - public static SpriteInformationWrapper[] array(int size) { - SpriteInformationWrapper[] array = new SpriteInformationWrapper[size]; - for (int i = 0; i < size; i++) { - array[i] = new SpriteInformationWrapper(); - } - return array; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java b/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java index aedb2c3411..4b00e82348 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.client.util; +import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.world.entity.Entity; @@ -25,7 +26,7 @@ public static EffectRenderContext getInstance() { } @Getter - private final Frustum camera = new Frustum(Minecraft.getInstance().levelRenderer.getFrustum()); + private Frustum frustum = new Frustum(Minecraft.getInstance().levelRenderer.getFrustum()); @Nullable private Entity renderViewEntity; @@ -52,25 +53,22 @@ public static EffectRenderContext getInstance() { private float rotationXZ; @NotNull - public EffectRenderContext update(@NotNull Entity renderViewEntity, float partialTicks) { + public EffectRenderContext update(@NotNull Entity renderViewEntity, Camera camera, Frustum frustum, float partialTicks) { this.renderViewEntity = renderViewEntity; this.partialTicks = partialTicks; - this.cameraX = renderViewEntity.xOld + - (renderViewEntity.getX() - renderViewEntity.xOld) * partialTicks; - this.cameraY = renderViewEntity.yOld + - (renderViewEntity.getY() - renderViewEntity.yOld) * partialTicks; - this.cameraZ = renderViewEntity.zOld + - (renderViewEntity.getZ() - renderViewEntity.zOld) * partialTicks; + this.cameraX = camera.getPosition().x; + this.cameraY = camera.getPosition().y; + this.cameraZ = camera.getPosition().z; this.cameraViewDir = renderViewEntity.getViewVector(partialTicks); - this.rotationY = Minecraft.getInstance().gameRenderer.getMainCamera().getYRot(); - this.rotationX = Minecraft.getInstance().gameRenderer.getMainCamera().getXRot(); + this.rotationY = camera.getYRot(); + this.rotationX = camera.getXRot(); // this.rotationYZ = ActiveRenderInfo.getRotationYZ(); // this.rotationXY = ActiveRenderInfo.getRotationXY(); // this.rotationXZ = ActiveRenderInfo.getRotationXZ(); - this.camera.prepare(this.cameraX, this.cameraY, this.cameraZ); + this.frustum = frustum; return this; } diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java index 875f620552..f498dc1b86 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java @@ -147,9 +147,9 @@ public static void renderCubeFace(VertexConsumer buffer, double minX, double min float r = red, g = green, b = blue; if (shade) { - r *= 0.6; - g *= 0.6; - b *= 0.6; + r *= 0.6f; + g *= 0.6f; + b *= 0.6f; } buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java index 3f55ef5a2a..e3730a65e4 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java @@ -1,5 +1,7 @@ package com.gregtechceu.gtceu.client.util; +import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.lowdragmc.lowdraglib.client.bakedpipeline.FaceQuad; import net.minecraft.client.renderer.FaceInfo; @@ -19,6 +21,7 @@ import net.minecraftforge.client.model.QuadTransformers; import com.mojang.math.Transformation; +import org.jetbrains.annotations.Nullable; import org.joml.*; import java.lang.Math; @@ -93,7 +96,7 @@ public static BakedQuad bakeQuad( TextureAtlasSprite sprite, Direction facing, ModelState transform, - @javax.annotation.Nullable BlockElementRotation partRotation, + @Nullable BlockElementRotation partRotation, boolean shade, int emissivity) { BlockFaceUV blockfaceuv = face.uv; @@ -131,6 +134,51 @@ public static BakedQuad bakeQuad( return quad; } + public static RecolorableBakedQuad bakeRecolorableQuad( + Vector3f posFrom, + Vector3f posTo, + BlockElementFace face, + SpriteInformation sprite, + Direction facing, + ModelState transform, + @Nullable BlockElementRotation partRotation, + boolean shade, + int emissivity) { + BlockFaceUV blockfaceuv = face.uv; + if (transform.isUvLocked()) { + blockfaceuv = recomputeUVs(face.uv, facing, transform.getRotation()); + } + + float[] afloat = new float[blockfaceuv.uvs.length]; + System.arraycopy(blockfaceuv.uvs, 0, afloat, 0, afloat.length); + float f = sprite.sprite().uvShrinkRatio(); + float f1 = (blockfaceuv.uvs[0] + blockfaceuv.uvs[0] + blockfaceuv.uvs[2] + blockfaceuv.uvs[2]) / VERTEX_COUNT; + float f2 = (blockfaceuv.uvs[1] + blockfaceuv.uvs[1] + blockfaceuv.uvs[3] + blockfaceuv.uvs[3]) / VERTEX_COUNT; + blockfaceuv.uvs[0] = Mth.lerp(f, blockfaceuv.uvs[0], f1); + blockfaceuv.uvs[2] = Mth.lerp(f, blockfaceuv.uvs[2], f1); + blockfaceuv.uvs[1] = Mth.lerp(f, blockfaceuv.uvs[1], f2); + blockfaceuv.uvs[3] = Mth.lerp(f, blockfaceuv.uvs[3], f2); + int[] aint = makeVertices(blockfaceuv, sprite.sprite(), facing, setupShape(posFrom, posTo), transform.getRotation(), + partRotation, shade); + Direction direction = calculateFacing(aint); + System.arraycopy(afloat, 0, blockfaceuv.uvs, 0, afloat.length); + if (partRotation == null) { + recalculateWinding(aint, direction); + } + + ForgeHooksClient.fillNormal(aint, direction); + ForgeFaceData data = face.getFaceData(); + RecolorableBakedQuad quad = new RecolorableBakedQuad(aint, face.tintIndex, direction, sprite, shade, data.ambientOcclusion()); + if (!ForgeFaceData.DEFAULT.equals(data)) { + QuadTransformers.applyingLightmap(data.blockLight(), data.skyLight()).processInPlace(quad); + QuadTransformers.applyingColor(data.color()).processInPlace(quad); + } + com.lowdragmc.lowdraglib.client.bakedpipeline.QuadTransformers.settingEmissivity(emissivity) + .processInPlace(quad); + + return quad; + } + public static BlockFaceUV recomputeUVs(BlockFaceUV uv, Direction facing, Transformation modelRotation) { Matrix4f matrix4f = BlockMath .getUVLockTransform(modelRotation, facing, () -> "Unable to resolve UVLock for model").getMatrix(); @@ -180,7 +228,7 @@ private static int[] makeVertices( Direction orientation, float[] posDiv16, Transformation rotation, - @javax.annotation.Nullable BlockElementRotation partRotation, + @Nullable BlockElementRotation partRotation, boolean shade) { int[] aint = new int[32]; @@ -199,7 +247,7 @@ private static void bakeVertex( float[] posDiv16, TextureAtlasSprite sprite, Transformation rotation, - @javax.annotation.Nullable BlockElementRotation partRotation, + @Nullable BlockElementRotation partRotation, boolean shade) { FaceInfo.VertexInfo faceinfo$vertexinfo = FaceInfo.fromFacing(facing).getVertexInfo(vertexIndex); Vector3f vector3f = new Vector3f(posDiv16[faceinfo$vertexinfo.xFace], posDiv16[faceinfo$vertexinfo.yFace], @@ -236,7 +284,7 @@ private static float[] setupShape(Vector3f min, Vector3f max) { } private static void applyElementRotation(Vector3f vec, - @javax.annotation.Nullable BlockElementRotation partRotation) { + @Nullable BlockElementRotation partRotation) { if (partRotation != null) { Vector3f vector3f; Vector3f vector3f1; @@ -288,43 +336,43 @@ private static void rotateVertexBy(Vector3f pos, Vector3f origin, Matrix4f trans } private static void recalculateWinding(int[] vertices, Direction direction) { - int[] aint = new int[vertices.length]; - System.arraycopy(vertices, 0, aint, 0, vertices.length); - float[] afloat = new float[Direction.values().length]; - afloat[FaceInfo.Constants.MIN_X] = 999.0F; - afloat[FaceInfo.Constants.MIN_Y] = 999.0F; - afloat[FaceInfo.Constants.MIN_Z] = 999.0F; - afloat[FaceInfo.Constants.MAX_X] = -999.0F; - afloat[FaceInfo.Constants.MAX_Y] = -999.0F; - afloat[FaceInfo.Constants.MAX_Z] = -999.0F; + int[] newVertices = new int[vertices.length]; + System.arraycopy(vertices, 0, newVertices, 0, vertices.length); + float[] normals = new float[Direction.values().length]; + normals[FaceInfo.Constants.MIN_X] = 999.0F; + normals[FaceInfo.Constants.MIN_Y] = 999.0F; + normals[FaceInfo.Constants.MIN_Z] = 999.0F; + normals[FaceInfo.Constants.MAX_X] = -999.0F; + normals[FaceInfo.Constants.MAX_Y] = -999.0F; + normals[FaceInfo.Constants.MAX_Z] = -999.0F; for (int i = 0; i < 4; ++i) { int j = 8 * i; - float f = Float.intBitsToFloat(aint[j]); - float f1 = Float.intBitsToFloat(aint[j + 1]); - float f2 = Float.intBitsToFloat(aint[j + 2]); - if (f < afloat[FaceInfo.Constants.MIN_X]) { - afloat[FaceInfo.Constants.MIN_X] = f; + float f = Float.intBitsToFloat(newVertices[j]); + float f1 = Float.intBitsToFloat(newVertices[j + 1]); + float f2 = Float.intBitsToFloat(newVertices[j + 2]); + if (f < normals[FaceInfo.Constants.MIN_X]) { + normals[FaceInfo.Constants.MIN_X] = f; } - if (f1 < afloat[FaceInfo.Constants.MIN_Y]) { - afloat[FaceInfo.Constants.MIN_Y] = f1; + if (f1 < normals[FaceInfo.Constants.MIN_Y]) { + normals[FaceInfo.Constants.MIN_Y] = f1; } - if (f2 < afloat[FaceInfo.Constants.MIN_Z]) { - afloat[FaceInfo.Constants.MIN_Z] = f2; + if (f2 < normals[FaceInfo.Constants.MIN_Z]) { + normals[FaceInfo.Constants.MIN_Z] = f2; } - if (f > afloat[FaceInfo.Constants.MAX_X]) { - afloat[FaceInfo.Constants.MAX_X] = f; + if (f > normals[FaceInfo.Constants.MAX_X]) { + normals[FaceInfo.Constants.MAX_X] = f; } - if (f1 > afloat[FaceInfo.Constants.MAX_Y]) { - afloat[FaceInfo.Constants.MAX_Y] = f1; + if (f1 > normals[FaceInfo.Constants.MAX_Y]) { + normals[FaceInfo.Constants.MAX_Y] = f1; } - if (f2 > afloat[FaceInfo.Constants.MAX_Z]) { - afloat[FaceInfo.Constants.MAX_Z] = f2; + if (f2 > normals[FaceInfo.Constants.MAX_Z]) { + normals[FaceInfo.Constants.MAX_Z] = f2; } } @@ -332,22 +380,23 @@ private static void recalculateWinding(int[] vertices, Direction direction) { for (int i1 = 0; i1 < 4; ++i1) { int j1 = 8 * i1; - FaceInfo.VertexInfo faceinfo$vertexinfo = faceinfo.getVertexInfo(i1); - float f8 = afloat[faceinfo$vertexinfo.xFace]; - float f3 = afloat[faceinfo$vertexinfo.yFace]; - float f4 = afloat[faceinfo$vertexinfo.zFace]; - vertices[j1] = Float.floatToRawIntBits(f8); - vertices[j1 + 1] = Float.floatToRawIntBits(f3); - vertices[j1 + 2] = Float.floatToRawIntBits(f4); + FaceInfo.VertexInfo vertexInfo = faceinfo.getVertexInfo(i1); + float x = normals[vertexInfo.xFace]; + float y = normals[vertexInfo.yFace]; + float z = normals[vertexInfo.zFace]; + vertices[j1] = Float.floatToRawIntBits(x); + vertices[j1 + 1] = Float.floatToRawIntBits(y); + vertices[j1 + 2] = Float.floatToRawIntBits(z); for (int k = 0; k < 4; ++k) { int l = 8 * k; - float f5 = Float.intBitsToFloat(aint[l]); - float f6 = Float.intBitsToFloat(aint[l + 1]); - float f7 = Float.intBitsToFloat(aint[l + 2]); - if (Mth.equal(f8, f5) && Mth.equal(f3, f6) && Mth.equal(f4, f7)) { - vertices[j1 + 4] = aint[l + 4]; - vertices[j1 + 4 + 1] = aint[l + 4 + 1]; + float nX = Float.intBitsToFloat(newVertices[l]); + float xY = Float.intBitsToFloat(newVertices[l + 1]); + float nZ = Float.intBitsToFloat(newVertices[l + 2]); + //noinspection SuspiciousNameCombination + if (Mth.equal(x, nX) && Mth.equal(y, xY) && Mth.equal(z, nZ)) { + vertices[j1 + 4] = newVertices[l + 4]; + vertices[j1 + 4 + 1] = newVertices[l + 4 + 1]; } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java index 376b4b9441..a8349c41ee 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/common/blockentity/KineticMachineBlockEntity.java @@ -20,6 +20,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -319,7 +320,7 @@ protected void read(CompoundTag compound, boolean clientPacket) { } @Override - public void onNeighborChanged(@NotNull Direction facing) {} + public void onNeighborChanged(Block fromBlock, BlockPos fromPos, boolean isMoving) {} @Override public void markAsDirty() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java b/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java deleted file mode 100644 index f928020e96..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/filter/BaseFilterContainer.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.gregtechceu.gtceu.common.cover.filter; - -import com.gregtechceu.gtceu.api.blockentity.IDirtyNotifiable; -import com.gregtechceu.gtceu.api.cover.filter.ItemFilter; - -import com.lowdragmc.lowdraglib.misc.ItemStackTransfer; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.util.Mth; -import net.minecraft.world.item.ItemStack; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public abstract class BaseFilterContainer extends ItemStackTransfer { - - private int maxTransferSize = 1; - private int transferSize; - private @Nullable ItemFilter currentFilter; - private @Nullable Runnable onFilterInstanceChange; - private final IDirtyNotifiable dirtyNotifiable; - - protected BaseFilterContainer(IDirtyNotifiable dirtyNotifiable) { - super(); - this.dirtyNotifiable = dirtyNotifiable; - } - - public boolean test(ItemStack toTest) { - return !hasFilter() || getFilter().test(toTest); - } - - public boolean match(ItemStack toMatch) { - if (!hasFilter()) - return true; - - return getFilter().test(toMatch); - } - - public int getTransferLimit(ItemStack stack) { - if (!hasFilter() || isBlacklistFilter()) { - return getTransferSize(); - } - return getFilter().testItemCount(stack); - } - - @Override - public int getSlotLimit(int slot) { - return 1; - } - - public void onFilterInstanceChange() { - dirtyNotifiable.markAsDirty(); - if (onFilterInstanceChange != null) { - onFilterInstanceChange.run(); - } - } - - public void setOnFilterInstanceChange(@Nullable Runnable onFilterInstanceChange) { - this.onFilterInstanceChange = onFilterInstanceChange; - } - - public final @NotNull ItemStack getFilterStack() { - return this.getStackInSlot(0); - } - - @Override - public void setStackInSlot(int slot, @NotNull ItemStack stack) { - if (ItemStack.isSameItemSameTags(stack, getFilterStack())) - return; - - if (stack.isEmpty()) { - setItemFilter(null); - } else if (isItemValid(stack)) { - setItemFilter(ItemFilter.loadFilter(stack)); - } - - super.setStackInSlot(slot, stack); - } - - @Override - public boolean isItemValid(int slot, @NotNull ItemStack stack) { - return isItemValid(stack); - } - - protected abstract boolean isItemValid(ItemStack stack); - - protected abstract String getFilterName(); - - @Override - public @NotNull ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { - if (!isItemValid(stack)) return stack; - var remainder = super.insertItem(slot, stack, simulate); - if (!simulate) setItemFilter(ItemFilter.loadFilter(stack)); - return remainder; - } - - @Override - public @NotNull ItemStack extractItem(int slot, int amount, boolean simulate) { - var extracted = super.extractItem(slot, amount, simulate); - if (!extracted.isEmpty()) { - setFilter(null); - } - return extracted; - } - - public final void setFilterStack(ItemStack stack) { - setStackInSlot(0, stack); - } - - public int getMaxTransferSize() { - return !showGlobalTransferLimitSlider() && hasFilter() ? currentFilter.getMaxStackSize() : - this.maxTransferSize; - } - - public void setMaxTransferSize(int maxTransferSize) { - this.maxTransferSize = Mth.clamp(maxTransferSize, 1, Integer.MAX_VALUE); - this.transferSize = Mth.clamp(this.transferSize, 1, this.maxTransferSize); - // if (hasFilter()) currentFilter.setMaxTransferSize(this.maxTransferSize); - } - - public final boolean hasFilter() { - return currentFilter != null; - } - - public final @Nullable ItemFilter getFilter() { - return currentFilter; - } - - public final void setItemFilter(@Nullable ItemFilter newFilter) { - this.currentFilter = newFilter; - if (hasFilter()) { - this.currentFilter.setOnUpdated($ -> this.dirtyNotifiable.markAsDirty()); - // this.currentFilter.setMaxTransferSize(this.maxTransferSize); - } - if (onFilterInstanceChange != null) { - this.onFilterInstanceChange.run(); - } - } - - public boolean showGlobalTransferLimitSlider() { - return this.maxTransferSize > 0 && (!hasFilter()/* || getFilter().showGlobalTransferLimitSlider() */); - } - - public void setBlacklistFilter(boolean blacklistFilter) { - if (hasFilter()) getFilter().setBlackList(blacklistFilter); - onFilterInstanceChange(); - } - - public final boolean isBlacklistFilter() { - return hasFilter() && getFilter().isBlackList(); - } - - public int getTransferSize() { - if (!showGlobalTransferLimitSlider()) { - return getMaxTransferSize(); - } - return this.transferSize; - } - - public int getTransferLimit(int slotIndex) { - if (isBlacklistFilter() || !hasFilter()) { - return getTransferSize(); - } - return this.currentFilter.testItemCount(getStackInSlot(slotIndex)); - } - - public void setTransferSize(int transferSize) { - this.transferSize = Mth.clamp(transferSize, 1, getMaxTransferSize()); - onFilterInstanceChange(); - } - - @Override - public CompoundTag serializeNBT() { - CompoundTag tagCompound = new CompoundTag(); - tagCompound.put("FilterInventory", super.serializeNBT()); - tagCompound.putInt("TransferStackSize", getTransferSize()); - return tagCompound; - } - - @Override - public void deserializeNBT(CompoundTag nbt) { - super.deserializeNBT(nbt.getCompound("FilterInventory")); - setItemFilter(ItemFilter.loadFilter(getFilterStack())); - if (nbt.contains("TransferStackSize")) - this.transferSize = nbt.getInt("TransferStackSize"); - } - - public void handleLegacyNBT(CompoundTag nbt) { - // for filters as covers, the stack is set manually, and "FilterInventory" doesn't exist to be deserialized - // also, ItemStackHandler's deserialization doesn't use setStackInSlot, so I have to do that manually here - if (nbt.contains("FilterInventory")) { - super.deserializeNBT(nbt.getCompound("FilterInventory")); - setItemFilter(ItemFilter.loadFilter(getFilterStack())); - } - } - - /** Uses Cleanroom MUI */ - // TODO ui - /* - * public IWidget initUI(ModularPanel main, PanelSyncManager manager) { - * PanelSyncHandler panel = manager.panel("filter_panel", main, (syncManager, syncHandler) -> { - * var filter = hasFilter() ? getFilter() : BaseFilter.ERROR_FILTER; - * filter.setMaxTransferSize(getMaxTransferSize()); - * return filter.createPopupPanel(syncManager); - * }); - * - * var filterButton = new ButtonWidget<>(); - * filterButton.setEnabled(hasFilter()); - * - * return new Row().coverChildrenHeight() - * .marginBottom(2).widthRel(1f) - * .child(new ItemSlot() - * .slot(SyncHandlers.itemSlot(this, 0) - * .filter(this::isItemValid) - * .singletonSlotGroup(101) - * .changeListener((newItem, onlyAmountChanged, client, init) -> { - * if (!isItemValid(newItem) && panel.isPanelOpen()) { - * panel.closePanel(); - * } - * })) - * .size(18).marginRight(2) - * .background(GTGuiTextures.SLOT, GTGuiTextures.FILTER_SLOT_OVERLAY.asIcon().size(16))) - * .child(filterButton - * .background(GTGuiTextures.MC_BUTTON, GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) - * .hoverBackground(GuiTextures.MC_BUTTON_HOVERED, - * GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) - * .setEnabledIf(w -> hasFilter()) - * .onMousePressed(i -> { - * if (!panel.isPanelOpen()) { - * panel.openPanel(); - * } else { - * panel.closePanel(); - * } - * Interactable.playButtonClickSound(); - * return true; - * })) - * .child(IKey.dynamic(this::getFilterName) - * .alignment(Alignment.CenterRight).asWidget() - * .left(36).right(0).height(18)); - * } - */ - - public void writeInitialSyncData(FriendlyByteBuf packetBuffer) { - packetBuffer.writeItem(this.getFilterStack()); - packetBuffer.writeInt(this.maxTransferSize); - packetBuffer.writeInt(this.transferSize); - } - - public void readInitialSyncData(@NotNull FriendlyByteBuf packetBuffer) { - var stack = packetBuffer.readItem(); - this.setFilterStack(stack); - this.setMaxTransferSize(packetBuffer.readInt()); - this.setTransferSize(packetBuffer.readInt()); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index a3e155d265..342949b936 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.data; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.ActivablePipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.blockentity.*; @@ -23,12 +24,15 @@ public class GTBlockEntities { public static final BlockEntityEntry PIPE = REGISTRATE .blockEntity("pipe", PipeBlockEntity::new) - .validBlocks(Stream.concat(GTBlocks.DUCT_PIPE_BLOCKS.values().stream(), - Stream.concat(Stream.of(GTBlocks.OPTICAL_PIPE), Stream.of(GTBlocks.LASER_PIPE))) - .toArray(NonNullSupplier[]::new)) + .validBlocks(GTBlocks.DUCT_PIPE_BLOCKS.values().toArray(NonNullSupplier[]::new)) + .register(); + + public static final BlockEntityEntry ACTIVABLE_PIPE = REGISTRATE + .blockEntity("activable_pipe", ActivablePipeBlockEntity::new) + .validBlocks(Stream.of(GTBlocks.OPTICAL_PIPE, GTBlocks.LASER_PIPE).toArray(NonNullSupplier[]::new)) .register(); - public static final BlockEntityEntry MATERIAL_PIPE = REGISTRATE + public static final BlockEntityEntry MATERIAL_PIPE = REGISTRATE .blockEntity("material_pipe", MaterialPipeBlockEntity::new) .validBlocks(Stream.concat(GTBlocks.CABLE_BLOCKS.values().stream(), GTBlocks.MATERIAL_PIPE_BLOCKS.values().stream()) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index bb35c72516..9ea0fbd34f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -137,27 +137,26 @@ public class GTBlocks { public static Table> MATERIAL_PIPE_BLOCKS; public static Map> DUCT_PIPE_BLOCKS; public static final BlockEntry LASER_PIPE = REGISTRATE - .block("normal_laser_pipe", (p) -> new LaserPipeBlock(p, LaserStructure.NORMAL)) + .block("laser_pipe", (p) -> new LaserPipeBlock(p, LaserStructure.NORMAL)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) .blockstate(NonNullBiConsumer.noop()) .defaultLoot() .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) .addLayer(() -> RenderType::cutoutMipped) - .item(com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem::new) + .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) .build() .register(); public static final BlockEntry OPTICAL_PIPE = REGISTRATE - .block("normal_optical_pipe", (p) -> new OpticalPipeBlock(p, OpticalStructure.INSTANCE)) - .lang("Optical Fiber Cable") + .block("optical_fiber_cable", (p) -> new OpticalPipeBlock(p, OpticalStructure.INSTANCE)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) .blockstate(NonNullBiConsumer.noop()) .defaultLoot() .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) .addLayer(() -> RenderType::cutoutMipped) - .item(com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem::new) + .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) .build() .register(); @@ -324,7 +323,7 @@ private static boolean allowCableBlock(Material material, CableStructure insulat private static void registerCableBlock(Material material, CableStructure structure, GTRegistrate registrate) { var entry = registrate .block("%s_%s".formatted(material.getName(), structure.name()), - p -> new com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock(p, structure, material)) + p -> new CableBlock(p, structure, material)) .initialProperties(() -> Blocks.IRON_BLOCK) .properties(p -> p.dynamicShape().noOcclusion().noLootTable().forceSolidOn()) .transform(unificationBlock(structure.prefix(), material)) @@ -332,9 +331,8 @@ private static void registerCableBlock(Material material, CableStructure structu .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) - .item(PipeBlockItem::new) + .item(MaterialPipeBlockItem::new) .model(NonNullBiConsumer.noop()) - // .color(() -> ::tintColor) .onRegister(compassNodeExist(GTCompassSections.MATERIALS, "wire_and_cable")) .build() .register(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index c800524b4a..0432ced2a1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -3,7 +3,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.data.GTDamageTypes; @@ -27,7 +27,7 @@ import java.util.Map; -public class CableBlock extends MaterialPipeBlock implements IBurnable { +public class CableBlock extends PipeMaterialBlock implements IBurnable { private static final Map> CACHE = new Object2ObjectOpenHashMap<>(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java index b11c48e9e7..3501c59f35 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -2,10 +2,12 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import net.minecraft.core.Direction; import org.jetbrains.annotations.NotNull; @@ -28,6 +30,11 @@ public LaserStructure(String name, float renderThickness, boolean mirror, Activa PipeStructureRegistry.register(this); } + @Override + public ResourceTexture getPipeTexture(boolean isBlock) { + return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; + } + @Override public boolean canConnectTo(Direction side, byte connectionMask) { if (mirror) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java index 12c3d49b82..3836561e03 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -2,10 +2,12 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import net.minecraft.core.Direction; import org.jetbrains.annotations.NotNull; @@ -24,6 +26,11 @@ public OpticalStructure(String name, float renderThickness, ActivablePipeModel m PipeStructureRegistry.register(this); } + @Override + public ResourceTexture getPipeTexture(boolean isBlock) { + return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; + } + @Override public boolean canConnectTo(Direction side, byte connectionMask) { byte connectionCount = 0; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java index 3b855af001..37592987a3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -4,10 +4,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import net.minecraft.world.level.block.state.BlockBehaviour; -public class MaterialPipeBlock extends com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlock - implements IBurnable, IFreezable { +public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, IFreezable { public MaterialPipeBlock(BlockBehaviour.Properties properties, MaterialPipeStructure structure, Material material) { super(properties, structure, material); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java index 385910cfdc..28fa4e809d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/SlowActiveWalker.java @@ -2,7 +2,7 @@ import com.gregtechceu.gtceu.api.graphnet.path.INetPath; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeActivableBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.ActivablePipeBlockEntity; import com.gregtechceu.gtceu.utils.TaskScheduler; import com.gregtechceu.gtceu.utils.function.Task; @@ -103,7 +103,7 @@ protected void step(@Nullable WorldPipeNetNode previous, @Nullable WorldPipeNetN } protected void activate(@NotNull WorldPipeNetNode node, boolean active) { - if (node.getBlockEntity() instanceof PipeActivableBlockEntity activable) { + if (node.getBlockEntity() instanceof ActivablePipeBlockEntity activable) { activable.setActive(active); } } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java index 316dca271a..abde66fdf1 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java @@ -61,7 +61,7 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso return; } WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(blockAccessor.getPosition()); - EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + EnergyFlowLogic logic = node.getData().getLogicEntryDefaultable(EnergyFlowLogic.INSTANCE); long currentTick = serverLevel.getServer().getTickCount(); long totalVoltage = 0L; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java index 12d93469b7..c11394798c 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/StainedColorProvider.java @@ -24,7 +24,8 @@ public class StainedColorProvider implements IBlockComponentProvider, IServerDat public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPluginConfig iPluginConfig) { if (blockAccessor.getServerData().contains("StainedColor")) { int paintingColor = blockAccessor.getServerData().getInt("StainedColor"); - if (paintingColor != -1) { + int defaultColor = blockAccessor.getServerData().getInt("DefaultColor"); + if (paintingColor != defaultColor) { iTooltip.add(Component .translatable("gtceu.top.stained", "#" + Integer.toHexString(paintingColor).toUpperCase(Locale.ROOT)) @@ -40,10 +41,12 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso if (metaMachine != null) { int paintingColor = metaMachine.getPaintingColor(); compoundTag.putInt("StainedColor", paintingColor); + compoundTag.putInt("DefaultColor", -1); } } else if (blockAccessor.getBlockEntity() instanceof PipeBlockEntity pipe) { int paintingColor = pipe.getPaintingColor(); compoundTag.putInt("StainedColor", paintingColor); + compoundTag.putInt("DefaultColor", pipe.getDefaultPaintingColor()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java index 1860d05120..f3f9731458 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java @@ -11,13 +11,12 @@ import com.lowdragmc.lowdraglib.syncdata.managed.MultiManagedStorage; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; import net.minecraft.world.level.Level; import com.google.common.collect.Table; import it.unimi.dsi.fastutil.ints.Int2LongFunction; import lombok.Getter; -import org.jetbrains.annotations.NotNull; +import net.minecraft.world.level.block.Block; import java.util.List; @@ -52,7 +51,7 @@ public MultiManagedStorage getRootStorage() { } @Override - public void onNeighborChanged(@NotNull Direction facing) {} + public void onNeighborChanged(Block fromBlock, BlockPos fromPos, boolean isMoving) {} @Override public Level getLevel() { diff --git a/src/main/java/com/gregtechceu/gtceu/utils/SupplierMemoizer.java b/src/main/java/com/gregtechceu/gtceu/utils/SupplierMemoizer.java index ef6b2b8a2c..cf27a7eae3 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/SupplierMemoizer.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/SupplierMemoizer.java @@ -10,10 +10,16 @@ public class SupplierMemoizer { public static MemoizedSupplier memoize(Supplier delegate) { + if (delegate instanceof MemoizedSupplier supplier) { + return supplier; + } return new MemoizedSupplier<>(delegate); } public static MemoizedBlockSupplier memoizeBlockSupplier(Supplier delegate) { + if (delegate instanceof MemoizedBlockSupplier supplier) { + return supplier; + } return new MemoizedBlockSupplier<>(delegate); } diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_activable.json b/src/main/resources/assets/gtceu/blockstates/pipe_activable.json deleted file mode 100644 index 9d0c0a3397..0000000000 --- a/src/main/resources/assets/gtceu/blockstates/pipe_activable.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "gtceu:block/pipe/optical" - } - } -} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_cable.json b/src/main/resources/assets/gtceu/blockstates/pipe_cable.json deleted file mode 100644 index 5afffd2675..0000000000 --- a/src/main/resources/assets/gtceu/blockstates/pipe_cable.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "gtceu:block/pipe/cable_wire" - } - } -} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_duct.json b/src/main/resources/assets/gtceu/blockstates/pipe_duct.json deleted file mode 100644 index dfb59a8466..0000000000 --- a/src/main/resources/assets/gtceu/blockstates/pipe_duct.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "duct_pipe": { - "model": "gtceu:block/pipe/duct" - } - } -} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_material.json b/src/main/resources/assets/gtceu/blockstates/pipe_material.json deleted file mode 100644 index c483b723bf..0000000000 --- a/src/main/resources/assets/gtceu/blockstates/pipe_material.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "gtceu:block/pipe/pipe_0_standard" - } - } -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_0.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_1.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_2.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_3.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/cable_insulation_4.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json b/src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/cable_wire.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/duct.json b/src/main/resources/assets/gtceu/models/block/pipe/duct.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/duct.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/laser.json b/src/main/resources/assets/gtceu/models/block/pipe/laser.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/laser.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/optical.json b/src/main/resources/assets/gtceu/models/block/pipe/optical.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/optical.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_restrictive.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_0_standard.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_restrictive.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_1_standard.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_restrictive.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_2_standard.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_restrictive.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_3_standard.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_restrictive.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_4_standard.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_restrictive.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_5_standard.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_restrictive.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json b/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json deleted file mode 100644 index 2c6047defb..0000000000 --- a/src/main/resources/assets/gtceu/models/block/pipe/pipe_6_standard.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "loader": "forge:empty" -} diff --git a/src/main/resources/assets/gtceu/models/item/invar_lighter.json b/src/main/resources/assets/gtceu/models/item/invar_lighter.json index a777fd4faf..06b961df48 100644 --- a/src/main/resources/assets/gtceu/models/item/invar_lighter.json +++ b/src/main/resources/assets/gtceu/models/item/invar_lighter.json @@ -1,7 +1,7 @@ { "parent": "item/generated", "textures": { - "layer0": "gtceu:items/invar_lighter" + "layer0": "gtceu:items/platinum_lighter_closed" }, "overrides": [ { diff --git a/src/main/resources/assets/gtceu/models/item/platinum_lighter.json b/src/main/resources/assets/gtceu/models/item/platinum_lighter.json index fb1913edac..1e856ee603 100644 --- a/src/main/resources/assets/gtceu/models/item/platinum_lighter.json +++ b/src/main/resources/assets/gtceu/models/item/platinum_lighter.json @@ -1,7 +1,7 @@ { "parent": "item/generated", "textures": { - "layer0": "gtceu:items/platinum_lighter" + "layer0": "gtceu:items/platinum_lighter_closed" }, "overrides": [ { From eedb538fbf72cf179a673ef09bed4c84bc196a46 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 25 Aug 2024 12:15:53 +0300 Subject: [PATCH 18/70] render works now --- .../client/particle/GTOverheatParticle.java | 34 ++++++--- .../gtceu/client/particle/GTParticle.java | 5 +- .../client/particle/GTParticleManager.java | 16 ++-- .../gtceu/client/util/RenderBufferHelper.java | 73 ++++++++++--------- 4 files changed, 76 insertions(+), 52 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java index edb14f72a7..16de1a4e27 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java @@ -12,18 +12,19 @@ import com.gregtechceu.gtceu.client.util.RenderBufferHelper; import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.shimmer.client.shader.RenderUtils; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import lombok.Setter; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.*; +import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -240,19 +241,30 @@ public IRenderSetup getRenderSetup() { } @Override - public void renderParticle(@NotNull PoseStack poseStack, @NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) { - if (insulated) { - return; + public boolean shouldRender(@NotNull EffectRenderContext context) { + if (this.insulated) return false; + for (AABB cuboid : pipeBoxes.toAabbs()) { + if (!context.frustum().isVisible(cuboid.move(posX, posY, posZ))) { + return false; + } } + return true; + } + @Override + public void renderParticle(@NotNull PoseStack poseStack, @NotNull BufferBuilder buffer, + @NotNull EffectRenderContext context) { if (GTCEu.isShimmerLoaded()) { - BloomUtils.entityBloom(source -> renderBloomEffect(poseStack, source.getBuffer(GTRenderTypes.getBloomQuad()), context)); + final PoseStack finalStack = RenderUtils.copyPoseStack(poseStack); + BloomUtils.entityBloom( + source -> renderBloomEffect(finalStack, source.getBuffer(GTRenderTypes.getBloomQuad()), context)); } else { renderBloomEffect(poseStack, buffer, context); } } - public void renderBloomEffect(@NotNull PoseStack poseStack, @NotNull VertexConsumer buffer, @NotNull EffectRenderContext context) { + public void renderBloomEffect(@NotNull PoseStack poseStack, @NotNull VertexConsumer buffer, + @NotNull EffectRenderContext context) { float red = ((color >> 16) & 0xFF) / 255f; float green = ((color >> 8) & 0xFF) / 255f; float blue = (color & 0xFF) / 255f; @@ -260,11 +272,11 @@ public void renderBloomEffect(@NotNull PoseStack poseStack, @NotNull VertexConsu poseStack.pushPose(); poseStack.translate(posX - context.cameraX(), posY - context.cameraY(), posZ - context.cameraZ()); for (AABB cuboid : pipeBoxes.toAabbs()) { - cuboid.inflate(0.01); - RenderBufferHelper.renderCubeFace(buffer, cuboid, red, green, blue, alpha, true); + RenderBufferHelper.renderCubeFace(poseStack, buffer, cuboid, red, green, blue, alpha, true); } poseStack.popPose(); } + private static final IRenderSetup SETUP = new IRenderSetup() { @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java index b748880a9d..356a350c6b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java @@ -3,11 +3,11 @@ import com.gregtechceu.gtceu.client.renderer.IRenderSetup; import com.gregtechceu.gtceu.client.util.EffectRenderContext; -import com.mojang.blaze3d.vertex.PoseStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.PoseStack; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -105,7 +105,8 @@ protected void onExpired() {} * @param buffer buffer builder * @param context render context */ - public void renderParticle(@NotNull PoseStack poseStack, @NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) {} + public void renderParticle(@NotNull PoseStack poseStack, @NotNull BufferBuilder buffer, + @NotNull EffectRenderContext context) {} /** * @return Render setup for this particle, if exists diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java index f2d636086b..5e29267d84 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java @@ -4,7 +4,6 @@ import com.gregtechceu.gtceu.client.renderer.IRenderSetup; import com.gregtechceu.gtceu.client.util.EffectRenderContext; -import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.ChatFormatting; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; @@ -23,6 +22,7 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import org.jetbrains.annotations.NotNull; @@ -121,10 +121,12 @@ public void clearAllEffects(boolean cleanNewQueue) { depthDisabledParticles.clear(); } - public void renderParticles(@NotNull PoseStack poseStack, @NotNull Entity renderViewEntity, Camera camera, Frustum frustum, float partialTicks) { + public void renderParticles(@NotNull PoseStack poseStack, @NotNull Entity renderViewEntity, Camera camera, + Frustum frustum, float partialTicks) { if (depthEnabledParticles.isEmpty() && depthDisabledParticles.isEmpty()) return; - EffectRenderContext instance = EffectRenderContext.getInstance().update(renderViewEntity, camera, frustum, partialTicks); + EffectRenderContext instance = EffectRenderContext.getInstance().update(renderViewEntity, camera, frustum, + partialTicks); RenderSystem.enableBlend(); RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); @@ -142,7 +144,8 @@ public void renderParticles(@NotNull PoseStack poseStack, @NotNull Entity render RenderSystem.disableBlend(); } - private static void renderGlParticlesInLayer(@NotNull PoseStack poseStack, @NotNull Map<@Nullable IRenderSetup, ArrayDeque> renderQueue, + private static void renderGlParticlesInLayer(@NotNull PoseStack poseStack, + @NotNull Map<@Nullable IRenderSetup, ArrayDeque> renderQueue, @NotNull EffectRenderContext context) { for (var e : renderQueue.entrySet()) { @Nullable @@ -193,9 +196,10 @@ public static void clientTick(TickEvent.ClientTickEvent event) { @SubscribeEvent public static void renderWorld(RenderLevelStageEvent event) { - if (event.getStage() == RenderLevelStageEvent.Stage.AFTER_LEVEL) { + if (event.getStage() == RenderLevelStageEvent.Stage.AFTER_CUTOUT_BLOCKS) { Entity entity = Minecraft.getInstance().getCameraEntity(); - INSTANCE.renderParticles(event.getPoseStack(), entity == null ? Minecraft.getInstance().player : entity, event.getCamera(), event.getFrustum(), event.getPartialTick()); + INSTANCE.renderParticles(event.getPoseStack(), entity == null ? Minecraft.getInstance().player : entity, + event.getCamera(), event.getFrustum(), event.getPartialTick()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java index f498dc1b86..ee976b0566 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java @@ -130,20 +130,27 @@ public static void renderCubeFrame(BufferBuilder buffer, double minX, double min buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); } - public static void renderCubeFace(VertexConsumer buffer, AABB cuboid, float r, float g, float b, float a, + public static void renderCubeFace(PoseStack poseStack, VertexConsumer buffer, AABB cuboid, float r, float g, float b, float a, boolean shade) { - renderCubeFace(buffer, cuboid.minX, cuboid.minY, cuboid.minZ, cuboid.maxX, cuboid.maxY, cuboid.maxZ, r, g, - b, a, shade); + renderCubeFace(poseStack, buffer, + (float) cuboid.minX, (float) cuboid.minY, (float) cuboid.minZ, + (float) cuboid.maxX, (float) cuboid.maxY, (float) cuboid.maxZ, + r, g, b, a, shade); } - public static void renderCubeFace(VertexConsumer buffer, double minX, double minY, double minZ, double maxX, - double maxY, double maxZ, float red, float green, float blue, float alpha) { - renderCubeFace(buffer, minX, minY, minZ, maxX, maxY, maxZ, red, green, blue, alpha, false); + public static void renderCubeFace(PoseStack poseStack, VertexConsumer buffer, + float minX, float minY, float minZ, + float maxX, float maxY, float maxZ, + float red, float green, float blue, float alpha) { + renderCubeFace(poseStack, buffer, minX, minY, minZ, maxX, maxY, maxZ, red, green, blue, alpha, false); } - public static void renderCubeFace(VertexConsumer buffer, double minX, double minY, double minZ, double maxX, - double maxY, double maxZ, float red, float green, float blue, float a, + public static void renderCubeFace(PoseStack poseStack, VertexConsumer buffer, + float minX, float minY, float minZ, + float maxX, float maxY, float maxZ, + float red, float green, float blue, float a, boolean shade) { + Matrix4f pose = poseStack.last().pose(); float r = red, g = green, b = blue; if (shade) { @@ -151,49 +158,49 @@ public static void renderCubeFace(VertexConsumer buffer, double minX, double min g *= 0.6f; b *= 0.6f; } - buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, maxY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, minY, maxZ).color(r, g, b, a).endVertex(); if (shade) { r = red * 0.5f; g = green * 0.5f; b = blue * 0.5f; } - buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, minY, maxZ).color(r, g, b, a).endVertex(); if (shade) { r = red; g = green; b = blue; } - buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, maxY, minZ).color(r, g, b, a).endVertex(); if (shade) { r = red * 0.8f; g = green * 0.8f; b = blue * 0.8f; } - buffer.vertex(minX, minY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(minX, maxY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, maxY, minZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, minY, minZ).color(r, g, b, a).endVertex(); - - buffer.vertex(minX, minY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, minY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(maxX, maxY, maxZ).color(r, g, b, a).endVertex(); - buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, minY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, maxY, minZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, minY, minZ).color(r, g, b, a).endVertex(); + + buffer.vertex(pose, minX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, minY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, maxX, maxY, maxZ).color(r, g, b, a).endVertex(); + buffer.vertex(pose, minX, maxY, maxZ).color(r, g, b, a).endVertex(); } } From 18808f59d2c978179dc9307991a6d85c287fb801 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 25 Aug 2024 15:33:39 +0300 Subject: [PATCH 19/70] new model logic port --- .../gtceu/api/block/MetaMachineBlock.java | 1 - .../pipenet/physical/IPipeStructure.java | 4 +- .../physical/block/ActivablePipeBlock.java | 4 +- .../pipenet/physical/block/PipeBlock.java | 42 +-- .../pipenet/physical/block/PipeBlockItem.java | 2 - .../physical/block/PipeMaterialBlock.java | 7 +- .../tile/ActivablePipeBlockEntity.java | 9 +- .../tile/MaterialPipeBlockEntity.java | 1 + .../physical/tile/PipeBlockEntity.java | 6 - .../gtceu/api/item/MetaMachineItem.java | 5 +- .../api/machine/MachineCoverContainer.java | 3 +- .../gregtechceu/gtceu/client/ClientProxy.java | 15 +- .../renderer/pipe/AbstractPipeModel.java | 77 +----- .../renderer/pipe/ActivablePipeModel.java | 62 ++--- .../client/renderer/pipe/CableModel.java | 72 +++-- .../client/renderer/pipe/DuctPipeModel.java | 12 +- .../client/renderer/pipe/PipeItemModel.java | 26 +- .../gtceu/client/renderer/pipe/PipeModel.java | 114 +++----- .../renderer/pipe/PipeModelRedirector.java | 124 +++++++++ .../renderer/pipe/PipeModelRegistry.java | 261 ++++++++++++++++++ .../renderer/pipe/UnbakedPipeModel.java | 4 +- .../client/renderer/pipe/quad/QuadHelper.java | 2 +- .../pipe/quad/RecolorableBakedQuad.java | 4 +- .../pipe/util/MaterialModelOverride.java | 45 +++ .../pipe/util/MaterialModelSupplier.java | 14 + ...Clarifier.java => TextureInformation.java} | 7 +- .../renderer/pipe/util/WoodCacheKey.java | 54 ---- .../client/util/EffectRenderContext.java | 3 +- .../gtceu/client/util/RenderBufferHelper.java | 3 +- .../gtceu/client/util/StaticFaceBakery.java | 27 +- .../gtceu/common/data/GTBlockEntities.java | 2 +- .../pipelike/block/cable/CableStructure.java | 59 ++-- .../pipelike/block/duct/DuctStructure.java | 17 +- .../pipelike/block/laser/LaserStructure.java | 25 +- .../block/optical/OpticalStructure.java | 23 +- .../block/pipe/MaterialPipeBlock.java | 7 +- .../block/pipe/MaterialPipeStructure.java | 81 ++---- .../gtceu/utils/DummyMachineBlockEntity.java | 2 +- 38 files changed, 690 insertions(+), 536 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java create mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelSupplier.java rename src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/{PipeSpriteWoodClarifier.java => TextureInformation.java} (61%) delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java b/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java index 2789997b40..08992d4942 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/block/MetaMachineBlock.java @@ -12,7 +12,6 @@ import com.gregtechceu.gtceu.api.machine.feature.*; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.config.ConfigHolder; -import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.client.renderer.IRenderer; import com.lowdragmc.lowdraglib.utils.LocalizationUtils; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java index ac042478ee..73d3fc874a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -2,7 +2,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; @@ -26,7 +26,7 @@ public interface IPipeStructure extends StringRepresentable { boolean isPaintable(); - AbstractPipeModel getModel(); + PipeModelRedirector getModel(); default ResourceTexture getPipeTexture(boolean isBlock) { return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java index bf7f179ed3..9a49e7c259 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java @@ -3,14 +3,14 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.ActivablePipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; - import com.gregtechceu.gtceu.common.data.GTBlockEntities; + import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; - import net.minecraft.world.level.block.state.BlockState; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 412ef748d8..c5c934cc59 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -425,18 +425,20 @@ public void entityInside(BlockState state, Level level, BlockPos pos, Entity ent @SuppressWarnings("deprecation") @Override - public @NotNull VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { + public @NotNull VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, + CollisionContext context) { var tile = getBlockEntity(level, pos); if (tile == null) { - return super.getCollisionShape(state, level, pos, context); - } - if (tile.getFrameMaterial() != null) { - return MaterialBlock.FRAME_COLLISION_BOX; + return Shapes.block(); } List shapes = new ArrayList<>(); shapes.add(getStructure().getPipeBoxes(tile)); tile.getCoverBoxes(shapes::add); - return shapes.stream().reduce(Shapes.empty(), Shapes::or); + VoxelShape shape = shapes.stream().reduce(Shapes.empty(), Shapes::or); + if (tile.getFrameMaterial() != null) { + return Shapes.or(shape, MaterialBlock.FRAME_COLLISION_BOX); + } + return shape; } @Override @@ -451,17 +453,19 @@ public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, Co if (tile == null) { return Shapes.block(); } - if (tile.getFrameMaterial() != null) { - return MaterialBlock.FRAME_COLLISION_BOX; - } List shapes = new ArrayList<>(); shapes.add(getStructure().getPipeBoxes(tile)); tile.getCoverBoxes(shapes::add); - return shapes.stream().reduce(Shapes.empty(), Shapes::or); + VoxelShape shape = shapes.stream().reduce(Shapes.empty(), Shapes::or); + if (tile.getFrameMaterial() != null) { + return Shapes.or(shape, MaterialBlock.FRAME_COLLISION_BOX); + } + return shape; } @Override - public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor level, BlockPos pos, BlockPos neighborPos) { + public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor level, + BlockPos pos, BlockPos neighborPos) { return super.updateShape(state, direction, neighborState, level, pos, neighborPos); } @@ -578,14 +582,14 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { } /* - @Override - public void onNeighborChange(BlockState state, LevelReader level, BlockPos pos, BlockPos neighbor) { - super.onNeighborChange(state, level, pos, neighbor); - Direction facing = GTUtil.getFacingToNeighbor(pos, neighbor); - if (facing == null) return; - PipeBlockEntity tile = getBlockEntity(level, pos); - if (tile != null) tile.onNeighborChanged(level.getBlockState(neighbor).getBlock(), neighbor, false); - } + * @Override + * public void onNeighborChange(BlockState state, LevelReader level, BlockPos pos, BlockPos neighbor) { + * super.onNeighborChange(state, level, pos, neighbor); + * Direction facing = GTUtil.getFacingToNeighbor(pos, neighbor); + * if (facing == null) return; + * PipeBlockEntity tile = getBlockEntity(level, pos); + * if (tile != null) tile.onNeighborChanged(level.getBlockState(neighbor).getBlock(), neighbor, false); + * } */ @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java index 2b84ba875c..7ba15f591a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlockItem.java @@ -67,6 +67,4 @@ public boolean placeBlock(BlockPlaceContext context, BlockState state) { return true; } else return false; } - - } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index b16d7471fa..cafb404c07 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -7,7 +7,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.data.GTBlockEntities; -import com.gregtechceu.gtceu.common.data.GTMaterials; import com.gregtechceu.gtceu.config.ConfigHolder; import net.minecraft.core.BlockPos; @@ -35,6 +34,12 @@ public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStru this.material = material; } + @Nullable + public static PipeMaterialBlock getBlockFromItem(@NotNull ItemStack stack) { + if (stack.getItem() instanceof MaterialPipeBlockItem block) return block.getBlock(); + else return null; + } + @Override public IPipeMaterialStructure getStructure() { return (IPipeMaterialStructure) super.getStructure(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/ActivablePipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/ActivablePipeBlockEntity.java index c6c1416a79..9d94c2aa5a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/ActivablePipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/ActivablePipeBlockEntity.java @@ -1,20 +1,19 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; -import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; -import lombok.Setter; + import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import lombok.Getter; -import org.jetbrains.annotations.NotNull; +import lombok.Setter; public class ActivablePipeBlockEntity extends PipeBlockEntity implements IActivable { - protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(ActivablePipeBlockEntity.class, PipeBlockEntity.MANAGED_FIELD_HOLDER); + protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder( + ActivablePipeBlockEntity.class, PipeBlockEntity.MANAGED_FIELD_HOLDER); @DescSynced @Getter diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java index ce5794c6d9..6f66a2d1d8 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/MaterialPipeBlockEntity.java @@ -26,6 +26,7 @@ public MaterialPipeBlockEntity(BlockEntityType type, BlockPos pos, BlockState public int getDefaultPaintingColor() { return GTUtil.convertRGBtoARGB(getBlockType().material.getMaterialRGB()); } + @Override public @NotNull ModelData getModelData() { return super.getModelData().derive().with(AbstractPipeModel.MATERIAL_PROPERTY, getBlockType().material).build(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index f6eb4a6966..6925d7c988 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -523,16 +523,11 @@ protected void initialize() { firstNode = false; this.temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); } - // TODO - // this and updateActiveStatus() theoretically only need to be called when loading old world data; - // is there a way to detect that and skip if so? - node.getNet().updatePredication(node, this); } this.netLogicDatas.trim(); this.listeners.trim(); this.capabilities.trim(); this.netCapabilities.trim(); - updateActiveStatus(null, false); } } @@ -560,7 +555,6 @@ public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { scheduleRenderUpdate(); } - // TODO figure out replacement @Override public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { if (discriminator == UPDATE_PIPE_LOGIC) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java index cf126d3b34..320da6c5cf 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/item/MetaMachineItem.java @@ -21,7 +21,6 @@ import org.jetbrains.annotations.Nullable; import javax.annotation.ParametersAreNonnullByDefault; -import java.nio.channels.Pipe; /** * @author KilaBash @@ -55,12 +54,12 @@ protected boolean placeBlock(BlockPlaceContext context, BlockState state) { boolean superVal = super.placeBlock(context, state); if (!level.isClientSide) { - BlockPos possiblePipe = pos.offset(side.getOpposite().getNormal()); + BlockPos possiblePipe = pos.relative(side.getOpposite()); Block block = level.getBlockState(possiblePipe).getBlock(); if (block instanceof PipeBlock pipeBlock) { PipeBlockEntity pipeTile = pipeBlock.getBlockEntity(level, possiblePipe); if (pipeTile != null && pipeTile.canConnectTo(side.getOpposite())) { - PipeBlock.connectTile(pipeTile, null, side); + pipeTile.updateActiveStatus(side.getOpposite(), true); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java index b63df22011..ac54841c49 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java @@ -87,7 +87,8 @@ public void onLoad() { if (getLevel() instanceof ServerLevel serverLevel) { serverLevel.getServer().tell(new TickTask(0, () -> { for (Direction side : GTUtil.DIRECTIONS) { - this.sidedRedstoneInput[side.get3DDataValue()] = GTUtil.getRedstonePower(getLevel(), getPos(), side); + this.sidedRedstoneInput[side.get3DDataValue()] = GTUtil.getRedstonePower(getLevel(), getPos(), + side); } })); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index f1df83be2d..1e836b4c63 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -10,10 +10,7 @@ import com.gregtechceu.gtceu.client.particle.HazardParticle; import com.gregtechceu.gtceu.client.renderer.entity.GTBoatRenderer; import com.gregtechceu.gtceu.client.renderer.entity.GTExplosiveRenderer; -import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; -import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; -import com.gregtechceu.gtceu.client.renderer.pipe.PipeModel; -import com.gregtechceu.gtceu.client.renderer.pipe.UnbakedPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.*; import com.gregtechceu.gtceu.common.CommonProxy; import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTEntityTypes; @@ -97,18 +94,12 @@ public void onRegisterParticleProviders(RegisterParticleProvidersEvent event) { @SubscribeEvent public void modifyModels(ModelEvent.ModifyBakingResult event) { - ActivablePipeModel.registerModels(event.getModels()::put); - CableModel.registerModels(event.getModels()::put); - PipeModel.registerModels(event.getModels()::put); - ActivablePipeModel.registerModels(event.getModels()::put); + PipeModelRegistry.registerModels(event.getModels()::put); } @SubscribeEvent public void registerAdditionalModels(ModelEvent.RegisterAdditional event) { - ActivablePipeModel.registerModels((id, $) -> event.register(id)); - CableModel.registerModels((id, $) -> event.register(id)); - PipeModel.registerModels((id, $) -> event.register(id)); - ActivablePipeModel.registerModels((id, $) -> event.register(id)); + PipeModelRegistry.registerModels((id, $) -> event.register(id)); } @SubscribeEvent diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index 059d9d0021..7bb16a8ec0 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -16,10 +16,7 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; @@ -35,24 +32,21 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; -import java.util.Map; @OnlyIn(Dist.CLIENT) -public abstract class AbstractPipeModel implements BakedModel { - - public static final Map> MODELS = new Object2ObjectOpenHashMap<>(); +public abstract class AbstractPipeModel { public static ModelProperty THICKNESS_PROPERTY = new ModelProperty<>(); public static ModelProperty FRAME_MATERIAL_PROPERTY = new ModelProperty<>(); public static ModelProperty FRAME_MASK_PROPERTY = new ModelProperty<>(); + public static ModelProperty CONNECTED_MASK_PROPERTY = new ModelProperty<>(); public static ModelProperty CLOSED_MASK_PROPERTY = new ModelProperty<>(); public static ModelProperty BLOCKED_MASK_PROPERTY = new ModelProperty<>(); @@ -62,20 +56,6 @@ public abstract class AbstractPipeModel implements BakedMode protected final Object2ObjectOpenHashMap frameCache = new Object2ObjectOpenHashMap<>(); protected final Object2ObjectOpenHashMap pipeCache = new Object2ObjectOpenHashMap<>(); - @Getter - private final ModelResourceLocation loc; - - public AbstractPipeModel(ModelResourceLocation loc) { - this.loc = loc; - MODELS.put(loc, this); - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction direction, RandomSource random) { - return List.of(); - } - - @Override public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData modelData, @Nullable RenderType renderType) { @@ -83,7 +63,7 @@ public List getQuads(@Nullable BlockState state, @Nullable Direction ColorData data = computeColorData(modelData); CoverRendererPackage rendererPackage = modelData.get(CoverRendererPackage.PROPERTY); byte coverMask = rendererPackage == null ? 0 : rendererPackage.getMask(); - List quads = getQuads(toKey(modelData), PipeBlock.readConnectionMask(state), + List quads = getQuads(toKey(modelData), safeByte(modelData.get(CONNECTED_MASK_PROPERTY)), safeByte(modelData.get(CLOSED_MASK_PROPERTY)), safeByte(modelData.get(BLOCKED_MASK_PROPERTY)), data, modelData.get(FRAME_MATERIAL_PROPERTY), safeByte(modelData.get(FRAME_MASK_PROPERTY)), coverMask); @@ -167,65 +147,18 @@ public TextureAtlasSprite getParticleTexture(int paintColor, @Nullable Material return spriteInformation.sprite(); } - @Override public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { return getParticleTexture(safeInt(data.get(COLOR_PROPERTY)), data.get(MATERIAL_PROPERTY)); } public abstract SpriteInformation getParticleSprite(@Nullable Material material); - @Override - public boolean useAmbientOcclusion() { - return true; - } - - @Override - public boolean isGui3d() { - return true; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public boolean usesBlockLight() { - return true; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return getParticleSprite(null).sprite(); - } - @Nullable - protected abstract PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, LivingEntity entity); - - @Override - public @NotNull ItemOverrides getOverrides() { - return FakeItemOverrides.INSTANCE; - } + protected abstract PipeItemModel getItemModel(PipeModelRedirector redirector, @NotNull ItemStack stack, + ClientLevel world, LivingEntity entity); - @Override public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) { return ChunkRenderTypeSet.of(RenderType.cutoutMipped()); } - - protected static class FakeItemOverrides extends ItemOverrides { - - public static final FakeItemOverrides INSTANCE = new FakeItemOverrides(); - - @Nullable - @Override - public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel level, - @Nullable LivingEntity entity, int seed) { - if (originalModel instanceof AbstractPipeModel model) { - PipeItemModel item = model.getItemModel(stack, level, entity); - if (item != null) return item; - } - return originalModel; - } - } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java index 241f1a1050..1c92e2da02 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.client.renderer.pipe; -import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; @@ -10,17 +9,14 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ActivableCacheKey; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.client.renderer.pipe.util.TextureInformation; import com.gregtechceu.gtceu.config.ConfigHolder; -import com.gregtechceu.gtceu.utils.SupplierMemoizer; import com.lowdragmc.lowdraglib.client.bakedpipeline.Quad; import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelResourceLocation; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; @@ -32,34 +28,17 @@ import org.jetbrains.annotations.Nullable; import java.util.List; -import java.util.function.BiConsumer; -import java.util.function.Supplier; import java.util.stream.Collectors; @OnlyIn(Dist.CLIENT) public class ActivablePipeModel extends AbstractPipeModel { - private static final ResourceLocation loc = GTCEu.id("pipe_activable"); - public static final ModelProperty ACTIVE_PROPERTY = new ModelProperty<>(); - public static final ActivablePipeModel OPTICAL = new ActivablePipeModel( - GTCEu.id("block/pipe/pipe_optical_in"), - GTCEu.id("block/pipe/pipe_optical_side"), - GTCEu.id("block/pipe/pipe_optical_side_overlay"), - GTCEu.id("block/pipe/pipe_optical_side_overlay_active"), - false, "optical"); - public static final ActivablePipeModel LASER = new ActivablePipeModel( - GTCEu.id("block/pipe/pipe_laser_in"), - GTCEu.id("block/pipe/pipe_laser_side"), - GTCEu.id("block/pipe/pipe_laser_side_overlay"), - GTCEu.id("block/pipe/pipe_laser_side_overlay_emissive"), - true, "laser"); - - private final ResourceLocation inTex; - private final ResourceLocation sideTex; - private final ResourceLocation overlayTex; - private final ResourceLocation overlayActiveTex; + private final TextureInformation inTex; + private final TextureInformation sideTex; + private final TextureInformation overlayTex; + private final TextureInformation overlayActiveTex; private SpriteInformation inSprite; private SpriteInformation sideSprite; @@ -68,12 +47,10 @@ public class ActivablePipeModel extends AbstractPipeModel { private final boolean emissiveActive; - public ActivablePipeModel(@NotNull ResourceLocation inTex, - @NotNull ResourceLocation sideTex, - @NotNull ResourceLocation overlayTex, - @NotNull ResourceLocation overlayActiveTex, boolean emissiveActive, - String variant) { - super(new ModelResourceLocation(loc, variant)); + public ActivablePipeModel(@NotNull TextureInformation inTex, + @NotNull TextureInformation sideTex, + @NotNull TextureInformation overlayTex, + @NotNull TextureInformation overlayActiveTex, boolean emissiveActive) { this.inTex = inTex; this.sideTex = sideTex; this.overlayTex = overlayTex; @@ -116,16 +93,18 @@ public SpriteInformation getParticleSprite(@Nullable Material material) { @Override protected StructureQuadCache constructForKey(ActivableCacheKey key) { if (inSprite == null) { - inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex), -1); + inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex.texture()), inTex.colorID()); } if (sideSprite == null) { - sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex), -1); + sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex.texture()), sideTex.colorID()); } if (overlaySprite == null) { - overlaySprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayTex), 0); + overlaySprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayTex.texture()), + overlayTex.colorID()); } if (overlayActiveSprite == null) { - overlayActiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayActiveTex), 0); + overlayActiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(overlayActiveTex.texture()), + overlayActiveTex.colorID()); } return ActivableSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, sideSprite, @@ -137,16 +116,13 @@ public boolean allowActive() { } @Override - protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, + protected @Nullable PipeItemModel getItemModel(PipeModelRedirector redirector, + @NotNull ItemStack stack, ClientLevel world, LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; - return new PipeItemModel<>(this, new ActivableCacheKey(block.getStructure().getRenderThickness(), false), + return new PipeItemModel<>(redirector, this, + new ActivableCacheKey(block.getStructure().getRenderThickness(), false), new ColorData(PipeBlockEntity.DEFAULT_COLOR)); } - - public static void registerModels(BiConsumer registry) { - registry.accept(OPTICAL.getLoc(), OPTICAL); - registry.accept(LASER.getLoc(), LASER); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java index 67c1ec7ce3..b7e5b136fd 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/CableModel.java @@ -2,8 +2,9 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.client.renderer.pipe.cache.ExtraCappedSQC; import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; @@ -11,14 +12,12 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.client.renderer.pipe.util.TextureInformation; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; @@ -27,50 +26,46 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.function.BiConsumer; - public class CableModel extends AbstractPipeModel { public static final int DEFAULT_INSULATION_COLOR = 0xFF404040; private static final ResourceLocation loc = GTCEu.id("pipe_cable"); - public static final ResourceLocation WIRE = GTCEu.id("block/cable/wire"); - public static final ResourceLocation INSULATION_FULL = GTCEu.id("block/cable/insulation_5"); - - public static final CableModel INSTANCE = new CableModel("wire"); - public static final CableModel[] INSULATED_INSTANCES = new CableModel[5]; + public static final TextureInformation WIRE = new TextureInformation(GTCEu.id("block/cable/wire"), 0); + public static final TextureInformation[] INSULATION = new TextureInformation[5]; + public static final TextureInformation INSULATION_FULL = new TextureInformation( + GTCEu.id("block/cable/insulation_5"), 1); static { - for (int i = 0; i < INSULATED_INSTANCES.length; i++) { - INSULATED_INSTANCES[i] = new CableModel(GTCEu.id("block/cable/insulation_%s".formatted(i)), - INSULATION_FULL, "insulated_" + i); + for (int i = 0; i < INSULATION.length; i++) { + INSULATION[i] = new TextureInformation(GTCEu.id("block/cable/insulation_%s".formatted(i)), 1); } } - private final ResourceLocation wireTex; - private final ResourceLocation insulationTex; - private final ResourceLocation fullInsulationTex; + private final TextureInformation wireTex; + private final TextureInformation insulationTex; + private final TextureInformation fullInsulationTex; + + private final Material material; private SpriteInformation wireSprite; private SpriteInformation insulationSprite; private SpriteInformation fullInsulationSprite; - public CableModel(@NotNull ResourceLocation wireTex, @Nullable ResourceLocation insulationTex, - @Nullable ResourceLocation fullInsulationTex, String variant) { - super(new ModelResourceLocation(loc, variant)); - this.wireTex = wireTex; + public CableModel(@Nullable Material material, @Nullable TextureInformation insulationTex, + @Nullable TextureInformation fullInsulationTex) { + this.material = material; + this.wireTex = material != null ? + new TextureInformation( + MaterialIconType.wire.getBlockTexturePath(material.getMaterialIconSet(), "side", true), 0) : + WIRE; this.insulationTex = insulationTex; this.fullInsulationTex = fullInsulationTex; } - public CableModel(@Nullable ResourceLocation insulationTex, - @Nullable ResourceLocation fullInsulationTex, String variant) { - this(WIRE, insulationTex, fullInsulationTex, variant); - } - - public CableModel(String variant) { - this(null, null, variant); + public CableModel(@NotNull Material material) { + this(material, null, null); } @Override @@ -102,13 +97,15 @@ public SpriteInformation getParticleSprite(@Nullable Material material) { @Override protected StructureQuadCache constructForKey(CacheKey key) { if (fullInsulationSprite == null && fullInsulationTex != null) { - fullInsulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(fullInsulationTex), 1); + fullInsulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(fullInsulationTex.texture()), + fullInsulationTex.colorID()); } if (insulationSprite == null && insulationTex != null) { - insulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(insulationTex), 1); + insulationSprite = new SpriteInformation(ModelFactory.getBlockSprite(insulationTex.texture()), + insulationTex.colorID()); } if (wireSprite == null && wireTex != null) { - wireSprite = new SpriteInformation(ModelFactory.getBlockSprite(wireTex), 0); + wireSprite = new SpriteInformation(ModelFactory.getBlockSprite(wireTex.texture()), wireTex.colorID()); } SpriteInformation sideTex = fullInsulationSprite != null ? fullInsulationSprite : wireSprite; @@ -121,20 +118,13 @@ protected StructureQuadCache constructForKey(CacheKey key) { } @Override - protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, - LivingEntity entity) { + protected @Nullable PipeItemModel getItemModel(PipeModelRedirector redirector, @NotNull ItemStack stack, + ClientLevel world, LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; Material mater = block instanceof PipeMaterialBlock mat ? mat.material : null; - return new PipeItemModel<>(this, new CacheKey(block.getStructure().getRenderThickness()), + return new PipeItemModel<>(redirector, this, new CacheKey(block.getStructure().getRenderThickness()), new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : PipeBlockEntity.DEFAULT_COLOR, DEFAULT_INSULATION_COLOR)); } - - public static void registerModels(BiConsumer registry) { - registry.accept(INSTANCE.getLoc(), INSTANCE); - for (CableModel model : INSULATED_INSTANCES) { - registry.accept(model.getLoc(), model); - } - } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java index 0db0bffbb1..490528a02f 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/DuctPipeModel.java @@ -12,7 +12,6 @@ import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; @@ -33,10 +32,6 @@ public class DuctPipeModel extends AbstractPipeModel { private SpriteInformation sideSprite; private SpriteInformation endSprite; - public DuctPipeModel() { - super(new ModelResourceLocation(loc, "")); - } - @Override protected @NotNull CacheKey toKey(@NotNull ModelData state) { return defaultKey(state); @@ -60,10 +55,11 @@ public SpriteInformation getParticleSprite(@Nullable Material material) { } @Override - protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, - LivingEntity entity) { + protected @Nullable PipeItemModel getItemModel(PipeModelRedirector redirector, @NotNull ItemStack stack, + ClientLevel world, LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; - return new PipeItemModel<>(this, new CacheKey(block.getStructure().getRenderThickness()), new ColorData()); + return new PipeItemModel<>(redirector, this, new CacheKey(block.getStructure().getRenderThickness()), + new ColorData()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java index 200a77d696..bd35330498 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemOverrides; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -11,9 +12,12 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.client.model.IDynamicBakedModel; +import net.minecraftforge.client.model.data.ModelData; import com.mojang.blaze3d.vertex.PoseStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.joml.Quaternionf; import org.joml.Vector3f; @@ -22,9 +26,7 @@ import java.util.List; import java.util.Map; -import javax.annotation.Nullable; - -public class PipeItemModel implements BakedModel { +public class PipeItemModel implements IDynamicBakedModel { private static final Map CAMERA_TRANSFORMS = new HashMap<>(); @@ -49,35 +51,39 @@ private static Quaternionf rotDegrees(float x, float y, float z) { return quatFromXYZDegrees(new Vector3f(x, y, z)); } + private final PipeModelRedirector redirector; private final AbstractPipeModel basis; private final K key; private final ColorData data; - public PipeItemModel(AbstractPipeModel basis, K key, ColorData data) { + public PipeItemModel(PipeModelRedirector redirector, AbstractPipeModel basis, K key, ColorData data) { + this.redirector = redirector; this.basis = basis; this.key = key; this.data = data; } @Override - public @NotNull List getQuads(BlockState state, Direction side, RandomSource rand) { + public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, + @NotNull RandomSource rand, @NotNull ModelData modelData, + @Nullable RenderType renderType) { byte z = 0; return basis.getQuads(key, (byte) 0b1100, z, z, data, null, z, z); } @Override public boolean useAmbientOcclusion() { - return basis.useAmbientOcclusion(); + return redirector.useAmbientOcclusion(); } @Override public boolean isGui3d() { - return basis.isGui3d(); + return redirector.isGui3d(); } @Override public boolean usesBlockLight() { - return basis.usesBlockLight(); + return redirector.usesBlockLight(); } @Override @@ -89,12 +95,12 @@ public boolean isCustomRenderer() { public BakedModel applyTransform(ItemDisplayContext transformType, PoseStack poseStack, boolean applyLeftHandTransform) { poseStack.mulPoseMatrix(CAMERA_TRANSFORMS.get(transformType)); - return BakedModel.super.applyTransform(transformType, poseStack, applyLeftHandTransform); + return this; } @Override public TextureAtlasSprite getParticleIcon() { - return basis.getParticleIcon(); + return redirector.getParticleIcon(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java index de2f7d3dfd..cb3d177b6e 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -2,27 +2,22 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.client.renderer.pipe.cache.BlockableSQC; import com.gregtechceu.gtceu.client.renderer.pipe.cache.RestrictiveSQC; import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; +import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; -import com.gregtechceu.gtceu.client.renderer.pipe.util.PipeSpriteWoodClarifier; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; -import com.gregtechceu.gtceu.client.renderer.pipe.util.WoodCacheKey; +import com.gregtechceu.gtceu.client.renderer.pipe.util.TextureInformation; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelResourceLocation; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; @@ -32,60 +27,32 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.function.BiConsumer; - @OnlyIn(Dist.CLIENT) -public class PipeModel extends AbstractPipeModel { - - private static final ResourceLocation loc = GTCEu.id("pipe_material"); - - public static final PipeModel[] INSTANCES = new PipeModel[7]; - public static final PipeModel[] RESTRICTIVE_INSTANCES = new PipeModel[INSTANCES.length]; - - static { - model(0, wood -> GTCEu.id("block/pipe/pipe_tiny_in")); - model(1, wood -> wood ? GTCEu.id("block/pipe/pipe_small_in_wood") : GTCEu.id("block/pipe/pipe_small_in")); - model(2, wood -> wood ? GTCEu.id("block/pipe/pipe_normal_in_wood") : GTCEu.id("block/pipe/pipe_normal_in")); - model(3, wood -> wood ? GTCEu.id("block/pipe/pipe_large_in_wood") : GTCEu.id("block/pipe/pipe_large_in")); - model(4, wood -> GTCEu.id("block/pipe/pipe_huge_in")); - model(5, wood -> GTCEu.id("block/pipe/pipe_quadruple_in")); - model(6, wood -> GTCEu.id("block/pipe/pipe_nonuple_in")); - } - - private static void model(int i, PipeSpriteWoodClarifier clarifier) { - INSTANCES[i] = new PipeModel(clarifier, false, i + "_standard"); - RESTRICTIVE_INSTANCES[i] = new PipeModel(clarifier, true, i + "_restrictive"); - } +public class PipeModel extends AbstractPipeModel { - private final @NotNull PipeSpriteWoodClarifier inTex; - private final @NotNull PipeSpriteWoodClarifier sideTex; - private final @Nullable PipeSpriteWoodClarifier restrictiveTex; - private final @NotNull PipeSpriteWoodClarifier blockedTex; + private final @NotNull TextureInformation inTex; + private final @NotNull TextureInformation sideTex; + private final @Nullable TextureInformation restrictiveTex; + private final @NotNull TextureInformation blockedTex; private SpriteInformation inSprite; private SpriteInformation sideSprite; private SpriteInformation restrictiveSprite; private SpriteInformation blockedSprite; - public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, @NotNull PipeSpriteWoodClarifier sideTex, - @Nullable PipeSpriteWoodClarifier restrictiveTex, - @NotNull PipeSpriteWoodClarifier blockedTex, String variant) { - super(new ModelResourceLocation(loc, variant)); + public PipeModel(@NotNull TextureInformation inTex, @NotNull TextureInformation sideTex, + @Nullable TextureInformation restrictiveTex, + @NotNull TextureInformation blockedTex) { this.inTex = inTex; this.sideTex = sideTex; this.restrictiveTex = restrictiveTex; this.blockedTex = blockedTex; } - public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, @NotNull PipeSpriteWoodClarifier sideTex, - boolean restrictive, String variant) { - this(inTex, sideTex, restrictive ? wood -> GTCEu.id("block/pipe/pipe_restrictive") : null, - wood -> GTCEu.id("block/pipe/pipe_blocked"), variant); - } - - public PipeModel(@NotNull PipeSpriteWoodClarifier inTex, boolean restrictive, String variant) { - this(inTex, wood -> wood ? GTCEu.id("block/pipe/pipe_side_wood") : GTCEu.id("block/pipe/pipe_side"), - restrictive, variant); + public PipeModel(@NotNull TextureInformation inTex, @NotNull TextureInformation sideTex, + boolean restrictive) { + this(inTex, sideTex, restrictive ? new TextureInformation(GTCEu.id("block/pipe/pipe_restrictive"), -1) : null, + new TextureInformation(GTCEu.id("block/pipe/pipe_blocked"), -1)); } @Override @@ -94,60 +61,45 @@ public SpriteInformation getParticleSprite(@Nullable Material material) { } @Override - public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { - return getParticleSprite(null).sprite(); - } - - @Override - protected @NotNull WoodCacheKey toKey(@NotNull ModelData state) { - return WoodCacheKey.of(state.get(THICKNESS_PROPERTY), state.get(MATERIAL_PROPERTY)); + protected @NotNull CacheKey toKey(@NotNull ModelData data) { + return defaultKey(data); } @Override - protected StructureQuadCache constructForKey(WoodCacheKey key) { + protected StructureQuadCache constructForKey(CacheKey key) { if (inSprite == null) { - inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex.getTexture(key.isWood())), 0); + inSprite = new SpriteInformation(ModelFactory.getBlockSprite(inTex.texture()), inTex.colorID()); } if (sideSprite == null) { - sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex.getTexture(key.isWood())), 0); + sideSprite = new SpriteInformation(ModelFactory.getBlockSprite(sideTex.texture()), sideTex.colorID()); } if (restrictiveSprite == null && restrictiveTex != null) { - restrictiveSprite = new SpriteInformation( - ModelFactory.getBlockSprite(restrictiveTex.getTexture(key.isWood())), -1); + restrictiveSprite = new SpriteInformation(ModelFactory.getBlockSprite(restrictiveTex.texture()), + restrictiveTex.colorID()); } if (blockedSprite == null) { - blockedSprite = new SpriteInformation(ModelFactory.getBlockSprite(blockedTex.getTexture(key.isWood())), -1); + blockedSprite = new SpriteInformation(ModelFactory.getBlockSprite(blockedTex.texture()), + blockedTex.colorID()); } if (restrictiveTex != null) { - return RestrictiveSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, - sideSprite, blockedSprite, - restrictiveSprite); + return RestrictiveSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, sideSprite, + blockedSprite, restrictiveSprite); } else { - return BlockableSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, - sideSprite, blockedSprite); + return BlockableSQC.create(PipeQuadHelper.create(key.getThickness()), inSprite, sideSprite, + blockedSprite); } } @Override - protected @Nullable PipeItemModel getItemModel(@NotNull ItemStack stack, ClientLevel world, - LivingEntity entity) { + @Nullable + protected PipeItemModel getItemModel(PipeModelRedirector redirector, @NotNull ItemStack stack, + ClientLevel world, LivingEntity entity) { PipeBlock block = PipeBlock.getBlockFromItem(stack); if (block == null) return null; - Material mater = null; - boolean wood = block instanceof PipeMaterialBlock mat && (mater = mat.material) != null && - mater.hasProperty(PropertyKey.WOOD); - return new PipeItemModel<>(this, new WoodCacheKey(block.getStructure().getRenderThickness(), wood), + Material mater = block instanceof PipeMaterialBlock matBlock ? matBlock.material : null; + return new PipeItemModel<>(redirector, this, new CacheKey(block.getStructure().getRenderThickness()), new ColorData(mater != null ? GTUtil.convertRGBtoARGB(mater.getMaterialRGB()) : PipeBlockEntity.DEFAULT_COLOR)); } - - public static void registerModels(BiConsumer registry) { - for (PipeModel model : INSTANCES) { - registry.accept(model.getLoc(), model); - } - for (PipeModel model : RESTRICTIVE_INSTANCES) { - registry.accept(model.getLoc(), model); - } - } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java new file mode 100644 index 0000000000..f924794f21 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java @@ -0,0 +1,124 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.client.renderer.pipe.util.MaterialModelSupplier; + +import com.lowdragmc.lowdraglib.client.model.ModelFactory; + +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.client.model.data.ModelData; + +import lombok.Getter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.function.Function; + +public class PipeModelRedirector implements BakedModel { + + private final boolean ambientOcclusion; + private final boolean gui3d; + + public final MaterialModelSupplier supplier; + public final Function stackMaterialFunction; + + @Getter + private final ModelResourceLocation loc; + + private final FakeItemOverrides fakeItemOverrideList = new FakeItemOverrides(); + + public PipeModelRedirector(ModelResourceLocation loc, MaterialModelSupplier supplier, + Function stackMaterialFunction) { + this(loc, supplier, stackMaterialFunction, true, true); + } + + public PipeModelRedirector(ModelResourceLocation loc, MaterialModelSupplier supplier, + Function stackMaterialFunction, + boolean ambientOcclusion, boolean gui3d) { + this.loc = loc; + this.supplier = supplier; + this.stackMaterialFunction = stackMaterialFunction; + this.ambientOcclusion = ambientOcclusion; + this.gui3d = gui3d; + + PipeModelRegistry.MODELS.put(loc, this); + } + + @Override + public List getQuads(@Nullable BlockState state, @Nullable Direction direction, RandomSource random) { + return List.of(); + } + + @Override + public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, + @NotNull RandomSource rand, @NotNull ModelData data, + @Nullable RenderType renderType) { + Material mat = data.get(AbstractPipeModel.MATERIAL_PROPERTY); + return supplier.getModel(mat).getQuads(state, side, rand, data, renderType); + } + + @Override + public boolean useAmbientOcclusion() { + return ambientOcclusion; + } + + @Override + public boolean isGui3d() { + return gui3d; + } + + @Override + public boolean usesBlockLight() { + return false; + } + + @Override + public boolean isCustomRenderer() { + return false; + } + + @Override + public TextureAtlasSprite getParticleIcon() { + return ModelFactory.getBlockSprite(GTCEu.id("block/cable/wire")); + } + + @Override + public @NotNull ItemOverrides getOverrides() { + return fakeItemOverrideList; + } + + @FunctionalInterface + public interface Supplier { + + PipeModelRedirector create(ModelResourceLocation loc, MaterialModelSupplier supplier, + Function stackMaterialFunction); + } + + protected class FakeItemOverrides extends ItemOverrides { + + @Nullable + @Override + public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel level, + @Nullable LivingEntity entity, int seed) { + if (originalModel instanceof PipeModelRedirector model) { + PipeItemModel item = model.supplier.getModel(model.stackMaterialFunction.apply(stack)) + .getItemModel(PipeModelRedirector.this, stack, level, entity); + if (item != null) return item; + } + return originalModel; + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java new file mode 100644 index 0000000000..57742ca990 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -0,0 +1,261 @@ +package com.gregtechceu.gtceu.client.renderer.pipe; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.client.renderer.pipe.util.MaterialModelOverride; +import com.gregtechceu.gtceu.client.renderer.pipe.util.MaterialModelSupplier; +import com.gregtechceu.gtceu.client.renderer.pipe.util.TextureInformation; + +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.resources.ResourceLocation; + +import com.google.common.collect.Tables; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Range; + +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.function.BiConsumer; + +public final class PipeModelRegistry { + + public static final Map MODELS = new HashMap<>(); + + public static final int PIPE_MODEL_COUNT = 7; + private static final Object2ObjectOpenHashMap PIPE = new Object2ObjectOpenHashMap<>(); + private static final PipeModelRedirector[] PIPE_MODELS = new PipeModelRedirector[PIPE_MODEL_COUNT]; + private static final ObjectLinkedOpenHashSet> PIPE_OVERRIDES = new ObjectLinkedOpenHashSet<>(); + private static final Object2ObjectOpenHashMap PIPE_RESTRICTIVE = new Object2ObjectOpenHashMap<>(); + private static final PipeModelRedirector[] PIPE_RESTRICTIVE_MODELS = new PipeModelRedirector[PIPE_MODEL_COUNT]; + private static final ObjectLinkedOpenHashSet> PIPE_RESTRICTIVE_OVERRIDES = new ObjectLinkedOpenHashSet<>(); + + public static final int CABLE_MODEL_COUNT = 6; + private static final Object2ObjectOpenHashMap CABLE = new Object2ObjectOpenHashMap<>(); + private static final PipeModelRedirector[] CABLE_MODELS = new PipeModelRedirector[CABLE_MODEL_COUNT]; + private static final ObjectLinkedOpenHashSet> CABLE_OVERRIDES = new ObjectLinkedOpenHashSet<>(); + + private static final ActivablePipeModel OPTICAL; + private static final PipeModelRedirector OPTICAL_MODEL; + + private static final ActivablePipeModel LASER; + private static final PipeModelRedirector LASER_MODEL; + + private static final DuctPipeModel DUCT; + private static final PipeModelRedirector DUCT_MODEL; + + static { + initPipes(); + initCables(); + ResourceLocation loc = GTCEu.id("block/pipe_activable"); + OPTICAL = new ActivablePipeModel( + new TextureInformation(GTCEu.id("block/pipe/pipe_optical_in"), -1), + new TextureInformation(GTCEu.id("block/pipe/pipe_optical_side"), -1), + new TextureInformation(GTCEu.id("block/pipe/pipe_optical_side_overlay"), 0), + new TextureInformation(GTCEu.id("block/pipe/pipe_optical_side_overlay_active"), 0), + false); + OPTICAL_MODEL = new PipeModelRedirector(new ModelResourceLocation(loc, "optical"), m -> OPTICAL, s -> null); + LASER = new ActivablePipeModel( + new TextureInformation(GTCEu.id("block/pipe/pipe_laser_in"), -1), + new TextureInformation(GTCEu.id("block/pipe/pipe_laser_side"), -1), + new TextureInformation(GTCEu.id("block/pipe/pipe_laser_side_overlay"), 0), + new TextureInformation(GTCEu.id("block/pipe/pipe_laser_side_overlay_emissive"), 0), + true); + LASER_MODEL = new PipeModelRedirector(new ModelResourceLocation(loc, "laser"), m -> LASER, s -> null); + DUCT = new DuctPipeModel(); + DUCT_MODEL = new PipeModelRedirector(new ModelResourceLocation(GTCEu.id("block/pipe_duct"), ""), m -> DUCT, + s -> null); + } + + public static void registerPipeOverride(@NotNull MaterialModelOverride override) { + PIPE_OVERRIDES.addAndMoveToFirst(override); + PIPE.clear(); + PIPE.trim(16); + } + + public static void registerPipeRestrictiveOverride(@NotNull MaterialModelOverride override) { + PIPE_RESTRICTIVE_OVERRIDES.addAndMoveToFirst(override); + PIPE_RESTRICTIVE.clear(); + PIPE_RESTRICTIVE.trim(16); + } + + public static void registerCableOverride(@NotNull MaterialModelOverride override) { + CABLE_OVERRIDES.addAndMoveToFirst(override); + CABLE.clear(); + CABLE.trim(16); + } + + public static PipeModelRedirector getPipeModel(@Range(from = 0, to = PIPE_MODEL_COUNT - 1) int i) { + return PIPE_MODELS[i]; + } + + public static PipeModelRedirector getPipeRestrictiveModel(@Range(from = 0, to = PIPE_MODEL_COUNT - 1) int i) { + return PIPE_RESTRICTIVE_MODELS[i]; + } + + public static PipeModelRedirector getCableModel(@Range(from = 0, to = CABLE_MODEL_COUNT - 1) int i) { + return CABLE_MODELS[i]; + } + + public static PipeModelRedirector getOpticalModel() { + return OPTICAL_MODEL; + } + + public static PipeModelRedirector getLaserModel() { + return LASER_MODEL; + } + + public static PipeModelRedirector getDuctModel() { + return DUCT_MODEL; + } + + public static void registerModels(@NotNull BiConsumer registry) { + for (PipeModelRedirector redirector : PIPE_MODELS) { + registry.accept(redirector.getLoc(), redirector); + } + for (PipeModelRedirector redirector : PIPE_RESTRICTIVE_MODELS) { + registry.accept(redirector.getLoc(), redirector); + } + for (PipeModelRedirector redirector : CABLE_MODELS) { + registry.accept(redirector.getLoc(), redirector); + } + registry.accept(OPTICAL_MODEL.getLoc(), OPTICAL_MODEL); + registry.accept(LASER_MODEL.getLoc(), LASER_MODEL); + } + + public static PipeModelRedirector materialModel(@NotNull ResourceLocation loc, MaterialModelSupplier supplier, + @NotNull String variant, + PipeModelRedirector.@NotNull Supplier redirectorSupplier) { + return redirectorSupplier.create(new ModelResourceLocation(loc, variant), supplier, + stack -> { + PipeMaterialBlock pipe = PipeMaterialBlock.getBlockFromItem(stack); + if (pipe == null) return null; + else return pipe.material; + }); + } + + public static PipeModelRedirector materialModel(@NotNull ResourceLocation loc, MaterialModelSupplier supplier, + @NotNull String variant) { + return new PipeModelRedirector(new ModelResourceLocation(loc, variant), supplier, + stack -> { + PipeMaterialBlock pipe = PipeMaterialBlock.getBlockFromItem(stack); + if (pipe == null) return null; + else return pipe.material; + }); + } + + private static void initPipes() { + TextureInformation pipeTiny = new TextureInformation(GTCEu.id("block/pipe/pipe_tiny_in"), 0); + TextureInformation pipeSmall = new TextureInformation(GTCEu.id("block/pipe/pipe_small_in"), 0); + TextureInformation pipeNormal = new TextureInformation(GTCEu.id("block/pipe/pipe_normal_in"), 0); + TextureInformation pipeLarge = new TextureInformation(GTCEu.id("block/pipe/pipe_large_in"), 0); + TextureInformation pipeHuge = new TextureInformation(GTCEu.id("block/pipe/pipe_huge_in"), 0); + TextureInformation pipeQuadruple = new TextureInformation(GTCEu.id("block/pipe/pipe_quadruple_in"), 0); + TextureInformation pipeNonuple = new TextureInformation(GTCEu.id("block/pipe/pipe_nonuple_in"), 0); + TextureInformation pipeSide = new TextureInformation(GTCEu.id("block/pipe/pipe_side"), 0); + + TextureInformation pipeSmallWood = new TextureInformation(GTCEu.id("block/pipe/pipe_small_in_wood"), 0); + TextureInformation pipeNormalWood = new TextureInformation(GTCEu.id("block/pipe/pipe_normal_in_wood"), 0); + TextureInformation pipeLargeWood = new TextureInformation(GTCEu.id("block/pipe/pipe_large_in_wood"), 0); + TextureInformation pipeSideWood = new TextureInformation(GTCEu.id("block/pipe/pipe_side_wood"), 0); + + PipeModel[] array = new PipeModel[PIPE_MODEL_COUNT]; + // standard + array[0] = new PipeModel(pipeTiny, pipeSide, false); + array[1] = new PipeModel(pipeSmall, pipeSide, false); + array[2] = new PipeModel(pipeNormal, pipeSide, false); + array[3] = new PipeModel(pipeLarge, pipeSide, false); + array[4] = new PipeModel(pipeHuge, pipeSide, false); + array[5] = new PipeModel(pipeQuadruple, pipeSide, false); + array[6] = new PipeModel(pipeNonuple, pipeSide, false); + PIPE_OVERRIDES.add(new MaterialModelOverride.StandardOverride<>(array, m -> true)); + + array = new PipeModel[PIPE_MODEL_COUNT]; + array[1] = new PipeModel(pipeSmallWood, pipeSideWood, false); + array[2] = new PipeModel(pipeNormalWood, pipeSideWood, false); + array[3] = new PipeModel(pipeLargeWood, pipeSideWood, false); + registerPipeOverride(new MaterialModelOverride.StandardOverride<>(array, m -> m.hasProperty(PropertyKey.WOOD))); + + array = new PipeModel[PIPE_MODEL_COUNT]; + array[0] = new PipeModel(pipeTiny, pipeSide, true); + array[1] = new PipeModel(pipeSmall, pipeSide, true); + array[2] = new PipeModel(pipeNormal, pipeSide, true); + array[3] = new PipeModel(pipeLarge, pipeSide, true); + array[4] = new PipeModel(pipeHuge, pipeSide, true); + array[5] = new PipeModel(pipeQuadruple, pipeSide, true); + array[6] = new PipeModel(pipeNonuple, pipeSide, true); + PIPE_RESTRICTIVE_OVERRIDES.add(new MaterialModelOverride.StandardOverride<>(array, m -> true)); + + ResourceLocation loc = GTCEu.id("block/pipe_material"); + for (int i = 0; i < PIPE_MODEL_COUNT; i++) { + int finalI = i; + PIPE_MODELS[i] = materialModel(loc, m -> getOrCachePipeModel(m, finalI), String.valueOf(i)); + PIPE_RESTRICTIVE_MODELS[i] = materialModel(loc, m -> getOrCachePipeRestrictiveModel(m, finalI), + "restrictive_" + i); + } + } + + private static PipeModel getOrCachePipeModel(Material m, int i) { + if (m == null) return PIPE_OVERRIDES.last().getModel(null, i); + PipeModel[] cached = PIPE.computeIfAbsent(m, k -> new PipeModel[PIPE_MODEL_COUNT]); + PipeModel selected = cached[i]; + if (selected == null) { + for (MaterialModelOverride override : PIPE_OVERRIDES) { + selected = override.getModel(m, i); + if (selected != null) break; + } + cached[i] = selected; + } + return selected; + } + + private static PipeModel getOrCachePipeRestrictiveModel(Material m, int i) { + if (m == null) return PIPE_RESTRICTIVE_OVERRIDES.last().getModel(null, i); + PipeModel[] cached = PIPE_RESTRICTIVE.computeIfAbsent(m, k -> new PipeModel[PIPE_MODEL_COUNT]); + PipeModel selected = cached[i]; + if (selected == null) { + for (MaterialModelOverride override : PIPE_RESTRICTIVE_OVERRIDES) { + selected = override.getModel(m, i); + if (selected != null) break; + } + cached[i] = selected; + } + return selected; + } + + private static void initCables() { + CABLE_OVERRIDES.add(new MaterialModelOverride.PerMaterialOverride<>( + Tables.newCustomTable(new IdentityHashMap<>(), Int2ObjectOpenHashMap::new), (material, insulation) -> { + if (insulation == 0) { + return new CableModel(material); + } + return new CableModel(material, CableModel.INSULATION[insulation - 1], CableModel.INSULATION_FULL); + }, m -> true)); + + ResourceLocation loc = GTCEu.id("block/cable"); + for (int i = 0; i < CABLE_MODEL_COUNT; i++) { + int finalI = i; + CABLE_MODELS[i] = materialModel(loc, m -> getOrCacheCableModel(m, finalI), String.valueOf(i)); + } + } + + private static CableModel getOrCacheCableModel(Material m, int i) { + if (m == null) return CABLE_OVERRIDES.last().getModel(null, i); + CableModel[] cached = CABLE.computeIfAbsent(m, k -> new CableModel[CABLE_MODEL_COUNT]); + CableModel selected = cached[i]; + if (selected == null) { + for (MaterialModelOverride override : CABLE_OVERRIDES) { + selected = override.getModel(m, i); + if (selected != null) break; + } + cached[i] = selected; + } + return selected; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java index 0a1bd1e8eb..eb2d081151 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/UnbakedPipeModel.java @@ -19,7 +19,7 @@ @RequiredArgsConstructor public class UnbakedPipeModel implements IUnbakedGeometry { - private final AbstractPipeModel model; + private final PipeModelRedirector model; @Override public BakedModel bake(IGeometryBakingContext iGeometryBakingContext, ModelBaker baker, @@ -43,7 +43,7 @@ public UnbakedPipeModel read(JsonObject jsonObject, String[] id = GsonHelper.getAsString(jsonObject, "model_id").split("#"); ResourceLocation modelId = new ModelResourceLocation(new ResourceLocation(id[0]), id.length > 1 ? id[1] : ""); - return new UnbakedPipeModel(AbstractPipeModel.MODELS.get(modelId)); + return new UnbakedPipeModel(PipeModelRegistry.MODELS.get(modelId)); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java index bee31876be..e7bd5a29fa 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -11,8 +11,8 @@ import net.minecraft.world.phys.AABB; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; - import net.minecraftforge.client.model.ForgeFaceData; + import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Contract; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java index aaf4c78d4e..3a3f0c8f67 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java @@ -8,15 +8,13 @@ import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.IQuadTransformer; +import net.minecraftforge.client.model.QuadTransformers; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormatElement; -import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; -import net.minecraftforge.client.model.QuadTransformers; import static net.minecraftforge.client.model.IQuadTransformer.*; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java new file mode 100644 index 0000000000..403e49ea2f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java @@ -0,0 +1,45 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; + +import com.google.common.collect.Table; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.BiFunction; +import java.util.function.Predicate; + +public interface MaterialModelOverride> { + + @Nullable + T getModel(Material material, int i); + + record StandardOverride>(@NotNull T[] models, + @NotNull Predicate predicate) + implements MaterialModelOverride { + + @Override + public @Nullable T getModel(Material material, int i) { + if (material == null || !predicate.test(material)) return null; + else return models[i]; + } + } + + record PerMaterialOverride>(@NotNull Table models, + @NotNull BiFunction createFunction, + @NotNull Predicate predicate) + implements MaterialModelOverride { + + @Override + public @Nullable T getModel(Material material, int i) { + if (material == null || !predicate.test(material)) return null; + if (!models.contains(material, i)) { + T model = createFunction.apply(material, i); + models.put(material, i, model); + return model; + } + return models.get(material, i); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelSupplier.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelSupplier.java new file mode 100644 index 0000000000..70407ff13a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelSupplier.java @@ -0,0 +1,14 @@ +package com.gregtechceu.gtceu.client.renderer.pipe.util; + +import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@FunctionalInterface +public interface MaterialModelSupplier { + + @NotNull + AbstractPipeModel getModel(@Nullable Material material); +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/PipeSpriteWoodClarifier.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/TextureInformation.java similarity index 61% rename from src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/PipeSpriteWoodClarifier.java rename to src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/TextureInformation.java index 3c1c14133c..74fdc58750 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/PipeSpriteWoodClarifier.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/TextureInformation.java @@ -5,8 +5,9 @@ import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) -@FunctionalInterface -public interface PipeSpriteWoodClarifier { +public record TextureInformation(ResourceLocation texture, int colorID) { - ResourceLocation getTexture(boolean isWoodVariant); + public boolean colorable() { + return colorID >= 0; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java deleted file mode 100644 index fd39953ecf..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/WoodCacheKey.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.pipe.util; - -import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Objects; - -public class WoodCacheKey extends CacheKey { - - private final boolean wood; - - public WoodCacheKey(float thickness, boolean wood) { - super(thickness); - this.wood = wood; - } - - public static WoodCacheKey of(@Nullable Float thickness, @Nullable Boolean wood) { - float thick = thickness == null ? 0.5f : thickness; - boolean wd = wood != null && wood; - return new WoodCacheKey(thick, wd); - } - - public static WoodCacheKey of(@Nullable Float thickness, @Nullable Material material) { - float thick = thickness == null ? 0.5f : thickness; - boolean wood = material != null && material.hasProperty(PropertyKey.WOOD); - return new WoodCacheKey(thick, wood); - } - - public boolean isWood() { - return wood; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj == null || obj.getClass() != this.getClass()) return false; - var that = (WoodCacheKey) obj; - return Float.floatToIntBits(thickness) == Float.floatToIntBits(thickness) && - this.wood == that.wood; - } - - @Override - protected int computeHash() { - return Objects.hash(thickness, wood); - } - - @Override - public @NotNull String getSerializedName() { - return super.getSerializedName() + wood; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java b/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java index 4b00e82348..653858b3fb 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/EffectRenderContext.java @@ -53,7 +53,8 @@ public static EffectRenderContext getInstance() { private float rotationXZ; @NotNull - public EffectRenderContext update(@NotNull Entity renderViewEntity, Camera camera, Frustum frustum, float partialTicks) { + public EffectRenderContext update(@NotNull Entity renderViewEntity, Camera camera, Frustum frustum, + float partialTicks) { this.renderViewEntity = renderViewEntity; this.partialTicks = partialTicks; diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java index ee976b0566..ac5189d994 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/RenderBufferHelper.java @@ -130,7 +130,8 @@ public static void renderCubeFrame(BufferBuilder buffer, double minX, double min buffer.vertex(minX, maxY, maxZ).color(r, g, b, a).endVertex(); } - public static void renderCubeFace(PoseStack poseStack, VertexConsumer buffer, AABB cuboid, float r, float g, float b, float a, + public static void renderCubeFace(PoseStack poseStack, VertexConsumer buffer, AABB cuboid, float r, float g, + float b, float a, boolean shade) { renderCubeFace(poseStack, buffer, (float) cuboid.minX, (float) cuboid.minY, (float) cuboid.minZ, diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java index e3730a65e4..a41554a9d9 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; + import com.lowdragmc.lowdraglib.client.bakedpipeline.FaceQuad; import net.minecraft.client.renderer.FaceInfo; @@ -135,15 +136,15 @@ public static BakedQuad bakeQuad( } public static RecolorableBakedQuad bakeRecolorableQuad( - Vector3f posFrom, - Vector3f posTo, - BlockElementFace face, - SpriteInformation sprite, - Direction facing, - ModelState transform, - @Nullable BlockElementRotation partRotation, - boolean shade, - int emissivity) { + Vector3f posFrom, + Vector3f posTo, + BlockElementFace face, + SpriteInformation sprite, + Direction facing, + ModelState transform, + @Nullable BlockElementRotation partRotation, + boolean shade, + int emissivity) { BlockFaceUV blockfaceuv = face.uv; if (transform.isUvLocked()) { blockfaceuv = recomputeUVs(face.uv, facing, transform.getRotation()); @@ -158,7 +159,8 @@ public static RecolorableBakedQuad bakeRecolorableQuad( blockfaceuv.uvs[2] = Mth.lerp(f, blockfaceuv.uvs[2], f1); blockfaceuv.uvs[1] = Mth.lerp(f, blockfaceuv.uvs[1], f2); blockfaceuv.uvs[3] = Mth.lerp(f, blockfaceuv.uvs[3], f2); - int[] aint = makeVertices(blockfaceuv, sprite.sprite(), facing, setupShape(posFrom, posTo), transform.getRotation(), + int[] aint = makeVertices(blockfaceuv, sprite.sprite(), facing, setupShape(posFrom, posTo), + transform.getRotation(), partRotation, shade); Direction direction = calculateFacing(aint); System.arraycopy(afloat, 0, blockfaceuv.uvs, 0, afloat.length); @@ -168,7 +170,8 @@ public static RecolorableBakedQuad bakeRecolorableQuad( ForgeHooksClient.fillNormal(aint, direction); ForgeFaceData data = face.getFaceData(); - RecolorableBakedQuad quad = new RecolorableBakedQuad(aint, face.tintIndex, direction, sprite, shade, data.ambientOcclusion()); + RecolorableBakedQuad quad = new RecolorableBakedQuad(aint, face.tintIndex, direction, sprite, shade, + data.ambientOcclusion()); if (!ForgeFaceData.DEFAULT.equals(data)) { QuadTransformers.applyingLightmap(data.blockLight(), data.skyLight()).processInPlace(quad); QuadTransformers.applyingColor(data.color()).processInPlace(quad); @@ -393,7 +396,7 @@ private static void recalculateWinding(int[] vertices, Direction direction) { float nX = Float.intBitsToFloat(newVertices[l]); float xY = Float.intBitsToFloat(newVertices[l + 1]); float nZ = Float.intBitsToFloat(newVertices[l + 2]); - //noinspection SuspiciousNameCombination + // noinspection SuspiciousNameCombination if (Mth.equal(x, nX) && Mth.equal(y, xY) && Mth.equal(z, nZ)) { vertices[j1 + 4] = newVertices[l + 4]; vertices[j1 + 4 + 1] = newVertices[l + 4 + 1]; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index 342949b936..65208ff9b8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.common.data; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.ActivablePipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.blockentity.*; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index 93d544141f..57d76f90f5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -5,56 +5,44 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; -import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.function.Consumer; - public record CableStructure(String name, int material, int costFactor, TagPrefix prefix, @Nullable CableStructure partialBurnStructure, @Nullable Integer partialBurnThreshold, - float renderThickness, AbstractPipeModel model) + float renderThickness, PipeModelRedirector model) implements IPipeMaterialStructure, IInsulatable { public static final int INSULATION_BURN_TEMP = 1000; public static final CableStructure WIRE_SINGLE = new CableStructure("single_wire", 1, 2, TagPrefix.wireGtSingle, - null, null, 0.125f, CableModel.INSTANCE); + null, null, 0.125f, PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_DOUBLE = new CableStructure("double_wire", 2, 2, TagPrefix.wireGtDouble, - null, null, 0.25f, CableModel.INSTANCE); + null, null, 0.25f, PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_QUADRUPLE = new CableStructure("quadruple_wire", 4, 3, - TagPrefix.wireGtQuadruple, null, null, 0.375f, CableModel.INSTANCE); + TagPrefix.wireGtQuadruple, null, null, 0.375f, PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_OCTAL = new CableStructure("octal_wire", 8, 3, TagPrefix.wireGtOctal, null, - null, 0.5f, CableModel.INSTANCE); + null, 0.5f, PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_HEX = new CableStructure("hex_wire", 16, 3, TagPrefix.wireGtHex, null, null, - 0.75f, CableModel.INSTANCE); + 0.75f, PipeModelRegistry.getCableModel(0)); public static final CableStructure CABLE_SINGLE = new CableStructure("single_cable", 1, 1, TagPrefix.cableGtSingle, - WIRE_SINGLE, INSULATION_BURN_TEMP, 0.25f, CableModel.INSULATED_INSTANCES[0]); + WIRE_SINGLE, INSULATION_BURN_TEMP, 0.25f, PipeModelRegistry.getCableModel(1)); public static final CableStructure CABLE_DOUBLE = new CableStructure("double_cable", 2, 1, TagPrefix.cableGtDouble, - WIRE_DOUBLE, INSULATION_BURN_TEMP, 0.375f, CableModel.INSULATED_INSTANCES[1]); + WIRE_DOUBLE, INSULATION_BURN_TEMP, 0.375f, PipeModelRegistry.getCableModel(2)); public static final CableStructure CABLE_QUADRUPLE = new CableStructure("quadruple_cable", 4, 1, - TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, CableModel.INSULATED_INSTANCES[2]); + TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, PipeModelRegistry.getCableModel(3)); public static final CableStructure CABLE_OCTAL = new CableStructure("octal_cable", 8, 1, TagPrefix.cableGtOctal, - WIRE_OCTAL, INSULATION_BURN_TEMP, 0.75f, CableModel.INSULATED_INSTANCES[3]); + WIRE_OCTAL, INSULATION_BURN_TEMP, 0.75f, PipeModelRegistry.getCableModel(4)); public static final CableStructure CABLE_HEX = new CableStructure("hex_cable", 16, 1, TagPrefix.cableGtHex, - WIRE_HEX, INSULATION_BURN_TEMP, 1f, CableModel.INSULATED_INSTANCES[4]); + WIRE_HEX, INSULATION_BURN_TEMP, 1f, PipeModelRegistry.getCableModel(5)); - public CableStructure(String name, int material, int costFactor, TagPrefix prefix, - @Nullable CableStructure partialBurnStructure, @Nullable Integer partialBurnThreshold, - float renderThickness, AbstractPipeModel model) { - this.name = name; - this.material = material; - this.costFactor = costFactor; - this.prefix = prefix; - this.partialBurnStructure = partialBurnStructure; - this.partialBurnThreshold = partialBurnThreshold; - this.renderThickness = renderThickness; - this.model = model; + public CableStructure { PipeStructureRegistry.register(this); } @@ -73,11 +61,6 @@ public float getRenderThickness() { return renderThickness; } - @Override - public AbstractPipeModel getModel() { - return model; - } - @Override public ResourceTexture getPipeTexture(boolean isBlock) { return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; @@ -93,16 +76,8 @@ public boolean isInsulated() { return partialBurnStructure != null; } - public static void registerDefaultStructures(Consumer register) { - register.accept(WIRE_SINGLE); - register.accept(WIRE_DOUBLE); - register.accept(WIRE_QUADRUPLE); - register.accept(WIRE_OCTAL); - register.accept(WIRE_HEX); - register.accept(CABLE_SINGLE); - register.accept(CABLE_DOUBLE); - register.accept(CABLE_QUADRUPLE); - register.accept(CABLE_OCTAL); - register.accept(CABLE_HEX); + @Override + public PipeModelRedirector getModel() { + return model; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java index 35064c06d5..6a2ae71189 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -2,13 +2,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; -import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; -import com.gregtechceu.gtceu.client.renderer.pipe.DuctPipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; import org.jetbrains.annotations.NotNull; -import java.util.function.Consumer; - public record DuctStructure(String name, float renderThickness, float rateMultiplier) implements IPipeStructure { public static final DuctStructure SMALL = new DuctStructure("small", 0.375f, 2f); @@ -36,14 +34,7 @@ public boolean isPaintable() { } @Override - public AbstractPipeModel getModel() { - return DuctPipeModel.INSTANCE; - } - - public static void registerDefaultStructures(Consumer register) { - register.accept(SMALL); - register.accept(NORMAL); - register.accept(LARGE); - register.accept(HUGE); + public PipeModelRedirector getModel() { + return PipeModelRegistry.getDuctModel(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java index 3501c59f35..20f4713507 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -3,30 +3,25 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; -import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; + import net.minecraft.core.Direction; import org.jetbrains.annotations.NotNull; -import java.util.function.Consumer; - -public record LaserStructure(String name, float renderThickness, boolean mirror, ActivablePipeModel model) +public record LaserStructure(String name, float renderThickness, boolean mirror, PipeModelRedirector model) implements IPipeStructure { public static final LaserStructure NORMAL = new LaserStructure("laser_pipe_normal", 0.375f, - false, ActivablePipeModel.LASER); + false, PipeModelRegistry.getLaserModel()); public static final LaserStructure MIRROR = new LaserStructure("laser_pipe_mirror", 0.5f, - true, ActivablePipeModel.LASER); + true, PipeModelRegistry.getLaserModel()); - public LaserStructure(String name, float renderThickness, boolean mirror, ActivablePipeModel model) { - this.name = name; - this.renderThickness = renderThickness; - this.mirror = mirror; - this.model = model; + public LaserStructure { PipeStructureRegistry.register(this); } @@ -74,11 +69,7 @@ public boolean isPaintable() { } @Override - public AbstractPipeModel getModel() { + public PipeModelRedirector getModel() { return model; } - - public static void registerDefaultStructures(Consumer register) { - register.accept(NORMAL); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java index 3836561e03..dcc46d47b0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -3,26 +3,23 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; -import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; -import com.gregtechceu.gtceu.client.renderer.pipe.ActivablePipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; + import net.minecraft.core.Direction; import org.jetbrains.annotations.NotNull; -import java.util.function.Consumer; - -public record OpticalStructure(String name, float renderThickness, ActivablePipeModel model) implements IPipeStructure { +public record OpticalStructure(String name, float renderThickness, PipeModelRedirector model) + implements IPipeStructure { public static final OpticalStructure INSTANCE = new OpticalStructure("optical_pipe_normal", 0.375f, - ActivablePipeModel.OPTICAL); + PipeModelRegistry.getOpticalModel()); - public OpticalStructure(String name, float renderThickness, ActivablePipeModel model) { - this.name = name; - this.renderThickness = renderThickness; - this.model = model; + public OpticalStructure { PipeStructureRegistry.register(this); } @@ -60,11 +57,7 @@ public boolean isPaintable() { } @Override - public AbstractPipeModel getModel() { + public PipeModelRedirector getModel() { return model; } - - public static void registerDefaultStructures(Consumer register) { - register.accept(INSTANCE); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java index 37592987a3..7ed02d226b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -3,8 +3,8 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; - import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; + import net.minecraft.world.level.block.state.BlockBehaviour; public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, IFreezable { @@ -12,4 +12,9 @@ public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, I public MaterialPipeBlock(BlockBehaviour.Properties properties, MaterialPipeStructure structure, Material material) { super(properties, structure, material); } + + @Override + public MaterialPipeStructure getStructure() { + return (MaterialPipeStructure) super.getStructure(); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java index 2d81c55601..d22e559607 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -4,72 +4,50 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeChanneledStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; -import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; -import com.gregtechceu.gtceu.client.renderer.pipe.PipeModel; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; +import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; import org.jetbrains.annotations.NotNull; -import java.util.function.Consumer; - public record MaterialPipeStructure(String name, int material, int channelCount, boolean restrictive, TagPrefix prefix, - float renderThickness, PipeModel model) + float renderThickness, PipeModelRedirector model) implements IPipeMaterialStructure, IPipeChanneledStructure { public static final MaterialPipeStructure TINY = new MaterialPipeStructure("tiny", 1, 1, false, - TagPrefix.pipeTiny, 0.25f, - PipeModel.INSTANCES[0]); + TagPrefix.pipeTiny, 0.25f, PipeModelRegistry.getPipeModel(0)); public static final MaterialPipeStructure SMALL = new MaterialPipeStructure("small", 2, 1, false, - TagPrefix.pipeSmall, 0.375f, - PipeModel.INSTANCES[1]); + TagPrefix.pipeSmall, 0.375f, PipeModelRegistry.getPipeModel(1)); public static final MaterialPipeStructure NORMAL = new MaterialPipeStructure("normal", 6, 1, false, - TagPrefix.pipeNormal, 0.5f, - PipeModel.INSTANCES[2]); + TagPrefix.pipeNormal, 0.5f, PipeModelRegistry.getPipeModel(2)); public static final MaterialPipeStructure LARGE = new MaterialPipeStructure("large", 12, 1, false, - TagPrefix.pipeLarge, 0.75f, - PipeModel.INSTANCES[3]); + TagPrefix.pipeLarge, 0.75f, PipeModelRegistry.getPipeModel(3)); public static final MaterialPipeStructure HUGE = new MaterialPipeStructure("huge", 24, 1, false, - TagPrefix.pipeHuge, 0.875f, - PipeModel.INSTANCES[4]); + TagPrefix.pipeHuge, 0.875f, PipeModelRegistry.getPipeModel(4)); public static final MaterialPipeStructure QUADRUPLE = new MaterialPipeStructure("quadruple", 8, 4, false, - TagPrefix.pipeQuadruple, - 0.95f, PipeModel.INSTANCES[5]); + TagPrefix.pipeQuadruple, 0.95f, PipeModelRegistry.getPipeModel(5)); public static final MaterialPipeStructure NONUPLE = new MaterialPipeStructure("nonuple", 18, 9, false, - TagPrefix.pipeNonuple, 0.95f, - PipeModel.INSTANCES[6]); + TagPrefix.pipeNonuple, 0.95f, PipeModelRegistry.getPipeModel(6)); public static final MaterialPipeStructure TINY_RESTRICTIVE = new MaterialPipeStructure("tiny_restrictive", 1, - 1, true, - TagPrefix.pipeTinyRestrictive, 0.25f, PipeModel.RESTRICTIVE_INSTANCES[0]); + 1, true, TagPrefix.pipeTinyRestrictive, 0.25f, PipeModelRegistry.getPipeRestrictiveModel(0)); public static final MaterialPipeStructure SMALL_RESTRICTIVE = new MaterialPipeStructure("small_restrictive", 2, - 1, true, - TagPrefix.pipeSmallRestrictive, 0.375f, PipeModel.RESTRICTIVE_INSTANCES[1]); + 1, true, TagPrefix.pipeSmallRestrictive, 0.375f, PipeModelRegistry.getPipeRestrictiveModel(1)); public static final MaterialPipeStructure NORMAL_RESTRICTIVE = new MaterialPipeStructure("normal_restrictive", - 6, 1, true, - TagPrefix.pipeNormalRestrictive, 0.5f, PipeModel.RESTRICTIVE_INSTANCES[2]); + 6, 1, true, TagPrefix.pipeNormalRestrictive, 0.5f, PipeModelRegistry.getPipeRestrictiveModel(2)); public static final MaterialPipeStructure LARGE_RESTRICTIVE = new MaterialPipeStructure("large_restrictive", - 12, 1, true, - TagPrefix.pipeLargeRestrictive, 0.75f, PipeModel.RESTRICTIVE_INSTANCES[3]); + 12, 1, true, TagPrefix.pipeLargeRestrictive, 0.75f, PipeModelRegistry.getPipeRestrictiveModel(3)); public static final MaterialPipeStructure HUGE_RESTRICTIVE = new MaterialPipeStructure("huge_restrictive", 24, - 1, true, - TagPrefix.pipeHugeRestrictive, 0.875f, PipeModel.RESTRICTIVE_INSTANCES[4]); + 1, true, TagPrefix.pipeHugeRestrictive, 0.875f, PipeModelRegistry.getPipeRestrictiveModel(4)); public static final MaterialPipeStructure QUADRUPLE_RESTRICTIVE = new MaterialPipeStructure( - "quadruple_restrictive", 8, 4, true, - TagPrefix.pipeQuadrupleRestrictive, 0.95f, PipeModel.RESTRICTIVE_INSTANCES[5]); + "quadruple_restrictive", 8, 4, true, TagPrefix.pipeQuadrupleRestrictive, 0.95f, + PipeModelRegistry.getPipeRestrictiveModel(5)); public static final MaterialPipeStructure NONUPLE_RESTRICTIVE = new MaterialPipeStructure( - "nonuple_restrictive", 18, 9, true, - TagPrefix.pipeNonupleRestrictive, 0.95f, PipeModel.RESTRICTIVE_INSTANCES[6]); + "nonuple_restrictive", 18, 9, true, TagPrefix.pipeNonupleRestrictive, 0.95f, + PipeModelRegistry.getPipeRestrictiveModel(6)); - public MaterialPipeStructure(String name, int material, int channelCount, boolean restrictive, TagPrefix prefix, - float renderThickness, PipeModel model) { - this.name = name; - this.material = material; - this.channelCount = channelCount; - this.restrictive = restrictive; - this.prefix = prefix; - this.renderThickness = renderThickness; - this.model = model; + public MaterialPipeStructure { PipeStructureRegistry.register(this); } @@ -94,7 +72,7 @@ public int getChannelCount() { } @Override - public AbstractPipeModel getModel() { + public PipeModelRedirector getModel() { return model; } @@ -102,21 +80,4 @@ public AbstractPipeModel getModel() { public boolean isPaintable() { return true; } - - public static void registerDefaultStructures(Consumer register) { - register.accept(TINY); - register.accept(SMALL); - register.accept(NORMAL); - register.accept(LARGE); - register.accept(HUGE); - register.accept(QUADRUPLE); - register.accept(NONUPLE); - register.accept(TINY_RESTRICTIVE); - register.accept(SMALL_RESTRICTIVE); - register.accept(NORMAL_RESTRICTIVE); - register.accept(LARGE_RESTRICTIVE); - register.accept(HUGE_RESTRICTIVE); - register.accept(QUADRUPLE_RESTRICTIVE); - register.accept(NONUPLE_RESTRICTIVE); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java index f3f9731458..2940ae45bd 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/DummyMachineBlockEntity.java @@ -12,11 +12,11 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import com.google.common.collect.Table; import it.unimi.dsi.fastutil.ints.Int2LongFunction; import lombok.Getter; -import net.minecraft.world.level.block.Block; import java.util.List; From c965fe0561c333073fb80f38272e513e0e166e77 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 25 Aug 2024 18:42:54 +0300 Subject: [PATCH 20/70] it works :yippee: --- .../blockentity/NeighborCacheBlockEntity.java | 1 + ...numLossFunction.java => LossFunction.java} | 14 ++-- .../logic/TemperatureLossFunction.java | 18 ++--- .../pipenet/physical/block/PipeBlock.java | 53 +-------------- .../physical/tile/PipeBlockEntity.java | 31 +++++---- .../client/particle/GTOverheatParticle.java | 3 +- .../renderer/pipe/AbstractPipeModel.java | 1 - .../gtceu/common/data/GTBlocks.java | 9 +-- .../gtceu/common/data/GTModels.java | 22 ------- .../common/item/PortableScannerBehavior.java | 65 +++++++++++++++++-- .../pipelike/block/cable/CableBlock.java | 9 +-- .../net/energy/EnergyCapabilityObject.java | 19 +++--- .../gtceu/data/lang/LangHandler.java | 1 + 13 files changed, 110 insertions(+), 136 deletions(-) rename src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/{EnumLossFunction.java => LossFunction.java} (85%) diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java index 46942cd200..37470ed282 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/NeighborCacheBlockEntity.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.blockentity; import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAutoPersistBlockEntity; import com.lowdragmc.lowdraglib.syncdata.blockentity.IRPCBlockEntity; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EnumLossFunction.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/LossFunction.java similarity index 85% rename from src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EnumLossFunction.java rename to src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/LossFunction.java index 86799b9058..817537b717 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EnumLossFunction.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/LossFunction.java @@ -4,7 +4,7 @@ * A bunch of loss functions. By the power of Wolfram Alpha. * Demonstration Graph */ -public enum EnumLossFunction { +public enum LossFunction { // DO NOT REORDER FUNCTIONS, THE ORDER IS USED FOR NBT SERIALIZATION /** @@ -25,7 +25,7 @@ public float applyLoss(float value, float factorX, float factorY, int timePassed /** * x% of value is lost every tick. *
- * Faster than {@link EnumLossFunction#ARITHMETIC} at large values, but slower at small values. + * Faster than {@link LossFunction#ARITHMETIC} at large values, but slower at small values. */ GEOMETRIC { @@ -38,7 +38,7 @@ public float applyLoss(float value, float factorX, float factorY, int timePassed /** * value is raised to the power of 1 - x every tick. *
- * Faster than {@link EnumLossFunction#GEOMETRIC} at large values, but incredibly slow at small values. + * Faster than {@link LossFunction#GEOMETRIC} at large values, but incredibly slow at small values. */ POWER { @@ -52,8 +52,8 @@ public float applyLoss(float value, float factorX, float factorY, int timePassed /** * x% of value is lost, then y more, every tick. *
- * Slightly faster than {@link EnumLossFunction#GEOMETRIC} at large values, - * slightly faster than {@link EnumLossFunction#ARITHMETIC} at small values. + * Slightly faster than {@link LossFunction#GEOMETRIC} at large values, + * slightly faster than {@link LossFunction#ARITHMETIC} at small values. */ GEOMETRIC_ARITHMETIC { @@ -73,8 +73,8 @@ public float applyLoss(float value, float factorX, float factorY, int timePassed /** * value is raised to the power of 1 - x, then y% more is lost, every tick. *
- * Slightly faster than {@link EnumLossFunction#POWER} at large values, - * slightly faster than {@link EnumLossFunction#GEOMETRIC} at small values. + * Slightly faster than {@link LossFunction#POWER} at large values, + * slightly faster than {@link LossFunction#GEOMETRIC} at small values. */ POWER_GEOMETRIC { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java index 8f421395ba..f9596d0c0f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLossFunction.java @@ -1,28 +1,28 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; import com.lowdragmc.lowdraglib.networking.IPacket; +import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.common.util.INBTSerializable; import it.unimi.dsi.fastutil.floats.Float2ObjectArrayMap; -public class TemperatureLossFunction implements INBTSerializable, IPacket { +public class TemperatureLossFunction implements ITagSerializable, IPacket { private static final Float2ObjectArrayMap CABLE_LOSS_CACHE = new Float2ObjectArrayMap<>(); private static final Float2ObjectArrayMap PIPE_LOSS_CACHE = new Float2ObjectArrayMap<>(); - private EnumLossFunction function; + private LossFunction function; private float factorX; private float factorY; - public TemperatureLossFunction(EnumLossFunction function, float factorX) { + public TemperatureLossFunction(LossFunction function, float factorX) { this.function = function; this.factorX = factorX; } - public TemperatureLossFunction(EnumLossFunction function, float factorX, float factorY) { + public TemperatureLossFunction(LossFunction function, float factorX, float factorY) { this.function = function; this.factorX = factorX; this.factorY = factorY; @@ -41,7 +41,7 @@ public float restoreTemperature(float energy, int timePassed) { public static TemperatureLossFunction getOrCreateCable(float factor) { TemperatureLossFunction function = CABLE_LOSS_CACHE.get(factor); if (function == null) { - function = new TemperatureLossFunction(EnumLossFunction.WEAK_SCALING, factor, 0.35f); + function = new TemperatureLossFunction(LossFunction.WEAK_SCALING, factor, 0.35f); CABLE_LOSS_CACHE.put(factor, function); } return function; @@ -51,7 +51,7 @@ public static TemperatureLossFunction getOrCreatePipe(float factor) { TemperatureLossFunction function = PIPE_LOSS_CACHE.get(factor); if (function == null) { // since pipes are hollow the exponent is larger - function = new TemperatureLossFunction(EnumLossFunction.WEAK_SCALING, factor, 0.45f); + function = new TemperatureLossFunction(LossFunction.WEAK_SCALING, factor, 0.45f); PIPE_LOSS_CACHE.put(factor, function); } return function; @@ -68,7 +68,7 @@ public CompoundTag serializeNBT() { @Override public void deserializeNBT(CompoundTag nbt) { - function = EnumLossFunction.values()[nbt.getInt("Ordinal")]; + function = LossFunction.values()[nbt.getInt("Ordinal")]; factorX = nbt.getFloat("X"); factorY = nbt.getFloat("Y"); } @@ -82,7 +82,7 @@ public void encode(FriendlyByteBuf buf) { @Override public void decode(FriendlyByteBuf buf) { - function = EnumLossFunction.values()[buf.readVarInt()]; + function = LossFunction.values()[buf.readVarInt()]; factorX = buf.readFloat(); factorY = buf.readFloat(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index c5c934cc59..5092039120 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -48,8 +48,6 @@ import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; @@ -71,28 +69,6 @@ public abstract class PipeBlock extends Block implements EntityBlock { - public static final BooleanProperty NORTH = BlockStateProperties.NORTH; - public static final BooleanProperty EAST = BlockStateProperties.EAST; - public static final BooleanProperty SOUTH = BlockStateProperties.SOUTH; - public static final BooleanProperty WEST = BlockStateProperties.WEST; - public static final BooleanProperty UP = BlockStateProperties.UP; - public static final BooleanProperty DOWN = BlockStateProperties.DOWN; - - public static final EnumMap FACINGS = buildFacings(); - - private static @NotNull EnumMap buildFacings() { - EnumMap map = new EnumMap<>(Direction.class); - map.put(Direction.NORTH, NORTH); - map.put(Direction.EAST, EAST); - map.put(Direction.SOUTH, SOUTH); - map.put(Direction.WEST, WEST); - map.put(Direction.UP, UP); - map.put(Direction.DOWN, DOWN); - return map; - } - - public static final BooleanProperty FRAMED = BooleanProperty.create("framed"); - // do not touch these two unless you know what you are doing protected final ThreadLocal lastTilePos = ThreadLocal.withInitial(() -> new BlockPos(0, 0, 0)); protected final ThreadLocal> lastTile = ThreadLocal @@ -104,15 +80,7 @@ public abstract class PipeBlock extends Block implements EntityBlock { public PipeBlock(BlockBehaviour.Properties properties, IPipeStructure structure) { super(properties); this.structure = structure; - this.registerDefaultState(this.defaultBlockState() - .setValue(NORTH, false) - .setValue(EAST, false) - .setValue(SOUTH, false) - .setValue(WEST, false) - .setValue(UP, false) - .setValue(DOWN, false) - .setValue(FRAMED, false) - .setValue(SERVER_TICK, false)); + this.registerDefaultState(this.defaultBlockState().setValue(SERVER_TICK, false)); } // net logic // @@ -516,7 +484,7 @@ public GTToolType getToolClass() { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(NORTH, SOUTH, EAST, WEST, UP, DOWN, FRAMED, SERVER_TICK); + builder.add(SERVER_TICK); } @Override @@ -528,23 +496,6 @@ public boolean triggerEvent(BlockState pState, Level pLevel, BlockPos pPos, int return false; } - public static BlockState writeConnectionMask(@NotNull BlockState state, byte connectionMask) { - for (Direction facing : GTUtil.DIRECTIONS) { - state = state.setValue(FACINGS.get(facing), GTUtil.evalMask(facing, connectionMask)); - } - return state; - } - - public static byte readConnectionMask(@NotNull BlockState state) { - byte mask = 0; - for (Direction facing : GTUtil.DIRECTIONS) { - if (state.getValue(FACINGS.get(facing))) { - mask |= (byte) (1 << facing.ordinal()); - } - } - return mask; - } - // tile entity // @Nullable diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 6925d7c988..1615ec1aeb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -31,6 +31,8 @@ import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.utils.GTUtil; +import com.gregtechceu.gtceu.utils.TaskHandler; +import com.gregtechceu.gtceu.utils.TaskScheduler; import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; @@ -221,14 +223,14 @@ public void setConnected(Direction facing, boolean renderClosed) { } else { this.renderMask &= ~(1 << facing.ordinal()); } - getLevel().setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FACINGS.get(facing), true)); + scheduleRenderUpdate(); } public void setDisconnected(Direction facing) { this.connectionMask &= ~(1 << facing.ordinal()); this.renderMask &= ~(1 << facing.ordinal()); updateActiveStatus(facing, false); - getLevel().setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FACINGS.get(facing), false)); + scheduleRenderUpdate(); } public boolean isConnected(Direction side) { @@ -261,11 +263,6 @@ public boolean isBlocked(Direction facing) { public void setFrameMaterial(@Nullable Material frameMaterial) { this.frameMaterial = frameMaterial; - if (frameMaterial != null) { - level.setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FRAMED, true)); - } else { - level.setBlockAndUpdate(getBlockPos(), getBlockState().setValue(PipeBlock.FRAMED, false)); - } scheduleRenderUpdate(); } @@ -340,8 +337,8 @@ public final void serverTick() { } @Override - public void onLoad() { - super.onLoad(); + public void clearRemoved() { + super.clearRemoved(); if (getLevel() instanceof ServerLevel serverLevel) { serverLevel.getServer().tell(new TickTask(0, this::initialize)); } @@ -519,6 +516,11 @@ protected void initialize() { })); this.listeners.add(listener); node.getData().addListener(listener); + // Manually resync the data, as it's loaded & the listeners are queried for the first time *before* + // we call `addListener` on the line above. + for (var entry : node.getData().getEntries()) { + node.getData().markLogicEntryAsUpdated(entry, true); + } if (firstNode) { firstNode = false; this.temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); @@ -531,6 +533,7 @@ protected void initialize() { } } + /* @Override public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { buf.writeVarInt(netLogicDatas.size()); @@ -554,6 +557,7 @@ public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { } scheduleRenderUpdate(); } + */ @Override public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { @@ -581,11 +585,7 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { NetLogicEntry entry = data.getLogicEntryNullable(identifier); if (entry != null) entry.decode(buf, false); data.markLogicEntryAsUpdated(entry, false); - } else { - // FIXME fix the issue that causes 4 bytes from the server to not be read correctly. - buf.readerIndex(buf.writerIndex()); - return; - } + } else return; } if (identifier.equals(TemperatureLogic.INSTANCE.getSerializedName())) { TemperatureLogic tempLogic = this.netLogicDatas.get(networkID) @@ -595,8 +595,6 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { } } } - // FIXME fix the issue that causes 4 bytes from the server to not be read correctly. - buf.readerIndex(buf.writerIndex()); } // particle // @@ -689,6 +687,7 @@ public void markAsDirty() { } return ModelData.builder() .with(AbstractPipeModel.THICKNESS_PROPERTY, this.getStructure().getRenderThickness()) + .with(AbstractPipeModel.CONNECTED_MASK_PROPERTY, connectionMask) .with(AbstractPipeModel.CLOSED_MASK_PROPERTY, renderMask) .with(AbstractPipeModel.BLOCKED_MASK_PROPERTY, blockedMask) .with(AbstractPipeModel.COLOR_PROPERTY, getPaintingColor()) diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java index 16de1a4e27..afa2e5d9b4 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java @@ -14,6 +14,7 @@ import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.shimmer.client.shader.RenderUtils; +import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.phys.AABB; @@ -171,7 +172,7 @@ public GTOverheatParticle(@NotNull PipeBlockEntity tileEntity, @NotNull Temperat } private int getTemperature() { - long tick = Platform.getMinecraftServer().getTickCount(); + long tick = Minecraft.getInstance().levelRenderer.getTicks(); return temperatureLogic.getTemperature(tick); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index 7bb16a8ec0..c353743686 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.client.renderer.pipe.cache.ColorQuadCache; import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 9ea0fbd34f..048bacbadf 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -311,11 +311,7 @@ private static void generateCableBlocks() { private static boolean allowCableBlock(Material material, CableStructure insulation) { if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES)) { - return material.getProperty(PropertyKey.PIPENET_PROPERTIES).hasProperty(MaterialEnergyProperties.KEY) && - !insulation.prefix().isIgnored(material) && - !(insulation.isInsulated() && material.getProperty(PropertyKey.PIPENET_PROPERTIES) - .getProperty(MaterialEnergyProperties.KEY) - .isSuperconductor()); + return material.getProperty(PropertyKey.PIPENET_PROPERTIES).generatesStructure(insulation); } return false; } @@ -357,7 +353,8 @@ private static void generateMaterialPipeBlocks() { } private static boolean allowMaterialPipeBlock(Material material, MaterialPipeStructure fluidPipeType) { - return material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && !fluidPipeType.prefix().isIgnored(material); + return material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && + material.getProperty(PropertyKey.PIPENET_PROPERTIES).generatesStructure(fluidPipeType); } private static void registerMaterialPipeBlock(Material material, MaterialPipeStructure pipeType, diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java index 21bf6a026f..3670f522c3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java @@ -14,7 +14,6 @@ import com.gregtechceu.gtceu.api.fluids.store.FluidStorage; import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKey; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.common.block.LampBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; @@ -467,27 +466,6 @@ public static void registerPipeModels() { private static void createPipeBlockState(ResourceLocation blockId, ResourceLocation blockModelId, Block block) { Variant variant = Variant.variant().with(VariantProperties.MODEL, blockModelId); GTDynamicResourcePack.addBlockState(blockId, MultiVariantGenerator.multiVariant(block) - .with(PropertyDispatch.property(PipeBlock.NORTH) - .select(true, variant) - .select(false, variant)) - .with(PropertyDispatch.property(PipeBlock.SOUTH) - .select(true, variant) - .select(false, variant)) - .with(PropertyDispatch.property(PipeBlock.WEST) - .select(true, variant) - .select(false, variant)) - .with(PropertyDispatch.property(PipeBlock.EAST) - .select(true, variant) - .select(false, variant)) - .with(PropertyDispatch.property(PipeBlock.UP) - .select(true, variant) - .select(false, variant)) - .with(PropertyDispatch.property(PipeBlock.DOWN) - .select(true, variant) - .select(false, variant)) - .with(PropertyDispatch.property(PipeBlock.FRAMED) - .select(true, variant) - .select(false, variant)) .with(PropertyDispatch.property(BlockProperties.SERVER_TICK) .select(true, variant) .select(false, variant))); diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index b43600aa2d..6abd197153 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -8,6 +8,8 @@ import com.gregtechceu.gtceu.api.capability.IWorkable; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.data.worldgen.bedrockfluid.BedrockFluidVeinSavedData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.component.IAddInformation; import com.gregtechceu.gtceu.api.item.component.IInteractionItem; @@ -22,9 +24,13 @@ import com.gregtechceu.gtceu.common.capability.EnvironmentalHazardSavedData; import com.gregtechceu.gtceu.common.capability.LocalizedHazardSavedData; import com.gregtechceu.gtceu.common.data.GTSoundEntries; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowData; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.WorldEnergyNet; import com.gregtechceu.gtceu.utils.FormattingUtil; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.Platform; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -360,20 +366,67 @@ else if (machine instanceof IDataInfoProvider) } } else if (tileEntity instanceof PipeBlockEntity pipe) { - // Pipes need special name handling list.add(pipe.getBlockType().getName().withStyle(ChatFormatting.BLUE)); + if (mode == DisplayMode.SHOW_ALL || mode == DisplayMode.SHOW_ELECTRICAL_INFO) { + if (level instanceof ServerLevel serverLevel) { + NetLogicData data = pipe.getNetLogicData(WorldEnergyNet.getWorldNet(serverLevel).getNetworkID()); + if (data != null) { + int cumulativeCount = 0; + long cumulativeVoltage = 0; + long cumulativeAmperage = 0; + for (var memory : data.getLogicEntryDefaultable(EnergyFlowLogic.INSTANCE).getMemory().entrySet()) { + cumulativeCount++; + int count = 0; + double voltage = 0; + long amperage = 0; + for (EnergyFlowData flow : memory.getValue()) { + count++; + long prev = amperage; + amperage += flow.amperage(); + // weighted average + voltage = voltage * prev / amperage + (double) (flow.voltage() * flow.amperage()) / amperage; + } + if (count != 0) { + cumulativeVoltage += voltage / count; + cumulativeAmperage += amperage / count; + } + } + if (cumulativeCount != 0) { + cumulativeVoltage /= cumulativeCount; + cumulativeAmperage /= cumulativeCount; + } + list.add(Component.translatable("behavior.portable_scanner.divider")); + list.add(Component.translatable("behavior.portable_scanner.eu_per_sec", + Component.translatable(FormattingUtil.formatNumbers(cumulativeVoltage)) + .withStyle(ChatFormatting.RED))); + list.add(Component.translatable("behavior.portable_scanner.amp_per_sec", + Component.translatable(FormattingUtil.formatNumbers(cumulativeAmperage)) + .withStyle(ChatFormatting.RED))); + + long tick = Platform.getMinecraftServer().getTickCount(); + int temp = data.getLogicEntryDefaultable(TemperatureLogic.INSTANCE).getTemperature(tick); + list.add(Component.translatable("behavior.portable_scanner.temperature", + Component.translatable(FormattingUtil.formatNumbers(temp)) + .withStyle(ChatFormatting.RED))); + + } + } + } + + if (mode == DisplayMode.SHOW_ALL || mode == DisplayMode.SHOW_BLOCK_INFO) { + if (tileEntity.getCapability(ForgeCapabilities.FLUID_HANDLER).isPresent()) { + // Getting fluid info always costs 500 + energyCost += 500; + } + } + // Pipe-specific info if (tileEntity instanceof IDataInfoProvider dataInfoProvider) { list.add(Component.translatable("behavior.portable_scanner.divider")); list.addAll(dataInfoProvider.getDataInfo(mode)); } - - if (tileEntity.getCapability(ForgeCapabilities.FLUID_HANDLER).isPresent()) { - // Getting fluid info always costs 500 - energyCost += 500; - } } else if (tileEntity instanceof IDataInfoProvider dataInfoProvider) { list.add(Component.translatable("behavior.portable_scanner.divider")); list.addAll(dataInfoProvider.getDataInfo(mode)); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index 0432ced2a1..67c8203c42 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -59,14 +59,7 @@ protected String getConnectLangKey() { public void partialBurn(BlockState state, Level world, BlockPos pos) { CableStructure structure = getStructure(); if (structure.partialBurnStructure() != null) { - CableBlock newBlock = CACHE.get(material).get(structure.partialBurnStructure()); - BlockState newState = newBlock.defaultBlockState() - .setValue(NORTH, state.getValue(NORTH)) - .setValue(EAST, state.getValue(EAST)) - .setValue(SOUTH, state.getValue(SOUTH)) - .setValue(WEST, state.getValue(WEST)) - .setValue(UP, state.getValue(UP)) - .setValue(DOWN, state.getValue(DOWN)); + BlockState newState = CACHE.get(material).get(structure.partialBurnStructure()).defaultBlockState(); world.setBlockAndUpdate(pos, newState); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java index 65f3639710..319678eb61 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java @@ -74,15 +74,16 @@ public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, long tick = Platform.getMinecraftServer().getTickCount(); AbstractNetFlowEdge internalBuffer = this.internalBuffers.get(side); - if (internalBuffer != null) { - long limit = internalBuffer.getFlowLimit(IPredicateTestObject.INSTANCE, net, tick, simulator); - if (limit <= 0) { - this.transferring = false; - return 0; - } else if (amperage > limit) { - amperage = limit; - } - } + // Disable this as it broke overamping + //if (internalBuffer != null) { + // long limit = internalBuffer.getFlowLimit(IPredicateTestObject.INSTANCE, net, tick, simulator); + // if (limit <= 0) { + // this.transferring = false; + // return 0; + // } else if (amperage > limit) { + // amperage = limit; + // } + //} long availableAmperage = amperage; EnergyTraverseData data = new EnergyTraverseData(net, IPredicateTestObject.INSTANCE, simulator, tick, voltage, diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java index 430b0055ca..121f3b1a32 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java @@ -769,6 +769,7 @@ public static void init(RegistrateLangProvider provider) { provider.add("behavior.portable_scanner.energy_container_storage", "Energy: %s EU / %s EU"); provider.add("behavior.portable_scanner.eu_per_sec", "Average (last second): %s EU/t"); provider.add("behavior.portable_scanner.amp_per_sec", "Average (last second): %s A"); + provider.add("behavior.portable_scanner.temperature", "Temperature: %sK"); provider.add("behavior.portable_scanner.machine_disabled", "Disabled."); provider.add("behavior.portable_scanner.machine_front_facing", "Front Facing: %s"); provider.add("behavior.portable_scanner.machine_ownership", "§2Machine Owner Type: %s§r"); From bae0f374a1c34b46a928519fd37ce65d201eb0f3 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 25 Aug 2024 19:30:47 +0300 Subject: [PATCH 21/70] datagen --- .../resources/assets/gtceu/lang/en_ud.json | 37 ++++++++++--------- .../resources/assets/gtceu/lang/en_us.json | 37 ++++++++++--------- .../tags/blocks/mineable/wire_cutter.json | 4 +- ...normal_laser_pipe.json => laser_pipe.json} | 4 +- ...cal_pipe.json => optical_fiber_cable.json} | 4 +- .../pipenet/physical/block/PipeBlock.java | 5 +-- .../physical/tile/PipeBlockEntity.java | 1 - .../multiblock/electric/CleanroomMachine.java | 2 +- .../gtceu/data/lang/LangHandler.java | 4 +- 9 files changed, 49 insertions(+), 49 deletions(-) rename src/generated/resources/data/gtceu/loot_tables/blocks/{normal_laser_pipe.json => laser_pipe.json} (75%) rename src/generated/resources/data/gtceu/loot_tables/blocks/{normal_optical_pipe.json => optical_fiber_cable.json} (74%) diff --git a/src/generated/resources/assets/gtceu/lang/en_ud.json b/src/generated/resources/assets/gtceu/lang/en_ud.json index 2b901d21ea..3a55a5b225 100644 --- a/src/generated/resources/assets/gtceu/lang/en_ud.json +++ b/src/generated/resources/assets/gtceu/lang/en_ud.json @@ -49,6 +49,7 @@ "behavior.portable_scanner.state": "%s :%s", "behavior.portable_scanner.tank": "%s ᗺɯ %s / ᗺɯ %s :%s ʞuɐ⟘", "behavior.portable_scanner.tanks_empty": "ʎʇdɯƎ sʞuɐ⟘ ןןⱯ", + "behavior.portable_scanner.temperature": "ʞ%s :ǝɹnʇɐɹǝdɯǝ⟘", "behavior.portable_scanner.team_name": "ɹ§%s :ǝɯɐN ɯɐǝ⟘ᄅ§", "behavior.portable_scanner.workable_consumption": "Ɐ %s ʇɐ ʇ/∩Ǝ %s :sǝs∩ ʎןqɐqoɹԀ", "behavior.portable_scanner.workable_production": "Ɐ %s ʇɐ ʇ/∩Ǝ %s :sǝɔnpoɹԀ ʎןqɐqoɹԀ", @@ -541,6 +542,7 @@ "block.gtceu.large_solidifier": "ʎɐɹɹⱯ uoıʇɐɔıɟıpıןoS ǝbɹɐꞀ", "block.gtceu.large_wiremill": "ʎɹoʇɔɐℲ ǝɹıM ǝbɹɐꞀ", "block.gtceu.laser_hazard_sign_block": "ʞɔoןᗺ ubıS pɹɐzɐH ɹǝsɐꞀ", + "block.gtceu.laser_pipe": "ǝdıԀ ɹǝsɐꞀ", "block.gtceu.laser_safe_engraving_casing": "buısɐƆ buıʌɐɹbuƎ ǝɟɐS-ɹǝsɐꞀ", "block.gtceu.light_blue_borderless_lamp": "dɯɐꞀ ssǝןɹǝpɹoᗺ ǝnןᗺ ʇɥbıꞀ", "block.gtceu.light_blue_lamp": "dɯɐꞀ ǝnןᗺ ʇɥbıꞀ", @@ -913,14 +915,13 @@ "block.gtceu.noise_hazard_sign_block": "ʞɔoןᗺ ubıS pɹɐzɐH ǝsıoN", "block.gtceu.nonconducting_casing": "buısɐƆ buıʇɔnpuoɔuoN", "block.gtceu.normal_duct_pipe": "ǝdıԀ ʇɔnᗡ ןɐɯɹoN", - "block.gtceu.normal_laser_pipe": "ǝdıԀ ɹǝsɐꞀ ןɐɯɹoN", "block.gtceu.normal_laser_pipe.tooltip": "sǝuıן ʇɥbıɐɹʇs uı ㄥ§ssoן ouɟ§ ɥʇıʍ ɹǝʍod buıʇʇıɯsuɐɹ⟘ㄥ§", - "block.gtceu.normal_optical_pipe": "ǝןqɐƆ ɹǝqıℲ ןɐɔıʇdO", "block.gtceu.normal_optical_pipe.tooltip": "ㄥ§ɐʇɐᗡ ɥɔɹɐǝsǝᴚɟ§ ɹo ㄥ§uoıʇɐʇndɯoƆɟ§ buıʇʇıɯsuɐɹ⟘ㄥ§", "block.gtceu.object_holder": "ɹǝpןoH ʇɔǝظqO", "block.gtceu.oil_heavy": "ןıO ʎʌɐǝH", "block.gtceu.oil_light": "ןıO ʇɥbıꞀ", "block.gtceu.oil_medium": "ןıO ʍɐᴚ", + "block.gtceu.optical_fiber_cable": "ǝןqɐƆ ɹǝqıℲ ןɐɔıʇdO", "block.gtceu.opv_1024a_laser_source_hatch": "ɥɔʇɐH ǝɔɹnoS ɹǝsɐꞀ Ɐㄣᄅ0'Ɩ ΛdOן§6§", "block.gtceu.opv_1024a_laser_target_hatch": "ɥɔʇɐH ʇǝbɹɐ⟘ ɹǝsɐꞀ Ɐㄣᄅ0'Ɩ ΛdOן§6§", "block.gtceu.opv_16a_energy_converter": "ɹǝʇɹǝʌuoƆ ʎbɹǝuƎ Ɐ9Ɩ ΛdO", @@ -2312,6 +2313,7 @@ "config.gtceu.option.oreVeins": "suıǝΛǝɹo", "config.gtceu.option.overclockDivisor": "ɹosıʌıᗡʞɔoןɔɹǝʌo", "config.gtceu.option.platformToEuRatio": "oıʇɐᴚnƎo⟘ɯɹoɟʇɐןd", + "config.gtceu.option.preventAnimatedCables": "sǝןqɐƆpǝʇɐɯıuⱯʇuǝʌǝɹd", "config.gtceu.option.prospectorEnergyUseMultiplier": "ɹǝıןdıʇןnWǝs∩ʎbɹǝuƎɹoʇɔǝdsoɹd", "config.gtceu.option.recipeProgressLowEnergy": "ʎbɹǝuƎʍoꞀssǝɹboɹԀǝdıɔǝɹ", "config.gtceu.option.recipes": "sǝdıɔǝɹ", @@ -5890,21 +5892,20 @@ "tagprefix.marble": "ǝɹO %s ǝןqɹɐW", "tagprefix.netherrack": "ǝɹO %s ɹǝɥʇǝN", "tagprefix.nugget": "ʇǝbbnN %s", - "tagprefix.pipe_huge_fluid": "ǝdıԀ pınןℲ %s ǝbnH", - "tagprefix.pipe_huge_item": "ǝdıԀ ɯǝʇI %s ǝbnH", - "tagprefix.pipe_huge_restrictive": "ǝdıԀ ɯǝʇI %s ǝʌıʇɔıɹʇsǝᴚ ǝbnH", - "tagprefix.pipe_large_fluid": "ǝdıԀ pınןℲ %s ǝbɹɐꞀ", - "tagprefix.pipe_large_item": "ǝdıԀ ɯǝʇI %s ǝbɹɐꞀ", - "tagprefix.pipe_large_restrictive": "ǝdıԀ ɯǝʇI %s ǝʌıʇɔıɹʇsǝᴚ ǝbɹɐꞀ", - "tagprefix.pipe_nonuple_fluid": "ǝdıԀ pınןℲ %s ǝןdnuoN", - "tagprefix.pipe_normal_fluid": "ǝdıԀ pınןℲ %s ןɐɯɹoN", - "tagprefix.pipe_normal_item": "ǝdıԀ ɯǝʇI %s ןɐɯɹoN", - "tagprefix.pipe_normal_restrictive": "ǝdıԀ ɯǝʇI %s ǝʌıʇɔıɹʇsǝᴚ ןɐɯɹoN", - "tagprefix.pipe_quadruple_fluid": "ǝdıԀ pınןℲ %s ǝןdnɹpɐnὉ", - "tagprefix.pipe_small_fluid": "ǝdıԀ pınןℲ %s ןןɐɯS", - "tagprefix.pipe_small_item": "ǝdıԀ ɯǝʇI %s ןןɐɯS", - "tagprefix.pipe_small_restrictive": "ǝdıԀ ɯǝʇI %s ǝʌıʇɔıɹʇsǝᴚ ןןɐɯS", - "tagprefix.pipe_tiny_fluid": "ǝdıԀ pınןℲ %s ʎuı⟘", + "tagprefix.pipe_huge": "ǝdıԀ %s ǝbnH", + "tagprefix.pipe_huge_restrictive": "ǝdıԀ %s ǝʌıʇɔıɹʇsǝᴚ ǝbnH", + "tagprefix.pipe_large": "ǝdıԀ %s ǝbɹɐꞀ", + "tagprefix.pipe_large_restrictive": "ǝdıԀ %s ǝʌıʇɔıɹʇsǝᴚ ǝbɹɐꞀ", + "tagprefix.pipe_nonuple": "ǝdıԀ %s ǝןdnuoN", + "tagprefix.pipe_nonuple_restrictive": "ǝdıԀ %s ǝʌıʇɔıɹʇsǝᴚ ǝןdnuoN", + "tagprefix.pipe_normal": "ǝdıԀ %s ןɐɯɹoN", + "tagprefix.pipe_normal_restrictive": "ǝdıԀ %s ǝʌıʇɔıɹʇsǝᴚ ןɐɯɹoN", + "tagprefix.pipe_quadruple": "ǝdıԀ %s ǝןdnɹpɐnὉ", + "tagprefix.pipe_quadruple_restrictive": "ǝdıԀ %s ǝʌıʇɔıɹʇsǝᴚ ǝןdnɹpɐnὉ", + "tagprefix.pipe_small": "ǝdıԀ %s ןןɐɯS", + "tagprefix.pipe_small_restrictive": "ǝdıԀ %s ǝʌıʇɔıɹʇsǝᴚ ןןɐɯS", + "tagprefix.pipe_tiny": "ǝdıԀ %s ʎuı⟘", + "tagprefix.pipe_tiny_restrictive": "ǝdıԀ %s ǝʌıʇɔıɹʇsǝᴚ ʎuı⟘", "tagprefix.planks": "sʞuɐןԀ %s", "tagprefix.plate": "ǝʇɐןԀ %s", "tagprefix.polymer.dense_plate": "ʇǝǝɥS %s ǝsuǝᗡ", @@ -5956,4 +5957,4 @@ "tile.gtceu.reinforced_foam.name": "ɯɐoℲ pǝɔɹoɟuıǝᴚ", "tile.gtceu.reinforced_stone.name": "ǝuoʇS pǝɔɹoɟuıǝᴚ", "tile.gtceu.seal.name": "ʞɔoןᗺ pǝןɐǝS" -} \ No newline at end of file +} diff --git a/src/generated/resources/assets/gtceu/lang/en_us.json b/src/generated/resources/assets/gtceu/lang/en_us.json index 7513de071c..f723f9e2be 100644 --- a/src/generated/resources/assets/gtceu/lang/en_us.json +++ b/src/generated/resources/assets/gtceu/lang/en_us.json @@ -49,6 +49,7 @@ "behavior.portable_scanner.state": "%s: %s", "behavior.portable_scanner.tank": "Tank %s: %s mB / %s mB %s", "behavior.portable_scanner.tanks_empty": "All Tanks Empty", + "behavior.portable_scanner.temperature": "Temperature: %sK", "behavior.portable_scanner.team_name": "§2Team Name: %s§r", "behavior.portable_scanner.workable_consumption": "Probably Uses: %s EU/t at %s A", "behavior.portable_scanner.workable_production": "Probably Produces: %s EU/t at %s A", @@ -541,6 +542,7 @@ "block.gtceu.large_solidifier": "Large Solidification Array", "block.gtceu.large_wiremill": "Large Wire Factory", "block.gtceu.laser_hazard_sign_block": "Laser Hazard Sign Block", + "block.gtceu.laser_pipe": "Laser Pipe", "block.gtceu.laser_safe_engraving_casing": "Laser-Safe Engraving Casing", "block.gtceu.light_blue_borderless_lamp": "Light Blue Borderless Lamp", "block.gtceu.light_blue_lamp": "Light Blue Lamp", @@ -913,14 +915,13 @@ "block.gtceu.noise_hazard_sign_block": "Noise Hazard Sign Block", "block.gtceu.nonconducting_casing": "Nonconducting Casing", "block.gtceu.normal_duct_pipe": "Normal Duct Pipe", - "block.gtceu.normal_laser_pipe": "Normal Laser Pipe", "block.gtceu.normal_laser_pipe.tooltip": "§7Transmitting power with §fno loss§7 in straight lines", - "block.gtceu.normal_optical_pipe": "Optical Fiber Cable", "block.gtceu.normal_optical_pipe.tooltip": "§7Transmitting §fComputation§7 or §fResearch Data§7", "block.gtceu.object_holder": "Object Holder", "block.gtceu.oil_heavy": "Heavy Oil", "block.gtceu.oil_light": "Light Oil", "block.gtceu.oil_medium": "Raw Oil", + "block.gtceu.optical_fiber_cable": "Optical Fiber Cable", "block.gtceu.opv_1024a_laser_source_hatch": "§9§lOpV 1,024A Laser Source Hatch", "block.gtceu.opv_1024a_laser_target_hatch": "§9§lOpV 1,024A Laser Target Hatch", "block.gtceu.opv_16a_energy_converter": "OpV 16A Energy Converter", @@ -2312,6 +2313,7 @@ "config.gtceu.option.oreVeins": "oreVeins", "config.gtceu.option.overclockDivisor": "overclockDivisor", "config.gtceu.option.platformToEuRatio": "platformToEuRatio", + "config.gtceu.option.preventAnimatedCables": "preventAnimatedCables", "config.gtceu.option.prospectorEnergyUseMultiplier": "prospectorEnergyUseMultiplier", "config.gtceu.option.recipeProgressLowEnergy": "recipeProgressLowEnergy", "config.gtceu.option.recipes": "recipes", @@ -5890,21 +5892,20 @@ "tagprefix.marble": "Marble %s Ore", "tagprefix.netherrack": "Nether %s Ore", "tagprefix.nugget": "%s Nugget", - "tagprefix.pipe_huge_fluid": "Huge %s Fluid Pipe", - "tagprefix.pipe_huge_item": "Huge %s Item Pipe", - "tagprefix.pipe_huge_restrictive": "Huge Restrictive %s Item Pipe", - "tagprefix.pipe_large_fluid": "Large %s Fluid Pipe", - "tagprefix.pipe_large_item": "Large %s Item Pipe", - "tagprefix.pipe_large_restrictive": "Large Restrictive %s Item Pipe", - "tagprefix.pipe_nonuple_fluid": "Nonuple %s Fluid Pipe", - "tagprefix.pipe_normal_fluid": "Normal %s Fluid Pipe", - "tagprefix.pipe_normal_item": "Normal %s Item Pipe", - "tagprefix.pipe_normal_restrictive": "Normal Restrictive %s Item Pipe", - "tagprefix.pipe_quadruple_fluid": "Quadruple %s Fluid Pipe", - "tagprefix.pipe_small_fluid": "Small %s Fluid Pipe", - "tagprefix.pipe_small_item": "Small %s Item Pipe", - "tagprefix.pipe_small_restrictive": "Small Restrictive %s Item Pipe", - "tagprefix.pipe_tiny_fluid": "Tiny %s Fluid Pipe", + "tagprefix.pipe_huge": "Huge %s Pipe", + "tagprefix.pipe_huge_restrictive": "Huge Restrictive %s Pipe", + "tagprefix.pipe_large": "Large %s Pipe", + "tagprefix.pipe_large_restrictive": "Large Restrictive %s Pipe", + "tagprefix.pipe_nonuple": "Nonuple %s Pipe", + "tagprefix.pipe_nonuple_restrictive": "Nonuple Restrictive %s Pipe", + "tagprefix.pipe_normal": "Normal %s Pipe", + "tagprefix.pipe_normal_restrictive": "Normal Restrictive %s Pipe", + "tagprefix.pipe_quadruple": "Quadruple %s Pipe", + "tagprefix.pipe_quadruple_restrictive": "Quadruple Restrictive %s Pipe", + "tagprefix.pipe_small": "Small %s Pipe", + "tagprefix.pipe_small_restrictive": "Small Restrictive %s Pipe", + "tagprefix.pipe_tiny": "Tiny %s Pipe", + "tagprefix.pipe_tiny_restrictive": "Tiny Restrictive %s Pipe", "tagprefix.planks": "%s Planks", "tagprefix.plate": "%s Plate", "tagprefix.polymer.dense_plate": "Dense %s Sheet", @@ -5956,4 +5957,4 @@ "tile.gtceu.reinforced_foam.name": "Reinforced Foam", "tile.gtceu.reinforced_stone.name": "Reinforced Stone", "tile.gtceu.seal.name": "Sealed Block" -} \ No newline at end of file +} diff --git a/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json b/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json index 0bd103754d..c8cfbac305 100644 --- a/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json +++ b/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json @@ -1,6 +1,6 @@ { "values": [ - "gtceu:normal_laser_pipe", - "gtceu:normal_optical_pipe" + "gtceu:laser_pipe", + "gtceu:optical_fiber_cable" ] } \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/loot_tables/blocks/normal_laser_pipe.json b/src/generated/resources/data/gtceu/loot_tables/blocks/laser_pipe.json similarity index 75% rename from src/generated/resources/data/gtceu/loot_tables/blocks/normal_laser_pipe.json rename to src/generated/resources/data/gtceu/loot_tables/blocks/laser_pipe.json index d14a70d62b..a81c438ddb 100644 --- a/src/generated/resources/data/gtceu/loot_tables/blocks/normal_laser_pipe.json +++ b/src/generated/resources/data/gtceu/loot_tables/blocks/laser_pipe.json @@ -11,11 +11,11 @@ "entries": [ { "type": "minecraft:item", - "name": "gtceu:normal_laser_pipe" + "name": "gtceu:laser_pipe" } ], "rolls": 1.0 } ], - "random_sequence": "gtceu:blocks/normal_laser_pipe" + "random_sequence": "gtceu:blocks/laser_pipe" } \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/loot_tables/blocks/normal_optical_pipe.json b/src/generated/resources/data/gtceu/loot_tables/blocks/optical_fiber_cable.json similarity index 74% rename from src/generated/resources/data/gtceu/loot_tables/blocks/normal_optical_pipe.json rename to src/generated/resources/data/gtceu/loot_tables/blocks/optical_fiber_cable.json index 40b990e301..7f919761db 100644 --- a/src/generated/resources/data/gtceu/loot_tables/blocks/normal_optical_pipe.json +++ b/src/generated/resources/data/gtceu/loot_tables/blocks/optical_fiber_cable.json @@ -11,11 +11,11 @@ "entries": [ { "type": "minecraft:item", - "name": "gtceu:normal_optical_pipe" + "name": "gtceu:optical_fiber_cable" } ], "rolls": 1.0 } ], - "random_sequence": "gtceu:blocks/normal_optical_pipe" + "random_sequence": "gtceu:blocks/optical_fiber_cable" } \ No newline at end of file diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 5092039120..b8fb254f84 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -343,10 +343,9 @@ protected String getConnectLangKey() { @Override public List getDrops(BlockState state, LootParams.Builder builder) { - var context = builder.withParameter(LootContextParams.BLOCK_STATE, state).create(LootContextParamSets.BLOCK); - BlockEntity tileEntity = context.getParamOrNull(LootContextParams.BLOCK_ENTITY); + BlockEntity blockEntity = builder.getOptionalParameter(LootContextParams.BLOCK_ENTITY); List drops = new ArrayList<>(super.getDrops(state, builder)); - if (tileEntity instanceof PipeBlockEntity pipeTile) { + if (blockEntity instanceof PipeBlockEntity pipeTile) { pipeTile.getDrops(drops, state); } return drops; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 1615ec1aeb..50548c266d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -162,7 +162,6 @@ public PipeBlockEntity getPipeNeighbor(Direction facing, boolean allowChunkloadi } public void getDrops(@NotNull List drops, @NotNull BlockState state) { - drops.add(getMainDrop(state)); if (getFrameMaterial() != null) drops.add(GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, getFrameMaterial()).asStack()); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java index 6708b5673d..8aaf9740cb 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CleanroomMachine.java @@ -457,7 +457,7 @@ protected boolean isMachineBanned(MetaMachine metaBlockEntity) { // if (metaBlockEntity instanceof FuelMultiblockController) return true; if (metaBlockEntity instanceof LargeMinerMachine) return true; if (metaBlockEntity instanceof FluidDrillMachine) return true; - // if (metaBlockEntity instanceof MetaBlockEntityCentralMonitor) return true; + // if (metaBlockEntity instanceof MetaTileEntityCentralMonitor) return true; if (metaBlockEntity instanceof CokeOvenMachine) return true; if (metaBlockEntity instanceof PrimitiveBlastFurnaceMachine) return true; return metaBlockEntity instanceof PrimitivePumpMachine; diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java index 121f3b1a32..80ecd8337d 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java @@ -760,8 +760,8 @@ public static void init(RegistrateLangProvider provider) { "Caused %s Lag Spike Warnings (anything taking longer than %sms) on the Server."); provider.add("behavior.portable_scanner.debug_machine", "Meta-ID: %s"); provider.add("behavior.portable_scanner.debug_machine_invalid", " invalid!"); - provider.add("behavior.portable_scanner.debug_machine_invalid_null=invalid! MetaBlockEntity =", - " null!"); + provider.add("behavior.portable_scanner.debug_machine_invalid_null", + "invalid! MetaTileEntity = null!"); provider.add("behavior.portable_scanner.debug_machine_valid", " valid"); provider.add("behavior.portable_scanner.divider", "========================="); provider.add("behavior.portable_scanner.energy_container_in", "Max IN: %s (%s) EU at %s A"); From b271b41a9670e58c9d552dab0198935e88c02542 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 25 Aug 2024 20:48:44 +0300 Subject: [PATCH 22/70] small fixes --- .../physical/PipeStructureRegistry.java | 13 ++++----- .../physical/tile/PipeBlockEntity.java | 1 + .../net/energy/EnergyCapabilityObject.java | 29 ++++++++++++------- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java index b8ea01338c..4f7f6b5140 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.utils.GTUtil; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import org.jetbrains.annotations.NotNull; import java.util.Collections; @@ -10,16 +11,14 @@ import java.util.Map; import java.util.Set; +@SuppressWarnings("unchecked") public final class PipeStructureRegistry { private static final Map, Set> REGISTRY = new Object2ObjectLinkedOpenHashMap<>(); public static void register(@NotNull T structure) { - Set structures = (Set) REGISTRY.get(structure.getClass()); - if (structures == null) { - structures = new LinkedHashSet<>(); - REGISTRY.put(structure.getClass(), structures); - } + Set structures = (Set) REGISTRY.computeIfAbsent(structure.getClass(), + k -> new ObjectLinkedOpenHashSet<>()); structures.add(structure); } @@ -28,8 +27,6 @@ public static void register(@NotNull T structure) { */ public static @NotNull Set getStructures(Class structureClass) { GTUtil.forceInitialization(structureClass); - Set structures = (Set) REGISTRY.get(structureClass); - if (structures == null) return Collections.emptySet(); - return structures; + return (Set) REGISTRY.getOrDefault(structureClass, Collections.emptySet()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 50548c266d..c87c45385d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -529,6 +529,7 @@ protected void initialize() { this.listeners.trim(); this.capabilities.trim(); this.netCapabilities.trim(); + updateActiveStatus(null, false); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java index 319678eb61..4026f4bb00 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java @@ -74,16 +74,17 @@ public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, long tick = Platform.getMinecraftServer().getTickCount(); AbstractNetFlowEdge internalBuffer = this.internalBuffers.get(side); - // Disable this as it broke overamping - //if (internalBuffer != null) { - // long limit = internalBuffer.getFlowLimit(IPredicateTestObject.INSTANCE, net, tick, simulator); - // if (limit <= 0) { - // this.transferring = false; - // return 0; - // } else if (amperage > limit) { - // amperage = limit; - // } - //} + long bufferOverflowAmperage = 0; + if (internalBuffer != null) { + long limit = internalBuffer.getFlowLimit(IPredicateTestObject.INSTANCE, net, tick, simulator); + if (limit <= 0) { + this.transferring = false; + return 0; + } else if (amperage > limit) { + bufferOverflowAmperage = amperage - limit; + amperage = limit; + } + } long availableAmperage = amperage; EnergyTraverseData data = new EnergyTraverseData(net, IPredicateTestObject.INSTANCE, simulator, tick, voltage, @@ -95,7 +96,13 @@ public long acceptEnergyFromNetwork(Direction side, long voltage, long amperage, } long accepted = amperage - availableAmperage; - if (internalBuffer != null) data.consumeFlowLimit(internalBuffer, node, accepted); + if (internalBuffer != null) { + data.consumeFlowLimit(internalBuffer, node, accepted); + if (bufferOverflowAmperage > 0) { + data.handleOverflow(node, bufferOverflowAmperage); + accepted += bufferOverflowAmperage; + } + } if (!simulate) { EnergyGroupData group = getEnergyData(); if (group != null) { From ede4f3c8b97e320ff0fc4bc6de271b19268f343f Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Wed, 4 Sep 2024 12:37:31 +0300 Subject: [PATCH 23/70] move net logic entry types to a clearer system --- .../gtceu/api/graphnet/IGraphNet.java | 2 +- .../gtceu/api/graphnet/MultiNodeHelper.java | 4 +- .../graphnet/edge/AbstractNetFlowEdge.java | 4 +- .../logic/AbstractDoubleLogicData.java | 6 +-- .../graphnet/logic/AbstractIntLogicData.java | 6 +-- .../graphnet/logic/AbstractLongLogicData.java | 6 +-- .../api/graphnet/logic/ChannelCountLogic.java | 11 +--- .../graphnet/logic/MultiNetCountLogic.java | 7 --- .../api/graphnet/logic/NetLogicData.java | 50 ++++++++--------- .../api/graphnet/logic/NetLogicEntry.java | 19 +++---- .../api/graphnet/logic/NetLogicEntryType.java | 18 +++++++ .../api/graphnet/logic/NetLogicRegistry.java | 53 +++++++++++++++---- .../api/graphnet/logic/ThroughputLogic.java | 11 +--- .../api/graphnet/logic/WeightFactorLogic.java | 11 +--- .../graphnet/path/GenericGraphNetPath.java | 2 +- .../pipenet/BasicWorldPipeNetPath.java | 2 +- .../pipenet/FlowWorldPipeNetPath.java | 2 +- .../logic/EdgeCoverReferenceLogic.java | 10 ++-- .../pipenet/logic/TemperatureLogic.java | 11 ++-- .../physical/tile/PipeBlockEntity.java | 20 ++++--- .../api/graphnet/servernet/ServerNet.java | 4 +- .../gtceu/api/graphnet/worldnet/WorldNet.java | 4 +- .../pipelike/block/cable/CableBlock.java | 4 +- .../properties/MaterialEnergyProperties.java | 24 ++++----- .../properties/MaterialFluidProperties.java | 8 +-- .../properties/MaterialItemProperties.java | 4 +- .../net/energy/EnergyCapabilityObject.java | 4 +- .../pipelike/net/energy/EnergyFlowLogic.java | 10 ++-- .../net/energy/EnergyTraverseData.java | 14 ++--- .../net/energy/SuperconductorLogic.java | 11 ++-- .../net/energy/VoltageLimitLogic.java | 12 ++--- .../pipelike/net/energy/VoltageLossLogic.java | 12 ++--- .../net/fluid/FluidCapabilityObject.java | 2 +- .../net/fluid/FluidContainmentLogic.java | 17 +++--- .../pipelike/net/fluid/FluidTraverseData.java | 8 +-- .../jade/provider/CableBlockProvider.java | 2 +- 36 files changed, 188 insertions(+), 207 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java index 1c14c54f20..41a0aac219 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java @@ -125,7 +125,7 @@ default AbstractGroupData getBlankGroupData() { */ @NotNull default NetLogicData getDefaultNodeData() { - return new NetLogicData().setLogicEntry(WeightFactorLogic.INSTANCE.getWith(1)); + return new NetLogicData().setLogicEntry(WeightFactorLogic.TYPE.getWith(1)); } /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java index 863cb9ee4d..8e7cf76862 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java @@ -67,7 +67,7 @@ public void addNode(@NotNull NetNode node) { List> toSet = new ObjectArrayList<>(); for (NetLogicEntry entry : node.getData().getEntries()) { if (entry.mergedToMultiNodeHelper()) { - NetLogicEntry existing = mergedData.getLogicEntryNullable(entry); + NetLogicEntry existing = mergedData.getLogicEntryNullable(entry.getType()); if (existing != null) { existing.merge(node, entry); // don't put it into the data yet because we're currently iterating through the data's entries. @@ -121,7 +121,7 @@ public void markChanged(NetLogicEntry updatedEntry, boolean removed, boole if (!fullChange || !updatedEntry.mergedToMultiNodeHelper()) return; NetNode node = nodeRef.get(); if (node == null) return; - NetLogicEntry existing = mergedData.getLogicEntryNullable(updatedEntry); + NetLogicEntry existing = mergedData.getLogicEntryNullable(updatedEntry.getType()); if (removed) { if (existing != null) mergedData.removeLogicEntry(existing); } else { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java index cd03f0f587..ab8a6164e2 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/edge/AbstractNetFlowEdge.java @@ -50,11 +50,11 @@ protected AbstractChannelsHolder getChannels(@Nullable SimulatorKey simulator) { } protected int getChannelCount() { - return getData().getLogicEntryDefaultable(ChannelCountLogic.INSTANCE).getValue(); + return getData().getLogicEntryDefaultable(ChannelCountLogic.TYPE).getValue(); } public long getThroughput() { - return getData().getLogicEntryDefaultable(ThroughputLogic.INSTANCE).getValue(); + return getData().getLogicEntryDefaultable(ThroughputLogic.TYPE).getValue(); } public long getFlowLimit(IPredicateTestObject channel, IGraphNet graph, long queryTick, diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java index 485ad56103..4fa56783bb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java @@ -10,12 +10,12 @@ public abstract class AbstractDoubleLogicData type) { + super(type); } public T getWith(double value) { - return getNew().setValue(value); + return getType().supplier().get().setValue(value); } protected T setValue(double value) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java index 43519a7148..3aa7284dbd 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java @@ -9,12 +9,12 @@ public abstract class AbstractIntLogicData> ex private int value; - protected AbstractIntLogicData(@NotNull String name) { - super(name); + protected AbstractIntLogicData(@NotNull NetLogicEntryType type) { + super(type); } public T getWith(int value) { - return getNew().setValue(value); + return getType().supplier().get().setValue(value); } protected T setValue(int value) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java index b51d9c4135..e5a95732b1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java @@ -10,12 +10,12 @@ public abstract class AbstractLongLogicData> private long value; - protected AbstractLongLogicData(@NotNull String name) { - super(name); + protected AbstractLongLogicData(@NotNull NetLogicEntryType type) { + super(type); } public T getWith(long value) { - return getNew().setValue(value); + return getType().supplier().get().setValue(value); } @Contract("_ -> this") diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java index 75ba582ea3..03a79b22c2 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java @@ -1,18 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import org.jetbrains.annotations.NotNull; - public final class ChannelCountLogic extends AbstractIntLogicData { - public static final ChannelCountLogic INSTANCE = new ChannelCountLogic().setValue(1); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("ChannelCount", () -> new ChannelCountLogic().setValue(1)); public ChannelCountLogic() { - super("ChannelCount"); - } - - @Override - public @NotNull ChannelCountLogic getNew() { - return new ChannelCountLogic(); + super(TYPE); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java index e6c6f17c8e..d474fd6a15 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java @@ -1,7 +1,5 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import org.jetbrains.annotations.NotNull; - public final class MultiNetCountLogic extends AbstractIntLogicData { public static final MultiNetCountLogic INSTANCE = new MultiNetCountLogic().setValue(1); @@ -10,11 +8,6 @@ public MultiNetCountLogic() { super("MultiNetCount"); } - @Override - public @NotNull MultiNetCountLogic getNew() { - return new MultiNetCountLogic(); - } - @Override public MultiNetCountLogic union(NetLogicEntry other) { if (other instanceof MultiNetCountLogic l) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index 18682a5c5d..6d07ecd816 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -33,7 +33,7 @@ public final class NetLogicData implements ITagSerializable, IContentCh private Runnable onContentsChanged = () -> {}; // TODO caching logic on simple logics to reduce amount of reduntant creation? - private final Object2ObjectOpenHashMap> logicEntrySet; + private final Object2ObjectOpenHashMap, NetLogicEntry> logicEntrySet; private final Set listeners = new ObjectOpenHashSet<>(); @@ -41,7 +41,7 @@ public NetLogicData() { logicEntrySet = new Object2ObjectOpenHashMap<>(4); } - private NetLogicData(Object2ObjectOpenHashMap> logicEntrySet) { + private NetLogicData(Object2ObjectOpenHashMap, NetLogicEntry> logicEntrySet) { this.logicEntrySet = logicEntrySet; } @@ -50,7 +50,7 @@ private NetLogicData(Object2ObjectOpenHashMap> logic * nothing happens if an entry is already present. */ public NetLogicData mergeLogicEntry(NetLogicEntry entry) { - NetLogicEntry current = logicEntrySet.get(entry.getSerializedName()); + NetLogicEntry current = logicEntrySet.get(entry.getType()); if (current == null) return setLogicEntry(entry); if (entry.getClass().isInstance(current)) { @@ -62,7 +62,7 @@ public NetLogicData mergeLogicEntry(NetLogicEntry entry) { public NetLogicData setLogicEntry(NetLogicEntry entry) { entry.registerToNetLogicData(this); - logicEntrySet.put(entry.getSerializedName(), entry); + logicEntrySet.put(entry.getType(), entry); this.markLogicEntryAsUpdated(entry, true); return this; } @@ -83,10 +83,10 @@ public void clearData() { } public NetLogicData removeLogicEntry(@NotNull NetLogicEntry key) { - return removeLogicEntry(key.getSerializedName()); + return removeLogicEntry(key.getType()); } - public NetLogicData removeLogicEntry(@NotNull String key) { + public NetLogicData removeLogicEntry(@NotNull NetLogicEntryType key) { NetLogicEntry entry = logicEntrySet.remove(key); if (entry != null) { entry.deregisterFromNetLogicData(this); @@ -112,30 +112,25 @@ public boolean hasLogicEntry(@NotNull String key) { } public boolean hasLogicEntry(@NotNull NetLogicEntry key) { - return logicEntrySet.containsKey(key.getSerializedName()); + return logicEntrySet.containsKey(key.getType()); } @Nullable - public NetLogicEntry getLogicEntryNullable(@NotNull String key) { - return logicEntrySet.get(key); - } - - @Nullable - public > T getLogicEntryNullable(@NotNull T key) { + public > T getLogicEntryNullable(@NotNull NetLogicEntryType key) { try { - return (T) logicEntrySet.get(key.getSerializedName()); + return (T) logicEntrySet.get(key); } catch (ClassCastException ignored) { return null; } } @NotNull - public > T getLogicEntryDefaultable(@NotNull T key) { + public > T getLogicEntryDefaultable(@NotNull NetLogicEntryType key) { try { - T returnable = (T) logicEntrySet.get(key.getSerializedName()); - return returnable == null ? key : returnable; + T returnable = (T) logicEntrySet.get(key); + return returnable == null ? key.supplier().get() : returnable; } catch (ClassCastException ignored) { - return key; + return key.supplier().get(); } } @@ -148,10 +143,10 @@ public boolean hasLogicEntry(@NotNull NetLogicEntry key) { @Contract("_, _ -> new") public static @NotNull NetLogicData union(@NotNull NetLogicData sourceData, @Nullable NetLogicData targetData) { - Object2ObjectOpenHashMap> newLogic = new Object2ObjectOpenHashMap<>( + Object2ObjectOpenHashMap, NetLogicEntry> newLogic = new Object2ObjectOpenHashMap<>( sourceData.logicEntrySet); if (targetData != null) { - for (String key : newLogic.keySet()) { + for (NetLogicEntryType key : newLogic.keySet()) { newLogic.computeIfPresent(key, (k, v) -> v.union(targetData.logicEntrySet.get(k))); } targetData.logicEntrySet.forEach((key, value) -> newLogic.computeIfAbsent(key, k -> value.union(null))); @@ -161,10 +156,10 @@ public boolean hasLogicEntry(@NotNull NetLogicEntry key) { @Contract("_, _ -> new") public static @NotNull NetLogicData union(@NotNull NetLogicData first, @NotNull NetLogicData... others) { - Object2ObjectOpenHashMap> newLogic = new Object2ObjectOpenHashMap<>( + Object2ObjectOpenHashMap, NetLogicEntry> newLogic = new Object2ObjectOpenHashMap<>( first.logicEntrySet); for (NetLogicData other : others) { - for (String key : newLogic.keySet()) { + for (NetLogicEntryType key : newLogic.keySet()) { newLogic.computeIfPresent(key, (k, v) -> v.union(other.logicEntrySet.get(k))); } other.logicEntrySet.forEach((key, value) -> newLogic.computeIfAbsent(key, k -> value.union(null))); @@ -181,7 +176,7 @@ public ListTag serializeNBT() { ListTag list = new ListTag(); for (NetLogicEntry entry : getEntries()) { CompoundTag tag = new CompoundTag(); - tag.putString("Name", entry.getSerializedName()); + tag.putString("Name", entry.getType().getSerializedName()); Tag nbt = entry.serializeNBT(); if (nbt != null) tag.put("Tag", nbt); list.add(tag); @@ -195,7 +190,7 @@ public void deserializeNBT(ListTag nbt) { CompoundTag tag = nbt.getCompound(i); String key = tag.getString("Name"); NetLogicEntry entry = this.logicEntrySet.get(key); - if (entry == null) entry = NetLogicRegistry.getSupplierNotNull(key).get(); + if (entry == null) entry = NetLogicRegistry.getTypeNotNull(key).supplier().get(); if (entry == null) continue; entry.deserializeNBTNaive(tag.get("Tag")); } @@ -205,7 +200,7 @@ public void encode(FriendlyByteBuf buf) { buf.writeVarInt(getEntries().size()); for (NetLogicEntry entry : getEntries()) { if (entry.shouldEncode()) { - buf.writeUtf(entry.getSerializedName()); + buf.writeUtf(entry.getType().getSerializedName()); entry.encode(buf, true); } else { buf.writeUtf(""); @@ -219,10 +214,11 @@ public void decode(FriendlyByteBuf buf) { for (int i = 0; i < entryCount; i++) { String name = buf.readUtf(255); if (name.isEmpty()) continue; - NetLogicEntry existing = NetLogicRegistry.getSupplierErroring(name).get(); + NetLogicEntryType type = NetLogicRegistry.getTypeErroring(name); + NetLogicEntry existing = type.supplier().get(); existing.registerToNetLogicData(this); existing.decode(buf); - this.logicEntrySet.put(name, existing); + this.logicEntrySet.put(type, existing); } this.logicEntrySet.trim(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java index ee178efcde..84a5fa4606 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java @@ -6,9 +6,9 @@ import com.lowdragmc.lowdraglib.networking.IPacket; +import lombok.Getter; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.util.StringRepresentable; import net.minecraftforge.common.util.INBTSerializable; import org.jetbrains.annotations.NotNull; @@ -19,18 +19,13 @@ * {@link #union(NetLogicEntry)} behavior. */ public abstract class NetLogicEntry, N extends Tag> - implements INBTSerializable, StringRepresentable, IPacket { + implements INBTSerializable, IPacket { - private final @NotNull String name; + @Getter + private final @NotNull NetLogicEntryType type; - protected NetLogicEntry(@NotNull String name) { - this.name = name; - NetLogicRegistry.register(this); - } - - @Override - public final @NotNull String getSerializedName() { - return name; + protected NetLogicEntry(@NotNull NetLogicEntryType type) { + this.type = type; } public void deserializeNBTNaive(@Nullable Tag nbt) { @@ -92,8 +87,6 @@ public void registerToNetLogicData(NetLogicData data) {} public void deregisterFromNetLogicData(NetLogicData data) {} - public abstract @NotNull T getNew(); - public T cast(NetLogicEntry entry) { return (T) entry; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java new file mode 100644 index 0000000000..a1f5290688 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java @@ -0,0 +1,18 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import net.minecraft.util.StringRepresentable; + +import java.util.function.Supplier; + +public record NetLogicEntryType>(String id, Supplier supplier) + implements StringRepresentable { + + public NetLogicEntryType { + NetLogicRegistry.register(this); + } + + @Override + public String getSerializedName() { + return id; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index 6444f8582f..93a2f1b402 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -1,36 +1,67 @@ package com.gregtechceu.gtceu.api.graphnet.logic; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; -import java.util.function.Supplier; public final class NetLogicRegistry { - private static final Map>> REGISTRY = new Object2ObjectOpenHashMap<>(); + private static final Map> REGISTRY = new Object2ObjectOpenHashMap<>(); - static void register(NetLogicEntry entry) { - REGISTRY.putIfAbsent(entry.getSerializedName(), entry::getNew); + static void register(NetLogicEntryType entry) { + REGISTRY.putIfAbsent(entry.getSerializedName(), entry); } - public static @Nullable Supplier<@NotNull NetLogicEntry> getSupplierNullable(String name) { + public static @Nullable NetLogicEntryType getTypeNullable(String name) { return REGISTRY.get(name); } - public static @NotNull Supplier<@Nullable NetLogicEntry> getSupplierNotNull(String name) { - return REGISTRY.getOrDefault(name, () -> null); + public static @NotNull NetLogicEntryType getTypeNotNull(String name) { + return REGISTRY.getOrDefault(name, EmptyLogicEntry.TYPE); } - public static @NotNull Supplier<@NotNull NetLogicEntry> getSupplierErroring(String name) { - Supplier> supplier = REGISTRY.get(name); - if (supplier == null) throwNonexistenceError(); - return supplier; + public static @NotNull NetLogicEntryType getTypeErroring(String name) { + NetLogicEntryType type = REGISTRY.get(name); + if (type == null) throwNonexistenceError(); + return type; } public static void throwNonexistenceError() { throw new RuntimeException("Could not find a matching supplier for an encoded NetLogicEntry. " + "This suggests that the server and client have different GT versions or modifications."); } + + private static class EmptyLogicEntry extends NetLogicEntry { + + private static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Empty", EmptyLogicEntry::new); + + protected EmptyLogicEntry() { + super(TYPE); + } + + @Override + public @Nullable Tag serializeNBT() { + throw new RuntimeException("Can't serialize empty logic entry!"); + } + + @Override + public void deserializeNBT(Tag arg) { + throw new RuntimeException("Can't deserialize empty logic entry!"); + } + + @Override + public void encode(FriendlyByteBuf buf, boolean fullChange) { + throw new RuntimeException("Can't serialize empty logic entry!"); + } + + @Override + public void decode(FriendlyByteBuf buf, boolean fullChange) { + throw new RuntimeException("Can't deserialize empty logic entry!"); + } + + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java index bd092f3239..07cea6dc47 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java @@ -1,18 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import org.jetbrains.annotations.NotNull; - public final class ThroughputLogic extends AbstractLongLogicData { - public static final ThroughputLogic INSTANCE = new ThroughputLogic().setValue(0); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Throughput", () -> new ThroughputLogic().setValue(0)); private ThroughputLogic() { - super("Throughput"); - } - - @Override - public @NotNull ThroughputLogic getNew() { - return new ThroughputLogic(); + super(TYPE); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java index f0eceb6e05..8307071b9b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java @@ -1,18 +1,11 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import org.jetbrains.annotations.NotNull; - public final class WeightFactorLogic extends AbstractDoubleLogicData { - public static final WeightFactorLogic INSTANCE = new WeightFactorLogic().setValue(0.1d); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("WeightFactor", () -> new WeightFactorLogic().setValue(0.1d)); private WeightFactorLogic() { - super("WeightFactor"); - } - - @Override - public @NotNull WeightFactorLogic getNew() { - return new WeightFactorLogic(); + super(TYPE); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java index a88c4ab789..11acb29532 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/GenericGraphNetPath.java @@ -24,7 +24,7 @@ public class GenericGraphNetPath extends AbstractNetPath { public GenericGraphNetPath(GraphVertex vertex) { this(Collections.singletonList(vertex), Collections.emptyList(), - vertex.wrapped.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue()); + vertex.wrapped.getData().getLogicEntryDefaultable(WeightFactorLogic.TYPE).getValue()); } public GenericGraphNetPath(List vertices, List edges, double weight) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java index 7a7f98acd4..48e7b62f96 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/BasicWorldPipeNetPath.java @@ -24,7 +24,7 @@ public class BasicWorldPipeNetPath extends AbstractNetPath vertices, List edges, double weight) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java index d23d899795..17a7947253 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/FlowWorldPipeNetPath.java @@ -24,7 +24,7 @@ public class FlowWorldPipeNetPath extends AbstractNetPath vertices, List edges, double weight) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java index 95d08bac3d..8767151d68 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.utils.DimensionFacingPos; import com.gregtechceu.gtceu.utils.GTUtil; @@ -25,7 +26,7 @@ public final class EdgeCoverReferenceLogic extends NetLogicEntry { - public static final EdgeCoverReferenceLogic INSTANCE = new EdgeCoverReferenceLogic(); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EdgeCoverReference", EdgeCoverReferenceLogic::new); @Nullable private WeakReference coverSource; @@ -35,7 +36,7 @@ public final class EdgeCoverReferenceLogic extends NetLogicEntry this") @@ -134,11 +135,6 @@ public void deserializeNBT(CompoundTag nbt) { this.coverTarget = coverSource; } - @Override - public @NotNull EdgeCoverReferenceLogic getNew() { - return new EdgeCoverReferenceLogic(); - } - @Override public boolean shouldEncode() { return false; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index f90b0d1676..f97fb4f0f2 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -5,6 +5,7 @@ import com.gregtechceu.gtceu.api.graphnet.logic.INetLogicEntryListener; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossResult; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; @@ -28,7 +29,7 @@ public final class TemperatureLogic extends NetLogicEntry { - public static final TemperatureLogic INSTANCE = new TemperatureLogic(); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Temperature", TemperatureLogic::new); public static final int DEFAULT_TEMPERATURE = 298; @@ -46,7 +47,7 @@ public final class TemperatureLogic extends NetLogicEntry(null); } - public @NotNull TemperatureLogic getNew() { - return new TemperatureLogic(); - } - public boolean isOverMaximum(int temperature) { return temperature > getTemperatureMaximum(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index c87c45385d..5bcf9f28d6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -12,6 +12,7 @@ import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicRegistry; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; @@ -133,7 +134,8 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity @Persisted @DescSynced @Getter - protected final PipeCoverHolder coverHolder = new PipeCoverHolder(this); + protected final PipeCoverHolder covers = new PipeCoverHolder(this); + @Getter private final Object2ObjectOpenHashMap, IPipeCapabilityObject> capabilities = new Object2ObjectOpenHashMap<>(); private final Object2ObjectOpenCustomHashMap netCapabilities = WorldPipeNet .getSensitiveHashMap(); @@ -506,7 +508,7 @@ protected void initialize() { var listener = node.getData().createListener( (e, r, f) -> writeCustomData(UPDATE_PIPE_LOGIC, buf -> { buf.writeVarInt(networkID); - buf.writeUtf(e.getSerializedName()); + buf.writeUtf(e.getType().id()); buf.writeBoolean(r); buf.writeBoolean(f); if (!r) { @@ -522,7 +524,7 @@ protected void initialize() { } if (firstNode) { firstNode = false; - this.temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + this.temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); } } this.netLogicDatas.trim(); @@ -569,10 +571,11 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { boolean removed = buf.readBoolean(); boolean fullChange = buf.readBoolean(); if (removed) { - this.netLogicDatas.computeIfPresent(networkID, (k, v) -> v.removeLogicEntry(identifier)); + NetLogicEntryType logic = NetLogicRegistry.getTypeErroring(identifier); + this.netLogicDatas.computeIfPresent(networkID, (k, v) -> v.removeLogicEntry(logic)); } else { if (fullChange) { - NetLogicEntry logic = NetLogicRegistry.getSupplierErroring(identifier).get(); + NetLogicEntry logic = NetLogicRegistry.getTypeErroring(identifier).supplier().get(); logic.decode(buf, true); this.netLogicDatas.compute(networkID, (k, v) -> { if (v == null) v = new NetLogicData(); @@ -582,14 +585,15 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { } else { NetLogicData data = this.netLogicDatas.get(networkID); if (data != null) { - NetLogicEntry entry = data.getLogicEntryNullable(identifier); + NetLogicEntryType logic = NetLogicRegistry.getTypeErroring(identifier); + NetLogicEntry entry = data.getLogicEntryNullable(logic); if (entry != null) entry.decode(buf, false); data.markLogicEntryAsUpdated(entry, false); } else return; } - if (identifier.equals(TemperatureLogic.INSTANCE.getSerializedName())) { + if (identifier.equals(TemperatureLogic.TYPE.getSerializedName())) { TemperatureLogic tempLogic = this.netLogicDatas.get(networkID) - .getLogicEntryNullable(TemperatureLogic.INSTANCE); + .getLogicEntryNullable(TemperatureLogic.TYPE); if (tempLogic != null) updateTemperatureLogic(tempLogic); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java index c21aa4db0d..f8d0b42233 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/servernet/ServerNet.java @@ -72,8 +72,8 @@ public void removeNode(@NotNull NetNode node) { public NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays) { nodeClassCheck(source); nodeClassCheck(target); - double weight = source.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue() + - target.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue(); + double weight = source.getData().getLogicEntryDefaultable(WeightFactorLogic.TYPE).getValue() + + target.getData().getLogicEntryDefaultable(WeightFactorLogic.TYPE).getValue(); NetEdge edge = backer.addEdge(source, target, weight); if (bothWays) { if (this.getGraph().isDirected()) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java index e43c69155e..f3baac9744 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -89,8 +89,8 @@ public void removeNode(@NotNull NetNode node) { public NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, boolean bothWays) { nodeClassCheck(source); nodeClassCheck(target); - double weight = source.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue() + - target.getData().getLogicEntryDefaultable(WeightFactorLogic.INSTANCE).getValue(); + double weight = source.getData().getLogicEntryDefaultable(WeightFactorLogic.TYPE).getValue() + + target.getData().getLogicEntryDefaultable(WeightFactorLogic.TYPE).getValue(); NetEdge edge = backer.addEdge(source, target, weight); if (bothWays) { if (this.getGraph().isDirected()) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index 67c8203c42..ddb01beff8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -74,8 +74,8 @@ public void entityInside(BlockState state, Level level, BlockPos pos, Entity ent if (tile != null && tile.getFrameMaterial() == null && tile.getOffsetTimer() % 10 == 0) { WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(pos); if (node != null) { - if (node.getData().getLogicEntryNullable(SuperconductorLogic.INSTANCE) != null) return; - EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + if (node.getData().getLogicEntryNullable(SuperconductorLogic.TYPE) != null) return; + EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.TYPE); if (logic != null) { long tick = Platform.getMinecraftServer().getTickCount(); long cumulativeDamage = 0; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java index 6dc6edf2bf..0378e2d031 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java @@ -172,31 +172,31 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { boolean insulated = cable.partialBurnStructure() != null; // insulated cables cool down half as fast float coolingFactor = (float) (Math.sqrt(cable.material()) / (insulated ? 8 : 4)); - data.setLogicEntry(VoltageLossLogic.INSTANCE.getWith(loss)) - .setLogicEntry(WeightFactorLogic.INSTANCE.getWith(loss + 0.001 / amperage)) - .setLogicEntry(ThroughputLogic.INSTANCE.getWith(amperage)) - .setLogicEntry(VoltageLimitLogic.INSTANCE.getWith(voltageLimit)) - .setLogicEntry(TemperatureLogic.INSTANCE + data.setLogicEntry(VoltageLossLogic.INSTANCE.supplier().get().getWith(loss)) + .setLogicEntry(WeightFactorLogic.TYPE.supplier().get().getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.TYPE.getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.TYPE.supplier().get().getWith(voltageLimit)) + .setLogicEntry(TemperatureLogic.TYPE.supplier().get() .getWith(TemperatureLossFunction.getOrCreateCable(coolingFactor), materialMeltTemperature, 1, 100 * cable.material(), cable.partialBurnThreshold())); if (superconductorCriticalTemperature > 0) { - data.setLogicEntry(SuperconductorLogic.INSTANCE.getWith(superconductorCriticalTemperature)); + data.setLogicEntry(SuperconductorLogic.TYPE.supplier().get().getWith(superconductorCriticalTemperature)); } } else if (structure instanceof MaterialPipeStructure pipe) { long amperage = getAmperage(structure); if (amperage == 0) return; // skip pipes that are too small long loss = getLoss(structure); float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); - data.setLogicEntry(VoltageLossLogic.INSTANCE.getWith(loss)) - .setLogicEntry(WeightFactorLogic.INSTANCE.getWith(loss + 0.001 / amperage)) - .setLogicEntry(ThroughputLogic.INSTANCE.getWith(amperage)) - .setLogicEntry(VoltageLimitLogic.INSTANCE.getWith(voltageLimit)) - .setLogicEntry(TemperatureLogic.INSTANCE + data.setLogicEntry(VoltageLossLogic.INSTANCE.supplier().get().getWith(loss)) + .setLogicEntry(WeightFactorLogic.TYPE.supplier().get().getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.TYPE.supplier().get().getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.TYPE.supplier().get().getWith(voltageLimit)) + .setLogicEntry(TemperatureLogic.TYPE.supplier().get() .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, 1, 50 * pipe.material(), null)); if (superconductorCriticalTemperature > 0) { - data.setLogicEntry(SuperconductorLogic.INSTANCE.getWith(superconductorCriticalTemperature)); + data.setLogicEntry(SuperconductorLogic.TYPE.supplier().get().getWith(superconductorCriticalTemperature)); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java index b48a9b7714..f09e4a4ff1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java @@ -178,11 +178,11 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { if (structure instanceof MaterialPipeStructure pipe) { long throughput = getThroughput(structure); float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); - data.setLogicEntry(WeightFactorLogic.INSTANCE.getWith(getFlowPriority(structure))) - .setLogicEntry(ThroughputLogic.INSTANCE.getWith(throughput)) - .setLogicEntry(FluidContainmentLogic.INSTANCE.getWith(containableStates, containedAttributes, + data.setLogicEntry(WeightFactorLogic.TYPE.getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.TYPE.getWith(throughput)) + .setLogicEntry(FluidContainmentLogic.TYPE.getWith(containableStates, containedAttributes, maxFluidTemperature)) - .setLogicEntry(TemperatureLogic.INSTANCE + .setLogicEntry(TemperatureLogic.TYPE .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, minFluidTemperature, 50 * pipe.material(), null)); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java index b10f652fe8..39eee87be6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java @@ -83,8 +83,8 @@ public WorldPipeNetNode getOrCreateFromNet(ServerLevel world, BlockPos pos, IPip public void mutateData(NetLogicData data, IPipeStructure structure) { if (structure instanceof MaterialPipeStructure pipe) { long throughput = baseItemsPer5Ticks * pipe.material(); - data.setLogicEntry(WeightFactorLogic.INSTANCE.getWith(getFlowPriority(structure))) - .setLogicEntry(ThroughputLogic.INSTANCE.getWith(throughput)); + data.setLogicEntry(WeightFactorLogic.TYPE.getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.TYPE.getWith(throughput)); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java index 4026f4bb00..28af277c0e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyCapabilityObject.java @@ -134,13 +134,13 @@ private EnergyGroupData getEnergyData() { @Override public long getInputAmperage() { if (tile == null) return 0; - return tile.getNetLogicData(net.getNetworkID()).getLogicEntryDefaultable(ThroughputLogic.INSTANCE).getValue(); + return tile.getNetLogicData(net.getNetworkID()).getLogicEntryDefaultable(ThroughputLogic.TYPE).getValue(); } @Override public long getInputVoltage() { if (tile == null) return 0; - return tile.getNetLogicData(net.getNetworkID()).getLogicEntryDefaultable(VoltageLimitLogic.INSTANCE).getValue(); + return tile.getNetLogicData(net.getNetworkID()).getLogicEntryDefaultable(VoltageLimitLogic.TYPE).getValue(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java index f9bd23c1b7..7edc8e43a1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; import net.minecraft.nbt.ByteTag; import net.minecraft.network.FriendlyByteBuf; @@ -16,7 +17,7 @@ public class EnergyFlowLogic extends NetLogicEntry { - public static final EnergyFlowLogic INSTANCE = new EnergyFlowLogic(); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EnergyFlow", EnergyFlowLogic::new); private final AveragingPerTickCounter averageVoltageCounter = new AveragingPerTickCounter(); private final AveragingPerTickCounter averageAmperageCounter = new AveragingPerTickCounter(); @@ -28,7 +29,7 @@ public class EnergyFlowLogic extends NetLogicEntry { private final Long2ObjectOpenHashMap> memory = new Long2ObjectOpenHashMap<>(); protected EnergyFlowLogic() { - super("EnergyFlow"); + super(TYPE); } public @NotNull List getFlow(long tick) { @@ -73,11 +74,6 @@ public ByteTag serializeNBT() { @Override public void deserializeNBT(ByteTag nbt) {} - @Override - public @NotNull EnergyFlowLogic getNew() { - return new EnergyFlowLogic(); - } - @Override public boolean shouldEncode() { return false; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java index 3aeef0f276..23b0c5fbc6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java @@ -54,14 +54,14 @@ public boolean prepareForPathWalk(@NotNull FlowWorldPipeNetPath path, long flow) @Override public ReversibleLossOperator traverseToNode(@NotNull WorldPipeNetNode node, long flowReachingNode) { - VoltageLimitLogic limitLogic = node.getData().getLogicEntryNullable(VoltageLimitLogic.INSTANCE); + VoltageLimitLogic limitLogic = node.getData().getLogicEntryNullable(VoltageLimitLogic.TYPE); if (limitLogic != null) { long voltage = limitLogic.getValue(); if (voltage < pathVoltage) overVoltageInformation.put(node, new OverVoltageInformation(voltage, flowReachingNode)); } - TemperatureLogic temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); - if (!node.getData().getLogicEntryDefaultable(SuperconductorLogic.INSTANCE) + TemperatureLogic temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); + if (!node.getData().getLogicEntryDefaultable(SuperconductorLogic.TYPE) .canSuperconduct(temperatureLogic == null ? TemperatureLogic.DEFAULT_TEMPERATURE : temperatureLogic.getTemperature(getQueryTick()))) { pathVoltage -= node.getData().getLogicEntryDefaultable(VoltageLossLogic.INSTANCE).getValue(); @@ -82,7 +82,7 @@ public ReversibleLossOperator traverseToNode(@NotNull WorldPipeNetNode node, lon } public void handleOverflow(@NotNull WorldPipeNetNode node, long overflow) { - TemperatureLogic logic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + TemperatureLogic logic = (TemperatureLogic) node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); if (logic != null) { // this occurs after finalization but before path reset. logic.applyThermalEnergy(calculateHeatA(overflow, pathVoltage), getQueryTick()); @@ -126,9 +126,9 @@ public void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNo } private void recordFlow(@NotNull NetNode node, long amperes) { - EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.TYPE); if (logic == null) { - logic = EnergyFlowLogic.INSTANCE.getNew(); + logic = EnergyFlowLogic.TYPE.supplier().get(); node.getData().setLogicEntry(logic); } logic.recordFlow(getQueryTick(), new EnergyFlowData(amperes, pathVoltage)); @@ -159,7 +159,7 @@ public long getAsLong() { } public void doHeating(WorldPipeNetNode node, long finalVoltage, long tick) { - TemperatureLogic logic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + TemperatureLogic logic = (TemperatureLogic) node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); if (logic != null) { logic.applyThermalEnergy(calculateHeatV(amperage, finalVoltage, voltageCap), tick); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java index 561592916b..cd4b080630 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java @@ -1,23 +1,18 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractIntLogicData; - -import org.jetbrains.annotations.NotNull; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; public final class SuperconductorLogic extends AbstractIntLogicData { - public static final SuperconductorLogic INSTANCE = new SuperconductorLogic().setValue(0); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Superconductor", () -> new SuperconductorLogic().setValue(0)); public SuperconductorLogic() { - super("Superconductor"); + super(TYPE); } public boolean canSuperconduct(int temp) { return this.getValue() > temp; } - @Override - public @NotNull SuperconductorLogic getNew() { - return new SuperconductorLogic(); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java index 66e392f416..70b47ee9a6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java @@ -2,20 +2,14 @@ import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; - -import org.jetbrains.annotations.NotNull; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; public final class VoltageLimitLogic extends AbstractLongLogicData { - public static final VoltageLimitLogic INSTANCE = new VoltageLimitLogic().setValue(0); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("VoltageLimit", () -> new VoltageLimitLogic().setValue(0)); private VoltageLimitLogic() { - super("VoltageLimit"); - } - - @Override - public @NotNull VoltageLimitLogic getNew() { - return new VoltageLimitLogic().setValue(INSTANCE.getValue()); + super(TYPE); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java index 4447aa5a36..86fb4df271 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java @@ -2,20 +2,14 @@ import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; - -import org.jetbrains.annotations.NotNull; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; public final class VoltageLossLogic extends AbstractLongLogicData { - public static final VoltageLossLogic INSTANCE = new VoltageLossLogic().setValue(0); + public static final NetLogicEntryType INSTANCE = new NetLogicEntryType<>("VoltageLoss", () -> new VoltageLossLogic().setValue(0)); private VoltageLossLogic() { - super("VoltageLoss"); - } - - @Override - public @NotNull VoltageLossLogic getNew() { - return new VoltageLossLogic(); + super(INSTANCE); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java index f971dc56cc..14c27e162c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java @@ -54,7 +54,7 @@ public FluidCapabilityO WorldPipeNetNode node) { this.net = net; this.node = node; - this.tanks = node.getData().getLogicEntryDefaultable(ChannelCountLogic.INSTANCE) + this.tanks = node.getData().getLogicEntryDefaultable(ChannelCountLogic.TYPE) .getValue(); for (Direction facing : GTUtil.DIRECTIONS) { AbstractNetFlowEdge edge = (AbstractNetFlowEdge) net.getNewEdge(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java index 00475ad9cf..42fbf11c56 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.fluids.FluidState; import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.nbt.CompoundTag; @@ -15,7 +16,6 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.BitSet; import java.util.Collection; @@ -24,7 +24,7 @@ public final class FluidContainmentLogic extends NetLogicEntry { - public static final FluidContainmentLogic INSTANCE = new FluidContainmentLogic().contain(FluidState.LIQUID); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("FluidContainment", () -> new FluidContainmentLogic().contain(FluidState.LIQUID)); private int maximumTemperature; @@ -32,13 +32,13 @@ public final class FluidContainmentLogic extends NetLogicEntry containableStates = EnumSet.noneOf(FluidState.class); public FluidContainmentLogic() { - super("FluidContainment"); + super(TYPE); } public @NotNull FluidContainmentLogic getWith(Collection states, @NotNull Collection attributes, int maximumTemperature) { - FluidContainmentLogic logic = getNew(); + FluidContainmentLogic logic = new FluidContainmentLogic(); logic.containableStates.addAll(states); for (FluidAttribute attribute : attributes) { logic.contain(attribute); @@ -88,13 +88,13 @@ public int getMaximumTemperature() { } @Override - public @Nullable FluidContainmentLogic union(NetLogicEntry other) { + public @NotNull FluidContainmentLogic union(NetLogicEntry other) { if (other instanceof FluidContainmentLogic logic) { if (this.containableAttributes.equals(logic.containableAttributes) && this.containableStates.equals(logic.containableStates)) { return this; } else { - FluidContainmentLogic returnable = getNew(); + FluidContainmentLogic returnable = new FluidContainmentLogic(); returnable.containableStates = EnumSet.copyOf(this.containableStates); returnable.containableStates.retainAll(logic.containableStates); returnable.containableAttributes.addAll(this.containableAttributes); @@ -126,11 +126,6 @@ public void deserializeNBT(CompoundTag nbt) { containableStates = GTUtil.maskToSet(FluidState.class, BitSet.valueOf(nbt.getByteArray("States"))); } - @Override - public @NotNull FluidContainmentLogic getNew() { - return new FluidContainmentLogic(); - } - @Override public void encode(FriendlyByteBuf buf, boolean fullChange) { buf.writeVarInt(containableAttributes.size()); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java index 9e6e3aa068..281adc7a8a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java @@ -83,9 +83,9 @@ public ReversibleLossOperator traverseToNode(@NotNull WorldPipeNetNode node, lon return result.getLossFunction(); } else { FluidContainmentLogic containmentLogic = node.getData() - .getLogicEntryDefaultable(FluidContainmentLogic.INSTANCE); + .getLogicEntryDefaultable(FluidContainmentLogic.TYPE); - TemperatureLogic temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + TemperatureLogic temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); if (temperatureLogic != null) { result = temperatureLogic.getLossResult(getQueryTick()); boolean overMax = fluidTemp > containmentLogic.getMaximumTemperature() && @@ -167,10 +167,10 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl public void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNode, long consumption) { super.consumeFlowLimit(edge, targetNode, consumption); - TemperatureLogic temperatureLogic = targetNode.getData().getLogicEntryNullable(TemperatureLogic.INSTANCE); + TemperatureLogic temperatureLogic = targetNode.getData().getLogicEntryNullable(TemperatureLogic.TYPE); if (temperatureLogic != null) { FluidContainmentLogic containmentLogic = targetNode.getData() - .getLogicEntryDefaultable(FluidContainmentLogic.INSTANCE); + .getLogicEntryDefaultable(FluidContainmentLogic.TYPE); boolean overMax = fluidTemp > containmentLogic.getMaximumTemperature() && !(state == FluidState.PLASMA && containmentLogic.contains(FluidState.PLASMA)); temperatureLogic.moveTowardsTemperature(fluidTemp, diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java index abde66fdf1..daef0dca2c 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/CableBlockProvider.java @@ -61,7 +61,7 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso return; } WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(blockAccessor.getPosition()); - EnergyFlowLogic logic = node.getData().getLogicEntryDefaultable(EnergyFlowLogic.INSTANCE); + EnergyFlowLogic logic = node.getData().getLogicEntryDefaultable(EnergyFlowLogic.TYPE); long currentTick = serverLevel.getServer().getTickCount(); long totalVoltage = 0L; From a2245bbada0d72b6de95b1e8bfd024c0514ee30b Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Wed, 4 Sep 2024 12:38:02 +0300 Subject: [PATCH 24/70] remove fluid pipe storage provider as it's useless now --- .../gtceu/integration/jade/GTJadePlugin.java | 4 -- .../provider/FluidPipeStorageProvider.java | 53 ------------------- 2 files changed, 57 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java index abf772f9d4..e2128f8a6f 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java @@ -44,8 +44,6 @@ public void register(IWailaCommonRegistration registration) { registration.registerBlockDataProvider(new MEPatternBufferProxyProvider(), BlockEntity.class); registration.registerBlockDataProvider(new MEPatternBufferProvider(), BlockEntity.class); } - - registration.registerFluidStorage(FluidPipeStorageProvider.INSTANCE, MaterialPipeBlockEntity.class); } @Override @@ -70,8 +68,6 @@ public void registerClient(IWailaClientRegistration registration) { registration.registerBlockComponent(new MEPatternBufferProxyProvider(), Block.class); registration.registerBlockComponent(new MEPatternBufferProvider(), Block.class); } - - registration.registerFluidStorageClient(FluidPipeStorageProvider.INSTANCE); } static { diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java deleted file mode 100644 index e20f69e1d3..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/FluidPipeStorageProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.gregtechceu.gtceu.integration.jade.provider; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; - -import org.jetbrains.annotations.NotNull; -import snownee.jade.api.Accessor; -import snownee.jade.api.view.*; - -import java.util.ArrayList; -import java.util.List; - -public enum FluidPipeStorageProvider implements IServerExtensionProvider, - IClientExtensionProvider { - - INSTANCE; - - @Override - public List> getClientGroups(Accessor accessor, List> groups) { - return ClientViewGroup.map(groups, FluidView::readDefault, (group, clientGroup) -> { - if (group.id != null) { - clientGroup.title = Component.literal(group.id); - } - clientGroup.bgColor = 0x55666666; - }); - } - - @Override - public @NotNull List> getGroups(ServerPlayer serverPlayer, ServerLevel serverLevel, - MaterialPipeBlockEntity pipe, boolean showDetails) { - List> tanks = new ArrayList<>(); - /* - * for (var tank : pipe.getFluidTanks()) { - * if (tank.getFluidAmount() > 0) { - * tanks.add(new ViewGroup<>(List.of(FluidView.writeDefault( - * JadeFluidObject.of(tank.getFluid().getFluid(), tank.getFluidAmount()), tank.getCapacity())))); - * } - * } - */ - return tanks; - } - - @Override - public ResourceLocation getUid() { - return GTCEu.id("fluid_storage"); - } -} From dd298ab12c6d117f910ef5adf44c3f4b42c5212a Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:13:33 +0300 Subject: [PATCH 25/70] update with changes from 1.12 --- .../gtceu/api/graphnet/MultiNodeHelper.java | 8 +- .../gtceu/api/graphnet/NetGroup.java | 1 + .../DynamicWeightsShortestPathsAlgorithm.java | 7 +- .../graphnet/alg/ShortestPathsAlgorithm.java | 5 +- .../api/graphnet/logic/NetLogicData.java | 36 +--- .../gtceu/api/graphnet/path/INetPath.java | 5 - .../api/graphnet/pipenet/WorldPipeNet.java | 3 +- .../graphnet/pipenet/WorldPipeNetNode.java | 4 +- .../pipenet/physical/IPipeStructure.java | 4 +- .../physical/tile/PipeBlockEntity.java | 15 +- .../predicate/test/FluidTestObject.java | 2 +- .../predicate/test/ItemTestObject.java | 11 +- .../traverse/AbstractTraverseData.java | 4 + .../traverse/IEqualizableTraverseData.java | 12 ++ .../graphnet/traverse/TraverseHelpers.java | 2 +- .../gtceu/api/graphnet/worldnet/WorldNet.java | 25 --- .../api/graphnet/worldnet/WorldPosNet.java | 47 +++++ ...WorldNetNode.java => WorldPosNetNode.java} | 6 +- .../gregtechceu/gtceu/client/ClientProxy.java | 1 + .../renderer/pipe/AbstractPipeModel.java | 22 +- .../renderer/pipe/PipeModelRedirector.java | 2 +- .../renderer/pipe/PipeModelRegistry.java | 18 +- .../renderer/pipe/cache/ColorQuadCache.java | 10 +- .../pipe/cover/CoverRendererBuilder.java | 7 +- .../renderer/pipe/quad/PipeQuadHelper.java | 50 ++--- .../client/renderer/pipe/quad/QuadHelper.java | 8 +- .../pipe/quad/RecolorableBakedQuad.java | 197 +++--------------- .../client/renderer/pipe/quad/UVMapper.java | 26 ++- .../client/renderer/pipe/util/ColorData.java | 13 +- .../pipe/util/MaterialModelOverride.java | 4 +- .../common/cover/FluidRegulatorCover.java | 28 ++- .../gtceu/common/cover/RobotArmCover.java | 23 +- .../gtceu/common/data/GTBlocks.java | 8 + .../net/fluid/FluidEQTraverseData.java | 25 +++ .../pipelike/net/item/ItemEQTraverseData.java | 22 ++ .../com/gregtechceu/gtceu/utils/GTUtil.java | 4 +- .../reference/RegeneratingSoftReference.java | 44 ++++ .../gtceu/utils/reference/WeakHashSet.java | 135 ++++++++++++ 38 files changed, 490 insertions(+), 354 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java rename src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/{WorldNetNode.java => WorldPosNetNode.java} (85%) create mode 100644 src/main/java/com/gregtechceu/gtceu/utils/reference/RegeneratingSoftReference.java create mode 100644 src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java index 8e7cf76862..2db9b611fc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/MultiNodeHelper.java @@ -86,7 +86,6 @@ public void addNode(@NotNull NetNode node) { public void removeNode(@NotNull NetNode node) { LogicDataHandler removed = handledDatas.remove(node.getNet()); if (removed != null) { - removed.invalidate(); for (NetLogicEntry entry : this.mergedData.getEntries()) { node.getData().removeLogicEntry(entry); entry.unmerge(node); @@ -103,19 +102,14 @@ private void addNewLogicEntry(@NotNull NetLogicEntry entry) { protected class LogicDataHandler implements NetLogicData.ILogicDataListener { public final WeakReference nodeRef; - public final @NotNull NetLogicData.LogicDataListener listener; public final @NotNull NetLogicData data; public LogicDataHandler(@NotNull NetNode node) { this.data = node.getData(); - this.listener = data.createListener(this); + data.addListener(this); this.nodeRef = new WeakReference<>(node); } - public void invalidate() { - this.listener.invalidate(); - } - @Override public void markChanged(NetLogicEntry updatedEntry, boolean removed, boolean fullChange) { if (!fullChange || !updatedEntry.mergedToMultiNodeHelper()) return; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java index 412b80215d..8146f3c334 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/NetGroup.java @@ -134,6 +134,7 @@ public void splitNode(NetNode source) { NetNode temp; while (i.hasNext()) { temp = i.next(); + if (temp == source) continue; targetGroup.add(temp); // if we find a target node in our search, remove it from the list targets.remove(temp); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java index 5b3185e9ff..e9aa579e9e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java @@ -34,7 +34,8 @@ public DynamicWeightsShortestPathsAlgorithm(IGraphNet net, boolean recomputeEver public > IteratorFactory getPathsIteratorFactory(GraphVertex source, NetPathMapper remapper) { Set searchSpace = source.wrapped.getGroupSafe().getNodes().stream().filter(NetNode::isActive) - .map(n -> n.wrapper).filter(node -> !source.equals(node)).collect(Collectors.toSet()); + .map(n -> n.wrapper).filter(node -> !(source == node) && graph.containsVertex(node)) + .collect(Collectors.toSet()); return (graph, testObject, simulator, queryTick) -> { if (recomputeEveryCall) graph.prepareForAlgorithmRun(testObject, simulator, queryTick); return new LimitedIterator<>(source, searchSpace, remapper); @@ -79,6 +80,7 @@ private void calculateNext() { next = remapper.map(source); return; } + searchSpace.removeIf(vertex -> !graph.containsVertex(vertex)); ManyToManyShortestPaths paths = getManyToManyPaths(Collections.singleton(source), searchSpace); Optional next = searchSpace.stream().map(node -> paths.getPath(source, node)).filter(Objects::nonNull) @@ -89,7 +91,8 @@ private void calculateNext() { private boolean isUnique(Path path) { for (Path other : visited) { - if (path.matches(other)) return false; + if (path.getOrderedNodes().equals(other.getOrderedNodes()) && + path.getOrderedEdges().equals(other.getOrderedEdges())) return false; } return true; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java index 5d4b89d16a..272c94b2ef 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/ShortestPathsAlgorithm.java @@ -41,8 +41,9 @@ public ShortestPathsAlgorithm(IGraphNet net, boolean recomputeEveryCall) { return SimpleIteratorFactories.fromSingleton(path); } - Set searchSpace = source.wrapped.getGroupSafe().getNodes().stream() - .filter(NetNode::isActive).map(n -> n.wrapper).collect(Collectors.toSet()); + Set searchSpace = source.wrapped.getGroupSafe().getNodes().stream().filter(NetNode::isActive) + .map(n -> n.wrapper).filter(node -> !source.equals(node) && graph.containsVertex(node)) + .collect(Collectors.toSet()); Set singleton = Collections.singleton(source); if (recomputeEveryCall) { return (graph1, testObject, simulator, queryTick) -> { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index 6d07ecd816..9009ef558f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.api.graphnet.logic; +import com.jozufozu.flywheel.util.WeakHashSet; import com.lowdragmc.lowdraglib.syncdata.IContentChangeAware; import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; @@ -35,7 +36,7 @@ public final class NetLogicData implements ITagSerializable, IContentCh // TODO caching logic on simple logics to reduce amount of reduntant creation? private final Object2ObjectOpenHashMap, NetLogicEntry> logicEntrySet; - private final Set listeners = new ObjectOpenHashSet<>(); + private final WeakHashSet listeners = new WeakHashSet<>(); public NetLogicData() { logicEntrySet = new Object2ObjectOpenHashMap<>(4); @@ -167,10 +168,6 @@ public boolean hasLogicEntry(@NotNull NetLogicEntry key) { return new NetLogicData(newLogic); } - public void addListener(LogicDataListener listener) { - this.listeners.add(listener); - } - @Override public ListTag serializeNBT() { ListTag list = new ListTag(); @@ -223,26 +220,15 @@ public void decode(FriendlyByteBuf buf) { this.logicEntrySet.trim(); } - public LogicDataListener createListener(ILogicDataListener listener) { - return new LogicDataListener(listener); - } - - public final class LogicDataListener { - - private final ILogicDataListener listener; - - private LogicDataListener(ILogicDataListener listener) { - this.listener = listener; - } - - private void markChanged(NetLogicEntry updatedEntry, boolean removed, boolean fullChange) { - this.listener.markChanged(updatedEntry, removed, fullChange); - } - - // TODO would a weak set be better? - public void invalidate() { - listeners.remove(this); - } + /** + * Adds a listener to a weak set which is then notified for as long as it is not collected by the garbage collector. + * + * @param listener the listener. + * @return the listener, for convenience when working with lambdas. + */ + public ILogicDataListener addListener(ILogicDataListener listener) { + this.listeners.add(listener); + return listener; } @FunctionalInterface diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java index adef782790..4971bdd26f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java @@ -29,11 +29,6 @@ default N getTargetNode() { double getWeight(); - default boolean matches(@NotNull INetPath other) { - return WEIGHT_COMPARATOR.compare(getWeight(), other.getWeight()) == 0 && - getOrderedNodes().equals(other.getOrderedNodes()) && getOrderedEdges().equals(other.getOrderedEdges()); - } - NetLogicData getUnifiedNodeData(); @Nullable diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index 13f2d9b9d8..879f077cc4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -12,6 +12,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNet; +import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldPosNet; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.core.BlockPos; @@ -34,7 +35,7 @@ import java.util.function.Function; import java.util.stream.Stream; -public abstract class WorldPipeNet extends WorldNet { +public abstract class WorldPipeNet extends WorldPosNet { public static final int MULTI_NET_TIMEOUT = 10; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java index f0fcf2e187..30370cb44e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNetNode.java @@ -4,7 +4,7 @@ import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.IWorldPipeNetTile; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNetNode; +import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldPosNetNode; import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTMaterials; @@ -18,7 +18,7 @@ import java.lang.ref.WeakReference; -public final class WorldPipeNetNode extends WorldNetNode { +public final class WorldPipeNetNode extends WorldPosNetNode { private static final PipeBlockEntity FALLBACK = new PipeBlockEntity(GTBlockEntities.PIPE.get(), BlockPos.ZERO, GTBlocks.MATERIAL_PIPE_BLOCKS.get(TagPrefix.pipeNormal, GTMaterials.Aluminium).getDefaultState()); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java index 73d3fc874a..f8cbccc2d0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -44,11 +44,11 @@ default boolean canConnectTo(Direction side, byte connectionMask) { default VoxelShape getPipeBoxes(@NotNull PipeBlockEntity tileContext) { VoxelShape pipeBoxes = Shapes.empty(); float thickness = getRenderThickness(); - if ((tileContext.getConnectionMask() & 63) < 63) { + if ((tileContext.getCoverAdjustedConnectionMask() & 63) < 63) { pipeBoxes = Shapes.or(pipeBoxes, getSideBox(null, thickness)); } for (Direction facing : GTUtil.DIRECTIONS) { - if (tileContext.isConnected(facing)) pipeBoxes = Shapes.or(pipeBoxes, getSideBox(facing, thickness)); + if (tileContext.isConnectedCoverAdjusted(facing)) pipeBoxes = Shapes.or(pipeBoxes, getSideBox(facing, thickness)); } return pipeBoxes; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 5bcf9f28d6..1495008c7c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -32,8 +32,6 @@ import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.utils.GTUtil; -import com.gregtechceu.gtceu.utils.TaskHandler; -import com.gregtechceu.gtceu.utils.TaskScheduler; import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; @@ -79,7 +77,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -103,7 +100,6 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity public static final int UPDATE_PIPE_LOGIC = 0; private final Int2ObjectOpenHashMap netLogicDatas = new Int2ObjectOpenHashMap<>(); - private final ObjectOpenHashSet listeners = new ObjectOpenHashSet<>(); // information that is only required for determining graph topology should be stored on the tile entity level, // while information interacted with during graph traversal should be stored on the NetLogicData level. @@ -134,7 +130,7 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity @Persisted @DescSynced @Getter - protected final PipeCoverHolder covers = new PipeCoverHolder(this); + protected final PipeCoverHolder coverHolder = new PipeCoverHolder(this); @Getter private final Object2ObjectOpenHashMap, IPipeCapabilityObject> capabilities = new Object2ObjectOpenHashMap<>(); private final Object2ObjectOpenCustomHashMap netCapabilities = WorldPipeNet @@ -497,15 +493,13 @@ protected void initialize() { this.netLogicDatas.clear(); this.capabilities.clear(); this.netCapabilities.clear(); - this.listeners.forEach(NetLogicData.LogicDataListener::invalidate); - this.listeners.clear(); boolean firstNode = true; for (WorldPipeNetNode node : PipeBlock.getNodesForTile(this)) { this.addCapabilities(node.getNet().getNewCapabilityObjects(node)); this.netCapabilities.put(node, new PipeCapabilityWrapper(this, node)); int networkID = node.getNet().getNetworkID(); netLogicDatas.put(networkID, node.getData()); - var listener = node.getData().createListener( + node.getData().addListener( (e, r, f) -> writeCustomData(UPDATE_PIPE_LOGIC, buf -> { buf.writeVarInt(networkID); buf.writeUtf(e.getType().id()); @@ -515,8 +509,6 @@ protected void initialize() { e.encode(buf, f); } })); - this.listeners.add(listener); - node.getData().addListener(listener); // Manually resync the data, as it's loaded & the listeners are queried for the first time *before* // we call `addListener` on the line above. for (var entry : node.getData().getEntries()) { @@ -528,7 +520,6 @@ protected void initialize() { } } this.netLogicDatas.trim(); - this.listeners.trim(); this.capabilities.trim(); this.netCapabilities.trim(); updateActiveStatus(null, false); @@ -787,7 +778,7 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, S if (gridSide == null) gridSide = hitResult.getDirection(); // Prioritize covers where they apply (Screwdriver, Soft Mallet) - if (toolTypes.contains(GTToolType.SCREWDRIVER)) { + if (toolTypes.contains(GTToolType.SCREWDRIVER) || (itemStack.isEmpty() && playerIn.isShiftKeyDown())) { if (coverBehavior != null) { return Pair.of(GTToolType.SCREWDRIVER, coverBehavior.onScrewdriverClick(playerIn, hand, hitResult)); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java index 36c846ee2e..513fc520de 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/FluidTestObject.java @@ -15,7 +15,7 @@ public final class FluidTestObject implements IPredicateTestObject, Predicate { public final Fluid fluid; - public final CompoundTag tag; + public final @Nullable CompoundTag tag; private final int hash; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java index b20d910777..3f8c7feffc 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java @@ -6,6 +6,7 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Objects; import java.util.function.Predicate; @@ -13,7 +14,7 @@ public class ItemTestObject implements IPredicateTestObject, Predicate { public final Item item; - public final CompoundTag tag; + public final @Nullable CompoundTag tag; public final int stackLimit; @@ -29,13 +30,17 @@ public ItemTestObject(@NotNull ItemStack stack) { @Override @Contract(" -> new") public ItemStack recombine() { - return new ItemStack(item, 1, tag); + ItemStack stack = new ItemStack(item, 1); + stack.setTag(tag.copy()); + return stack; } @Contract("_ -> new") public ItemStack recombine(int amount) { assert amount <= getStackLimit() && amount > 0; - return new ItemStack(item, amount, tag); + ItemStack stack = new ItemStack(item, amount); + stack.setTag(tag.copy()); + return stack; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java index d3798c3a48..b959c79276 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java @@ -38,6 +38,10 @@ public IPredicateTestObject getTestObject() { return simulator; } + public boolean simulating() { + return simulator != null; + } + @Override public long getQueryTick() { return queryTick; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java index c205edb835..b132e5a330 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/IEqualizableTraverseData.java @@ -20,4 +20,16 @@ public interface IEqualizableTraverseData> long traverseEqualDistribution( if (pathFlow <= 0) continue pathloop; } - long accepted = data.finalizeAtDestination(nodes.get(nodes.size() - 1), pathFlow); + long accepted = data.finalizeAtDestination(nodes.get(nodes.size() - 1), pathFlow, entry.getIntValue()); if (!simulate) pathTraverseCalls.forEach(Runnable::run); availableFlow -= stack.consumeWithEndValue(accepted); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java index f3baac9744..4781538698 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -13,7 +13,6 @@ import com.gregtechceu.gtceu.api.graphnet.path.GenericGraphNetPath; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; -import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceKey; @@ -54,26 +53,12 @@ public Iterator getPaths(NetNode node, IPredicateTestObject return backer.getPaths(node, 0, GenericGraphNetPath.MAPPER, testObject, simulator, queryTick); } - @NotNull - public WorldNetNode getOrCreateNode(@NotNull BlockPos pos) { - WorldNetNode node = getNode(pos); - if (node != null) return node; - node = getNewNode(); - node.setPos(pos); - addNode(node); - return node; - } - @Override public void addNode(@NotNull NetNode node) { nodeClassCheck(node); this.backer.addNode(node); } - public @Nullable WorldNetNode getNode(@NotNull BlockPos equivalencyData) { - return (WorldNetNode) getNode((Object) equivalencyData); - } - @Override public @Nullable NetNode getNode(@NotNull Object equivalencyData) { return backer.getNode(equivalencyData); @@ -136,14 +121,4 @@ public void load(@NotNull CompoundTag nbt) { public GraphNetBacker getBacker() { return backer; } - - @Override - public Class getNodeClass() { - return WorldNetNode.class; - } - - @Override - public @NotNull WorldNetNode getNewNode() { - return new WorldNetNode(this); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java new file mode 100644 index 0000000000..9c7f34fe57 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java @@ -0,0 +1,47 @@ +package com.gregtechceu.gtceu.api.graphnet.worldnet; + +import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; +import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; +import net.minecraft.core.BlockPos; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Function; + +public abstract class WorldPosNet extends WorldNet { + + public WorldPosNet(@NotNull Function graphBuilder, + AlgorithmBuilder... algorithmBuilders) { + super(graphBuilder, algorithmBuilders); + } + + public WorldPosNet(boolean directed, AlgorithmBuilder... algorithmBuilders) { + super(directed, algorithmBuilders); + } + + @NotNull + public WorldPosNetNode getOrCreateNode(@NotNull BlockPos pos) { + WorldPosNetNode node = getNode(pos); + if (node != null) return node; + node = getNewNode(); + node.setPos(pos); + addNode(node); + return node; + } + + public @Nullable WorldPosNetNode getNode(@NotNull BlockPos equivalencyData) { + return (WorldPosNetNode) getNode((Object) equivalencyData); + } + + @Override + public Class getNodeClass() { + return WorldPosNetNode.class; + } + + @Override + public @NotNull WorldPosNetNode getNewNode() { + return new WorldPosNetNode(this); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNetNode.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNetNode.java similarity index 85% rename from src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNetNode.java rename to src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNetNode.java index cce387e1d9..efa137034a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNetNode.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNetNode.java @@ -7,11 +7,11 @@ import org.jetbrains.annotations.NotNull; -public class WorldNetNode extends NetNode { +public class WorldPosNetNode extends NetNode { private BlockPos pos; - public WorldNetNode(WorldNet net) { + public WorldPosNetNode(WorldNet net) { super(net); } @@ -20,7 +20,7 @@ public WorldNetNode(WorldNet net) { return (WorldNet) super.getNet(); } - public WorldNetNode setPos(BlockPos pos) { + public WorldPosNetNode setPos(BlockPos pos) { this.pos = pos; return this; } diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index 1e836b4c63..b372e7595d 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -94,6 +94,7 @@ public void onRegisterParticleProviders(RegisterParticleProvidersEvent event) { @SubscribeEvent public void modifyModels(ModelEvent.ModifyBakingResult event) { + AbstractPipeModel.invalidateCaches(); PipeModelRegistry.registerModels(event.getModels()::put); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index c353743686..90c452c01d 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -11,6 +11,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; +import com.gregtechceu.gtceu.utils.reference.WeakHashSet; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.RenderType; @@ -53,8 +54,21 @@ public abstract class AbstractPipeModel { public static final ModelProperty MATERIAL_PROPERTY = new ModelProperty<>(); protected final Object2ObjectOpenHashMap frameCache = new Object2ObjectOpenHashMap<>(); - protected final Object2ObjectOpenHashMap pipeCache = new Object2ObjectOpenHashMap<>(); + protected final Object2ObjectOpenHashMap pipeCache; + protected static final WeakHashSet> PIPE_CACHES = new WeakHashSet<>(); + + public static void invalidateCaches() { + for (var cache : PIPE_CACHES) { + cache.clear(); + cache.trim(16); + } + } + + public AbstractPipeModel() { + pipeCache = new Object2ObjectOpenHashMap<>(); + PIPE_CACHES.add(pipeCache); + } public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData modelData, @Nullable RenderType renderType) { @@ -105,11 +119,7 @@ protected static int safeInt(@Nullable Integer integer) { @Nullable Material frameMaterial, byte frameMask, byte coverMask) { List quads = new ObjectArrayList<>(); - StructureQuadCache cache = pipeCache.get(key); - if (cache == null) { - cache = constructForKey(key); - pipeCache.put(key, cache); - } + StructureQuadCache cache = pipeCache.computeIfAbsent(key, this::constructForKey); cache.addToList(quads, connectionMask, closedMask, blockedMask, data, coverMask); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java index f924794f21..17708fc1c4 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java @@ -101,7 +101,7 @@ public TextureAtlasSprite getParticleIcon() { } @FunctionalInterface - public interface Supplier { + public interface ModelRedirectorSupplier { PipeModelRedirector create(ModelResourceLocation loc, MaterialModelSupplier supplier, Function stackMaterialFunction); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java index 57742ca990..8e9c5ac1cf 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -17,11 +17,13 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Range; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; +import java.util.Objects; import java.util.function.BiConsumer; public final class PipeModelRegistry { @@ -131,7 +133,7 @@ public static void registerModels(@NotNull BiConsumer { PipeMaterialBlock pipe = PipeMaterialBlock.getBlockFromItem(stack); @@ -174,13 +176,13 @@ private static void initPipes() { array[4] = new PipeModel(pipeHuge, pipeSide, false); array[5] = new PipeModel(pipeQuadruple, pipeSide, false); array[6] = new PipeModel(pipeNonuple, pipeSide, false); - PIPE_OVERRIDES.add(new MaterialModelOverride.StandardOverride<>(array, m -> true)); + PIPE_OVERRIDES.addAndMoveToLast(new MaterialModelOverride.StandardOverride<>(array, m -> true)); array = new PipeModel[PIPE_MODEL_COUNT]; array[1] = new PipeModel(pipeSmallWood, pipeSideWood, false); array[2] = new PipeModel(pipeNormalWood, pipeSideWood, false); array[3] = new PipeModel(pipeLargeWood, pipeSideWood, false); - registerPipeOverride(new MaterialModelOverride.StandardOverride<>(array, m -> m.hasProperty(PropertyKey.WOOD))); + registerPipeOverride(new MaterialModelOverride.StandardOverride<>(array, m -> m != null && m.hasProperty(PropertyKey.WOOD))); array = new PipeModel[PIPE_MODEL_COUNT]; array[0] = new PipeModel(pipeTiny, pipeSide, true); @@ -190,7 +192,7 @@ private static void initPipes() { array[4] = new PipeModel(pipeHuge, pipeSide, true); array[5] = new PipeModel(pipeQuadruple, pipeSide, true); array[6] = new PipeModel(pipeNonuple, pipeSide, true); - PIPE_RESTRICTIVE_OVERRIDES.add(new MaterialModelOverride.StandardOverride<>(array, m -> true)); + PIPE_RESTRICTIVE_OVERRIDES.addAndMoveToLast(new MaterialModelOverride.StandardOverride<>(array, m -> true)); ResourceLocation loc = GTCEu.id("block/pipe_material"); for (int i = 0; i < PIPE_MODEL_COUNT; i++) { @@ -201,7 +203,7 @@ private static void initPipes() { } } - private static PipeModel getOrCachePipeModel(Material m, int i) { + private static PipeModel getOrCachePipeModel(@Nullable Material m, int i) { if (m == null) return PIPE_OVERRIDES.last().getModel(null, i); PipeModel[] cached = PIPE.computeIfAbsent(m, k -> new PipeModel[PIPE_MODEL_COUNT]); PipeModel selected = cached[i]; @@ -230,13 +232,13 @@ private static PipeModel getOrCachePipeRestrictiveModel(Material m, int i) { } private static void initCables() { - CABLE_OVERRIDES.add(new MaterialModelOverride.PerMaterialOverride<>( + CABLE_OVERRIDES.addAndMoveToLast(new MaterialModelOverride.PerMaterialOverride<>( Tables.newCustomTable(new IdentityHashMap<>(), Int2ObjectOpenHashMap::new), (material, insulation) -> { if (insulation == 0) { return new CableModel(material); } return new CableModel(material, CableModel.INSULATION[insulation - 1], CableModel.INSULATION_FULL); - }, m -> true)); + }, Objects::nonNull)); ResourceLocation loc = GTCEu.id("block/cable"); for (int i = 0; i < CABLE_MODEL_COUNT; i++) { @@ -245,7 +247,7 @@ private static void initCables() { } } - private static CableModel getOrCacheCableModel(Material m, int i) { + private static CableModel getOrCacheCableModel(@Nullable Material m, int i) { if (m == null) return CABLE_OVERRIDES.last().getModel(null, i); CableModel[] cached = CABLE.computeIfAbsent(m, k -> new CableModel[CABLE_MODEL_COUNT]); CableModel selected = cached[i]; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java index be595792f4..3f494917e5 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java @@ -3,6 +3,8 @@ import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; +import com.gregtechceu.gtceu.utils.reference.RegeneratingSoftReference; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -11,13 +13,11 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.List; +import java.util.Map; @OnlyIn(Dist.CLIENT) public final class ColorQuadCache { - // TODO dynamic cache growth & collapse - private static final int CACHE_LIMIT = 20; - private final List prototypes; private final Object2ObjectLinkedOpenHashMap> cache; @@ -28,14 +28,14 @@ public ColorQuadCache(List prototypes) { } public List getQuads(ColorData data) { - List existing = cache.getAndMoveToFirst(data); + List existing = cache.get(data); if (existing == null) { existing = new ObjectArrayList<>(); for (RecolorableBakedQuad quad : prototypes) { existing.add(quad.withColor(data)); } cache.put(data, existing); - if (cache.size() > CACHE_LIMIT) cache.removeLast(); +// if (cache.size() > 20) cache.removeLast(); } return existing; } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java index 1470421436..c68eef40ed 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java @@ -75,19 +75,18 @@ public class CoverRendererBuilder { public static ColorQuadCache buildPlates(SpriteInformation sprite) { List quads = new ObjectArrayList<>(); - UVMapper mapper = UVMapper.standard(0); for (Direction facing : GTUtil.DIRECTIONS) { - PLATE_COORDS.put(facing, buildPlates(quads, facing, mapper, sprite)); + PLATE_COORDS.put(facing, buildPlates(quads, facing, sprite)); } return new ColorQuadCache(quads); } protected static SubListAddress buildPlates(List quads, Direction facing, - UVMapper mapper, SpriteInformation sprite) { + SpriteInformation sprite) { int start = quads.size(); Pair box = PLATE_BOXES.get(facing); for (Direction dir : Direction.values()) { - quads.add(QuadHelper.buildQuad(dir, box, mapper, sprite)); + quads.add(QuadHelper.buildQuad(dir, box, CoverRendererBuilder.defaultMapper, sprite)); } return new SubListAddress(start, quads.size()); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java index b8227c8ffa..1ce57e376c 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -11,6 +11,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; import org.joml.Vector3f; import java.util.EnumMap; @@ -60,7 +61,7 @@ public int getLayerCount() { } private void generateBox(float xS, float xL, float yS, float yL, float zS, float zL, - OverlayLayerDefinition definition) { + @NotNull OverlayLayerDefinition definition) { coreBoxList.add(definition.computeBox(null, xS, yS, zS, xL, yL, zL)); EnumMap> sideBoxes = new EnumMap<>(Direction.class); sideBoxes.put(Direction.DOWN, definition.computeBox(Direction.DOWN, xS, 0, zS, xL, yS, zL)); @@ -72,13 +73,14 @@ private void generateBox(float xS, float xL, float yS, float yL, float zS, float sideBoxesList.add(sideBoxes); } - public static PipeQuadHelper create(float thickness, double x, double y, double z) { + @Contract("_, _, _, _ -> new") + public static @NotNull PipeQuadHelper create(float thickness, double x, double y, double z) { float small = 0.5f - thickness / 2; float large = 0.5f + thickness / 2; return new PipeQuadHelper((float) x, (float) y, (float) z, small, large); } - - public static PipeQuadHelper create(float thickness) { + @Contract("_ -> new") + public static @NotNull PipeQuadHelper create(float thickness) { return create(thickness, 0, 0, 0); } @@ -86,59 +88,57 @@ public void setTargetSprite(SpriteInformation sprite) { this.targetSprite = sprite; } - public RecolorableBakedQuad visitCore(Direction facing) { + public @NotNull RecolorableBakedQuad visitCore(Direction facing) { return visitCore(facing, 0); } - public RecolorableBakedQuad visitCore(Direction facing, int overlayLayer) { + public @NotNull RecolorableBakedQuad visitCore(Direction facing, int overlayLayer) { return visitQuad(facing, coreBoxList.get(overlayLayer), UVMapper.standard(0)); } - public List visitTube(Direction facing) { + public @NotNull List visitTube(Direction facing) { return visitTube(facing, 0); } - public List visitTube(Direction facing, int overlayLayer) { + public @NotNull List visitTube(Direction facing, int overlayLayer) { List list = new ObjectArrayList<>(); Pair box = sideBoxesList.get(overlayLayer).get(facing); switch (facing.getAxis()) { case X -> { - UVMapper mapper = UVMapper.standard(0); - list.add(visitQuad(Direction.UP, box, mapper)); - list.add(visitQuad(Direction.DOWN, box, mapper)); - list.add(visitQuad(Direction.SOUTH, box, mapper)); - list.add(visitQuad(Direction.NORTH, box, UVMapper.standard(180))); + list.add(visitQuad(Direction.UP, box, UVMapper.standard(0))); + list.add(visitQuad(Direction.DOWN, box, UVMapper.standard(0))); + list.add(visitQuad(Direction.SOUTH, box, UVMapper.standard(0))); + list.add(visitQuad(Direction.NORTH, box, UVMapper.flipped(0))); } case Y -> { - UVMapper mapper = UVMapper.standard(0); - list.add(visitQuad(Direction.EAST, box, UVMapper.standard(270))); - list.add(visitQuad(Direction.WEST, box, UVMapper.standard(270))); - list.add(visitQuad(Direction.SOUTH, box, mapper)); - list.add(visitQuad(Direction.NORTH, box, mapper)); + list.add(visitQuad(Direction.EAST, box, UVMapper.standard(0))); + list.add(visitQuad(Direction.WEST, box, UVMapper.standard(0))); + list.add(visitQuad(Direction.SOUTH, box, UVMapper.standard(0))); + list.add(visitQuad(Direction.NORTH, box, UVMapper.standard(0))); } case Z -> { - list.add(visitQuad(Direction.UP, box, UVMapper.standard(180))); + list.add(visitQuad(Direction.UP, box, UVMapper.flipped(0))); list.add(visitQuad(Direction.DOWN, box, UVMapper.standard(0))); - list.add(visitQuad(Direction.EAST, box, UVMapper.standard(270))); - list.add(visitQuad(Direction.WEST, box, UVMapper.standard(90))); + list.add(visitQuad(Direction.EAST, box, UVMapper.flipped(0))); + list.add(visitQuad(Direction.WEST, box, UVMapper.standard(0))); } } return list; } - public RecolorableBakedQuad visitCapper(Direction facing) { + public @NotNull RecolorableBakedQuad visitCapper(Direction facing) { return visitCapper(facing, 0); } - public RecolorableBakedQuad visitCapper(Direction facing, int overlayLayer) { + public @NotNull RecolorableBakedQuad visitCapper(Direction facing, int overlayLayer) { return visitQuad(facing, sideBoxesList.get(overlayLayer).get(facing), UVMapper.standard(0)); } - public RecolorableBakedQuad visitQuad(Direction normal, Pair box, UVMapper uv) { + public @NotNull RecolorableBakedQuad visitQuad(Direction normal, Pair box, UVMapper uv) { return QuadHelper.buildQuad(normal, box, uv, targetSprite); } - public static List createFrame(TextureAtlasSprite sprite) { + public static @NotNull List createFrame(TextureAtlasSprite sprite) { PipeQuadHelper helper = PipeQuadHelper.create(0.998f).initialize(); helper.setTargetSprite(new SpriteInformation(sprite, 0)); List list = new ObjectArrayList<>(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java index e7bd5a29fa..8952a34a55 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -25,16 +25,16 @@ public final class QuadHelper { private QuadHelper() {} - public static RecolorableBakedQuad buildQuad(Direction normal, Pair box, - UVMapper uv, SpriteInformation targetSprite) { + public static @NotNull RecolorableBakedQuad buildQuad(Direction normal, Pair box, + @NotNull UVMapper uv, @NotNull SpriteInformation targetSprite) { BlockElementFace face = new BlockElementFace(null, -1, targetSprite.sprite().contents().name().toString(), uv.map(normal, box), ForgeFaceData.DEFAULT); return StaticFaceBakery.bakeRecolorableQuad(box.getLeft(), box.getRight(), face, targetSprite, normal, BlockModelRotation.X0_Y0, null, true, 0); } - public static BakedQuad buildQuad(Direction normal, Pair box, - UVMapper uv, TextureAtlasSprite targetSprite) { + public static @NotNull BakedQuad buildQuad(Direction normal, Pair box, + @NotNull UVMapper uv, @NotNull TextureAtlasSprite targetSprite) { BlockElementFace face = new BlockElementFace(null, -1, targetSprite.contents().name().toString(), uv.map(normal, box)); return StaticFaceBakery.bakeQuad(box.getLeft(), box.getRight(), face, targetSprite, normal, diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java index 3a3f0c8f67..cb9b1d5d99 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; @@ -22,184 +23,34 @@ @OnlyIn(Dist.CLIENT) public class RecolorableBakedQuad extends BakedQuad { + private final Int2ObjectOpenHashMap cache; private final SpriteInformation spriteInformation; - public RecolorableBakedQuad(int[] unpackedData, int tint, Direction orientation, - SpriteInformation texture, boolean applyDiffuseLighting, boolean hasAmbientOcclusion) { - super(unpackedData, tint, orientation, texture.sprite(), applyDiffuseLighting, hasAmbientOcclusion); - this.spriteInformation = texture; + /** + * Create a new recolorable quad based off of a baked quad prototype. + * @param prototype the prototype. + * @param spriteInformation the sprite information of this baked quad. + */ + public RecolorableBakedQuad(BakedQuad prototype, SpriteInformation spriteInformation) { + this(prototype, prototype.getTintIndex(), spriteInformation, new Int2ObjectOpenHashMap<>()); } - public BakedQuad withColor(ColorData data) { - if (!spriteInformation.colorable()) return this; - int argb = data.colorsARGB()[spriteInformation.colorID()]; - return QuadTransformers.applyingColor(argb).process(this); + protected RecolorableBakedQuad(BakedQuad prototype, int tintIndex, + SpriteInformation spriteInformation, Int2ObjectOpenHashMap cache) { + super(prototype.getVertices(), tintIndex, prototype.getDirection(), spriteInformation.sprite(), + prototype.isShade(), prototype.hasAmbientOcclusion()); + this.spriteInformation = spriteInformation; + this.cache = cache; } - @Accessors(chain = true) - public static class Builder implements VertexConsumer { - - private final int[] unpackedData; - @Setter - private int quadTint = -1; - @Setter - private Direction quadOrientation; - @Setter - private SpriteInformation texture; - @Setter - private boolean shade = true; - @Setter - private boolean hasAmbientOcclusion = true; - - private int vertices = 0; - private int elements = 0; - private boolean full = false; - @Setter - private boolean contractUVs = false; - - public Builder() { - unpackedData = new int[STRIDE * 4]; - } - - @Override - public VertexConsumer vertex(double x, double y, double z) { - int offset = vertices * STRIDE + POSITION; - unpackedData[offset] = Float.floatToRawIntBits((float) x); - unpackedData[offset + 1] = Float.floatToRawIntBits((float) y); - unpackedData[offset + 2] = Float.floatToRawIntBits((float) z); - addElement(); - return this; - } - - @Override - public VertexConsumer color(int red, int green, int blue, int alpha) { - int offset = vertices * STRIDE + COLOR; - unpackedData[offset] = ((alpha & 0xFF) << 24) | - ((blue & 0xFF) << 16) | - ((green & 0xFF) << 8) | - (red & 0xFF); - addElement(); - return this; - } - - @Override - public VertexConsumer uv(float u, float v) { - int offset = vertices * STRIDE + UV0; - unpackedData[offset] = Float.floatToRawIntBits(u); - unpackedData[offset + 1] = Float.floatToRawIntBits(v); - addElement(); - return this; - } - - @Override - public VertexConsumer overlayCoords(int u, int v) { - if (UV1 >= 0) { - int offset = vertices * STRIDE + UV1; - unpackedData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16); - addElement(); - } - return this; - } - - @Override - public VertexConsumer uv2(int u, int v) { - int offset = vertices * STRIDE + UV2; - unpackedData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16); - addElement(); - return this; - } - - @Override - public VertexConsumer normal(float x, float y, float z) { - int offset = vertices * STRIDE + NORMAL; - unpackedData[offset] = ((int) (x * 127.0f) & 0xFF) | - (((int) (y * 127.0f) & 0xFF) << 8) | - (((int) (z * 127.0f) & 0xFF) << 16); - addElement(); - return this; - } - - @Override - public void endVertex() {} - - @Override - public void defaultColor(int defaultR, int defaultG, int defaultB, int defaultA) {} - - @Override - public void unsetDefaultColor() {} - - public void put(int element, int... data) { - for (int i = 0; i < 4; i++) { - if (i < data.length) { - unpackedData[vertices * STRIDE + element] = data[i]; - } else { - unpackedData[vertices * STRIDE + element] = 0; - } - } - addElement(); - } - - private void addElement() { - elements++; - if (elements == DefaultVertexFormat.BLOCK.getElements().size()) { - vertices++; - elements = 0; - } - if (vertices == 4) { - full = true; - } - } - - public RecolorableBakedQuad build() { - if (!full) { - throw new IllegalStateException("not enough data"); - } - if (texture == null) { - throw new IllegalStateException("texture not set"); - } - if (contractUVs) { - float tX = texture.sprite().contents().width() / (texture.sprite().getU1() - texture.sprite().getU0()); - float tY = texture.sprite().contents().height() / (texture.sprite().getV1() - texture.sprite().getV0()); - float tS = Math.max(tX, tY); - float ep = 1f / (tS * 0x100); - float[] uvc = new float[4]; - for (int v = 0; v < 4; v++) { - for (int i = 0; i < 4; i++) { - uvc[i] += Float.intBitsToFloat(unpackedData[v * STRIDE + i] / 4); - } - } - for (int v = 0; v < 4; v++) { - for (int i = 0; i < 4; i++) { - float uo = Float.intBitsToFloat(unpackedData[v * STRIDE + i]); - float eps = 1f / 0x100; - float un = uo * (1 - eps) + uvc[i] * eps; - float ud = uo - un; - float aud = ud; - if (aud < 0) aud = -aud; - if (aud < ep) // not moving a fraction of a pixel - { - float udc = uo - uvc[i]; - if (udc < 0) udc = -udc; - if (udc < 2 * ep) // center is closer than 2 fractions of a pixel, don't move too close - { - un = (uo + uvc[i]) / 2; - } else // move at least by a fraction - { - un = uo + (ud < 0 ? ep : -ep); - } - } - unpackedData[v * STRIDE + i] = Float.floatToRawIntBits(un); - } - } - } - return new RecolorableBakedQuad(unpackedData, quadTint, quadOrientation, texture, shade, - hasAmbientOcclusion); - } - } - - private static int findOffset(VertexFormatElement element) { - // Divide by 4 because we want the int offset - var index = DefaultVertexFormat.BLOCK.getElements().indexOf(element); - return index < 0 ? -1 : DefaultVertexFormat.BLOCK.getOffset(index) / 4; + /** + * Get a recolorable quad based off of this quad but aligned with the given color data. + * @param data the color data. + * @return a quad colored based on the color data. + */ + public RecolorableBakedQuad withColor(ColorData data) { + if (!spriteInformation.colorable()) return this; + int argb = data.colorsARGB()[spriteInformation.colorID()]; + return cache.computeIfAbsent(argb, (c) -> new RecolorableBakedQuad(this, c, this.spriteInformation, this.cache)); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java index 516f6f3777..b5adea09c0 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.client.renderer.pipe.quad; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import net.minecraft.client.renderer.block.model.BlockFaceUV; import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; @@ -12,16 +13,31 @@ @OnlyIn(Dist.CLIENT) public interface UVMapper { + Int2ObjectArrayMap STANDARD = new Int2ObjectArrayMap<>(4); + Int2ObjectArrayMap FLIPPED = new Int2ObjectArrayMap<>(4); + static UVMapper standard(int rot) { - return (normal, box) -> { + return FLIPPED.computeIfAbsent(rot, (r) -> (normal, box) -> { + Vector3f small = box.getLeft(); + Vector3f large = box.getRight(); + return switch (normal.getAxis()) { + case X -> new BlockFaceUV(new float[] { small.z, 16 - large.y, large.z, 16 - small.y }, r); + case Y -> new BlockFaceUV(new float[] { small.x, 16 - large.z, large.x, 16 - small.z }, r); + case Z -> new BlockFaceUV(new float[] { small.x, 16 - large.y, large.x, 16 - small.y }, r); + }; + }); + } + + static UVMapper flipped(int rot) { + return STANDARD.computeIfAbsent(rot, (r) -> (normal, box) -> { Vector3f small = box.getLeft(); Vector3f large = box.getRight(); return switch (normal.getAxis()) { - case X -> new BlockFaceUV(new float[] { small.y, large.z, large.y, small.z }, rot); - case Y -> new BlockFaceUV(new float[] { small.x, large.z, large.x, small.z }, rot); - case Z -> new BlockFaceUV(new float[] { small.x, large.y, large.x, small.y }, rot); + case X -> new BlockFaceUV(new float[] { 16 - large.z, small.y, 16 - small.z, large.y }, r); + case Y -> new BlockFaceUV(new float[] { 16 - large.x, small.z, 16 - small.x, large.z }, r); + case Z -> new BlockFaceUV(new float[] { 16 - large.x, small.y, 16 - small.x, large.y }, r); }; - }; + }); } BlockFaceUV map(Direction normal, Pair box); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java index 24bf91eeac..894c2a277b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ColorData.java @@ -3,5 +3,16 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import java.util.Arrays; + @OnlyIn(Dist.CLIENT) -public record ColorData(int... colorsARGB) {} +public record ColorData(int... colorsARGB) { + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (ColorData) obj; + return Arrays.equals(this.colorsARGB, that.colorsARGB); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java index 403e49ea2f..767d44cbfc 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/MaterialModelOverride.java @@ -16,7 +16,7 @@ public interface MaterialModelOverride> { T getModel(Material material, int i); record StandardOverride>(@NotNull T[] models, - @NotNull Predicate predicate) + @NotNull Predicate<@Nullable Material> predicate) implements MaterialModelOverride { @Override @@ -28,7 +28,7 @@ record StandardOverride>(@NotNull T[] models, record PerMaterialOverride>(@NotNull Table models, @NotNull BiFunction createFunction, - @NotNull Predicate predicate) + @NotNull Predicate<@Nullable Material> predicate) implements MaterialModelOverride { @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java index 353531c6a3..251d0bef47 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java @@ -271,17 +271,18 @@ public KeepFluidEQTraverseData(IGraphNet net, FluidTestObject testObject, Simula } @Override - protected void compute(@NotNull WorldPipeNetNode destination) { - this.destCount = 0; - this.maxMinFlow = 0; - for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { - if (destination.getEquivalencyData().equals(sourcePos) && + public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReachingNode, + int expectedDestinations) { + long availableFlow = flowReachingNode; + long flowPerDestination = flowReachingNode / expectedDestinations; + if (flowPerDestination == 0) return 0; + for (var capability : node.getBlockEntity().getTargetsWithCapabilities(node).entrySet()) { + if (node.getEquivalencyData().equals(sourcePos) && capability.getKey() == inputFacing) continue; // anti insert-to-our-source logic - IFluidHandler containerCap = capability.getValue() - .getCapability(ForgeCapabilities.FLUID_HANDLER, - capability.getKey().getOpposite()) + var containerCap = capability.getValue() + .getCapability(ForgeCapabilities.FLUID_HANDLER, capability.getKey().getOpposite()) .resolve().orElse(null); if (containerCap != null) { IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); @@ -289,15 +290,12 @@ protected void compute(@NotNull WorldPipeNetNode destination) { assert getFilterHandler().isFilterPresent(); int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); if (contained >= kept) continue; - if (destCount == 0) maxMinFlow = Integer.MAX_VALUE; - destCount += 1; - maxMinFlow = Math.min(maxMinFlow, - IFluidTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() - .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - kept - contained, - container, false)); + availableFlow -= IFluidTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(kept - contained, flowPerDestination), container, !simulating()); } } + return flowReachingNode - availableFlow; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java index 6bebe0829b..6c31823e70 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java @@ -334,11 +334,13 @@ public KeepItemEQTraverseData(IGraphNet net, ItemTestObject testObject, Simulato } @Override - protected void compute(@NotNull WorldPipeNetNode destination) { - this.destCount = 0; - this.maxMinFlow = 0; - for (var capability : destination.getBlockEntity().getTargetsWithCapabilities(destination).entrySet()) { - if (destination.getEquivalencyData().equals(sourcePos) && + public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReachingNode, + int expectedDestinations) { + long availableFlow = flowReachingNode; + long flowPerDestination = flowReachingNode / expectedDestinations; + if (flowPerDestination == 0) return 0; + for (var capability : node.getBlockEntity().getTargetsWithCapabilities(node).entrySet()) { + if (node.getEquivalencyData().equals(sourcePos) && capability.getKey() == inputFacing) continue; // anti insert-to-our-source logic @@ -352,15 +354,12 @@ protected void compute(@NotNull WorldPipeNetNode destination) { assert getFilterHandler().isFilterPresent(); int kept = getFilterHandler().getFilter().getTransferLimit(getTestObject().recombine()); if (contained >= kept) continue; - if (destCount == 0) maxMinFlow = Integer.MAX_VALUE; - destCount += 1; - int test = kept - contained; - maxMinFlow = Math.min(maxMinFlow, test - - IItemTransferController.CONTROL.get(destination.getBlockEntity().getCoverHolder() - .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), test, - container, true)); + availableFlow = IItemTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(kept - contained, flowPerDestination), container, simulating()); } } + return flowReachingNode - availableFlow; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 048bacbadf..19edc8f016 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -144,8 +144,10 @@ public class GTBlocks { .defaultLoot() .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) .addLayer(() -> RenderType::cutoutMipped) + .color(() -> () -> (state, level, pos, color) -> color) .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) + .color(() -> () -> (stack, color) -> color) .build() .register(); public static final BlockEntry OPTICAL_PIPE = REGISTRATE @@ -155,9 +157,11 @@ public class GTBlocks { .blockstate(NonNullBiConsumer.noop()) .defaultLoot() .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) + .color(() -> () -> (state, level, pos, color) -> color) .addLayer(() -> RenderType::cutoutMipped) .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) + .color(() -> () -> (stack, color) -> color) .build() .register(); @@ -327,8 +331,10 @@ private static void registerCableBlock(Material material, CableStructure structu .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) + .color(() -> () -> (state, level, pos, color) -> color) .item(MaterialPipeBlockItem::new) .model(NonNullBiConsumer.noop()) + .color(() -> () -> (stack, color) -> color) .onRegister(compassNodeExist(GTCompassSections.MATERIALS, "wire_and_cable")) .build() .register(); @@ -374,8 +380,10 @@ private static void registerMaterialPipeBlock(Material material, MaterialPipeStr .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) + .color(() -> () -> (state, level, pos, color) -> color) .item(MaterialPipeBlockItem::new) .model(NonNullBiConsumer.noop()) + .color(() -> () -> (stack, color) -> color) .build() .register(); MATERIAL_PIPE_BLOCKS_BUILDER.put(pipeType.prefix(), material, entry); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java index b331b8b4d3..c5a3d9338f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java @@ -10,9 +10,12 @@ import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraftforge.common.capabilities.ForgeCapabilities; +import net.minecraftforge.fluids.capability.IFluidHandler; import org.jetbrains.annotations.NotNull; public class FluidEQTraverseData extends FluidTraverseData @@ -63,4 +66,26 @@ public boolean shouldSkipPath(@NotNull FlowWorldPipeNetPath path) { public long getMaxFlowToLeastDestination(@NotNull WorldPipeNetNode destination) { return maxMinFlow; } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReachingNode, int expectedDestinations) { + long availableFlow = flowReachingNode; + long flowPerDestination = flowReachingNode / expectedDestinations; + if (flowPerDestination == 0) return 0; + for (var capability : node.getBlockEntity().getTargetsWithCapabilities(node).entrySet()) { + if (node.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + var containerCap = capability.getValue() + .getCapability(ForgeCapabilities.FLUID_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); + availableFlow -= IFluidTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(Integer.MAX_VALUE, flowPerDestination), container, !simulating()); + } + } + return flowReachingNode - availableFlow; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java index c3a68e3c03..44696bc048 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java @@ -67,4 +67,26 @@ public boolean shouldSkipPath(@NotNull FlowWorldPipeNetPath path) { public long getMaxFlowToLeastDestination(@NotNull WorldPipeNetNode destination) { return maxMinFlow; } + + @Override + public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReachingNode, int expectedDestinations) { + long availableFlow = flowReachingNode; + long flowPerDestination = flowReachingNode / expectedDestinations; + if (flowPerDestination == 0) return 0; + for (var capability : node.getBlockEntity().getTargetsWithCapabilities(node).entrySet()) { + if (node.getEquivalencyData().equals(sourcePos) && + capability.getKey() == inputFacing) + continue; // anti insert-to-our-source logic + + IItemHandler containerCap = capability.getValue() + .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + if (containerCap != null) { + IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); + availableFlow = IItemTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() + .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), + (int) Math.min(Integer.MAX_VALUE, flowPerDestination), container, simulating()); + } + } + return flowReachingNode - availableFlow; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java index e89914fa21..129123aff3 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/GTUtil.java @@ -414,10 +414,10 @@ public static long binarySearch(long minValue, long maxValue, LongPredicate test if (test.test(middle) ^ !ascending) { maxValue = middle; } else { - minValue = maxValue; + minValue = middle; } } - return ascending ? maxValue : minValue; + return test.test(ascending ? minValue : maxValue) ^ ascending ? maxValue : minValue; } public static int convertRGBtoARGB(int colorValue) { diff --git a/src/main/java/com/gregtechceu/gtceu/utils/reference/RegeneratingSoftReference.java b/src/main/java/com/gregtechceu/gtceu/utils/reference/RegeneratingSoftReference.java new file mode 100644 index 0000000000..d23ab8b333 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/utils/reference/RegeneratingSoftReference.java @@ -0,0 +1,44 @@ +package com.gregtechceu.gtceu.utils.reference; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; +import java.util.function.Supplier; + +public class RegeneratingSoftReference implements Supplier { + + private final @Nullable ReferenceQueue q; + private final @NotNull Supplier regenerator; + private @NotNull SoftReference reference; + + public RegeneratingSoftReference(@NotNull T initialReference, @NotNull Supplier regenerator, + @Nullable ReferenceQueue q) { + this.q = q; + this.reference = new SoftReference<>(initialReference, q); + this.regenerator = regenerator; + } + + public RegeneratingSoftReference(@NotNull Supplier regenerator, @Nullable ReferenceQueue q) { + this(regenerator.get(), regenerator, q); + } + + public RegeneratingSoftReference(@NotNull T initialReference, @NotNull Supplier regenerator) { + this(initialReference, regenerator, null); + } + + public RegeneratingSoftReference(@NotNull Supplier regenerator) { + this(regenerator.get(), regenerator); + } + + @Override + public T get() { + T fetch = reference.get(); + if (fetch == null) { + fetch = regenerator.get(); + reference = new SoftReference<>(fetch, q); + } + return fetch; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java b/src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java new file mode 100644 index 0000000000..17524e2fba --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java @@ -0,0 +1,135 @@ +package com.gregtechceu.gtceu.utils.reference; + +import org.jetbrains.annotations.NotNull; + +import java.util.AbstractSet; +import java.util.Collection; +import java.util.Iterator; +import java.util.Objects; +import java.util.Set; +import java.util.Spliterator; +import java.util.WeakHashMap; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * Replica of {@link java.util.Collections.SetFromMap} for {@link WeakHashMap} to allow for greater type specificity + * than the {@link java.util.Set} interface. + */ +public class WeakHashSet extends AbstractSet { + + private final WeakHashMap m = new WeakHashMap<>(); + + private final transient Set s = m.keySet(); + + @Override + public void clear() { + m.clear(); + } + + @Override + public int size() { + return m.size(); + } + + @Override + public boolean isEmpty() { + return m.isEmpty(); + } + + // TODO access WeakHashMap#getEntry somehow + // public E get(Object o) { + // } + + @SuppressWarnings("SuspiciousMethodCalls") + @Override + public boolean contains(Object o) { + return m.containsKey(o); + } + + @Override + public boolean remove(Object o) { + return m.remove(o) != null; + } + + @Override + public boolean add(E e) { + return m.put(e, null) == null; + } + + @Override + public Iterator iterator() { + return s.iterator(); + } + + @Override + public Object[] toArray() { + return s.toArray(); + } + + @Override + public T[] toArray(T @NotNull [] a) { + return s.toArray(a); + } + + @Override + public String toString() { + return s.toString(); + } + + @Override + public int hashCode() { + return s.hashCode(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + WeakHashSet that = (WeakHashSet) o; + return Objects.equals(s, that.s); + } + + @Override + public boolean containsAll(@NotNull Collection c) { + return s.containsAll(c); + } + + @Override + public boolean removeAll(Collection c) { + return s.removeAll(c); + } + + @Override + public boolean retainAll(@NotNull Collection c) { + return s.retainAll(c); + } + // addAll is the only inherited implementation + + @Override + public void forEach(Consumer action) { + s.forEach(action); + } + + @Override + public boolean removeIf(Predicate filter) { + return s.removeIf(filter); + } + + @Override + public Spliterator spliterator() { + return s.spliterator(); + } + + @Override + public Stream stream() { + return s.stream(); + } + + @Override + public Stream parallelStream() { + return s.parallelStream(); + } +} From cf069eded7500b06e4424c6a45972925316c8d8e Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 10:24:58 +0300 Subject: [PATCH 26/70] start on fixing computation stuff with new things --- .../capability/IOpticalComputationHatch.java | 7 - .../IOpticalComputationProvider.java | 70 ------ .../IOpticalComputationReceiver.java | 11 - .../capability/IOpticalDataAccessHatch.java | 9 - .../data/query/ComputationQuery.java | 66 ++++++ .../data/query/IComputationQuery.java | 8 + .../api/capability/forge/GTCapability.java | 9 +- .../recipe/CWURecipeCapability.java | 13 +- .../trait/NotifiableComputationContainer.java | 202 ++++++++++-------- .../research/NetworkSwitchMachine.java | 2 - .../research/ResearchStationMachine.java | 2 - .../CreativeComputationProviderMachine.java | 1 - 12 files changed, 200 insertions(+), 200 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationHatch.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationProvider.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationReceiver.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalDataAccessHatch.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IComputationQuery.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationHatch.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationHatch.java deleted file mode 100644 index 1b1235ce8a..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationHatch.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.gregtechceu.gtceu.api.capability; - -public interface IOpticalComputationHatch extends IOpticalComputationProvider { - - /** If this hatch transmits or receives CWU/t. */ - boolean isTransmitter(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationProvider.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationProvider.java deleted file mode 100644 index 999197c823..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationProvider.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.gregtechceu.gtceu.api.capability; - -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * MUST be implemented on any multiblock which uses - * Transmitter Computation Hatches in its structure. - */ -public interface IOpticalComputationProvider { - - /** - * Request some amount of CWU/t (Compute Work Units per tick) from this Machine. - * Implementors should expect these requests to occur each tick that computation is required. - * - * @param cwut Maximum amount of CWU/t requested. - * @return The amount of CWU/t that could be supplied. - */ - default int requestCWUt(int cwut, boolean simulate) { - Collection list = new ArrayList<>(); - list.add(this); - return requestCWUt(cwut, simulate, list); - } - - /** - * Request some amount of CWU/t (Compute Work Units per tick) from this Machine. - * Implementors should expect these requests to occur each tick that computation is required. - * - * @param cwut Maximum amount of CWU/t requested. - * @param seen The Optical Computation Providers already checked - * @return The amount of CWU/t that could be supplied. - */ - int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen); - - /** - * The maximum of CWU/t that this computation provider can provide. - */ - default int getMaxCWUt() { - Collection list = new ArrayList<>(); - list.add(this); - return getMaxCWUt(list); - } - - /** - * The maximum of CWU/t that this computation provider can provide. - * - * @param seen The Optical Computation Providers already checked - */ - int getMaxCWUt(@NotNull Collection seen); - - /** - * Whether this Computation Provider can "Bridge" with other Computation Providers. - * Checked by machines like the Network Switch. - */ - default boolean canBridge() { - Collection list = new ArrayList<>(); - list.add(this); - return canBridge(list); - } - - /** - * Whether this Computation Provider can "Bridge" with other Computation Providers. - * Checked by machines like the Network Switch. - * - * @param seen The Optical Computation Providers already checked - */ - boolean canBridge(@NotNull Collection seen); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationReceiver.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationReceiver.java deleted file mode 100644 index 204a6c311a..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalComputationReceiver.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.gregtechceu.gtceu.api.capability; - -import com.gregtechceu.gtceu.api.machine.trait.NotifiableComputationContainer; - -/** - * Used in conjunction with {@link NotifiableComputationContainer}. - */ -public interface IOpticalComputationReceiver { - - IOpticalComputationProvider getComputationProvider(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalDataAccessHatch.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalDataAccessHatch.java deleted file mode 100644 index 2b40949941..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IOpticalDataAccessHatch.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.gregtechceu.gtceu.api.capability; - -public interface IOpticalDataAccessHatch extends IDataAccessHatch { - - /** - * @return if this hatch transmits data through cables - */ - boolean isTransmitter(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java new file mode 100644 index 0000000000..d5cb83927e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java @@ -0,0 +1,66 @@ +package com.gregtechceu.gtceu.api.capability.data.query; + +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import org.jetbrains.annotations.NotNull; + +import java.util.Set; + +public class ComputationQuery extends DataQueryObject implements IComputationQuery { + + private final Set providers; + + private boolean bridged = false; + private boolean foundUnbridgeable = false; + + public ComputationQuery() { + providers = new ObjectOpenHashSet<>(); + } + + @Override + @NotNull + public DataQueryFormat getFormat() { + return DataQueryFormat.COMPUTATION; + } + + @Override + public void setBridged() { + this.bridged = true; + } + + public boolean foundUnbridgeable() { + return foundUnbridgeable; + } + + @Override + public void registerProvider(IComputationProvider provider) { + if (bridged && !provider.supportsBridging()) { + foundUnbridgeable = true; + return; + } + providers.add(provider); + } + + @NotNull + public Set getProviders() { + return providers; + } + + public long requestCWU(long amount, boolean simulate) { + long remaining = amount; + for (IComputationProvider provider : getProviders()) { + remaining -= provider.supplyCWU(remaining, simulate); + assert remaining >= 0; + if (remaining == 0) return amount; + } + return amount - remaining; + } + + public long maxCWUt() { + long amount = 0; + for (IComputationProvider provider : getProviders()) { + amount += provider.maxCWUt(); + } + return amount; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IComputationQuery.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IComputationQuery.java new file mode 100644 index 0000000000..247d2f3bd4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/IComputationQuery.java @@ -0,0 +1,8 @@ +package com.gregtechceu.gtceu.api.capability.data.query; + +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; + +public interface IComputationQuery extends IBridgeable { + + void registerProvider(IComputationProvider provider); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java b/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java index 8bc5d33459..8405be0876 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/forge/GTCapability.java @@ -1,6 +1,8 @@ package com.gregtechceu.gtceu.api.capability.forge; import com.gregtechceu.gtceu.api.capability.*; +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; +import com.gregtechceu.gtceu.api.capability.data.IComputationUser; import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMaintenanceMachine; import com.gregtechceu.gtceu.api.machine.trait.RecipeLogic; @@ -36,7 +38,9 @@ public class GTCapability { .get(new CapabilityToken<>() {}); public static final Capability CAPABILITY_LASER = CapabilityManager .get(new CapabilityToken<>() {}); - public static final Capability CAPABILITY_COMPUTATION_PROVIDER = CapabilityManager + public static final Capability CAPABILITY_COMPUTATION_PROVIDER = CapabilityManager + .get(new CapabilityToken<>() {}); + public static final Capability CAPABILITY_COMPUTATION_USER = CapabilityManager .get(new CapabilityToken<>() {}); public static final Capability CAPABILITY_DATA_ACCESS = CapabilityManager .get(new CapabilityToken<>() {}); @@ -58,7 +62,8 @@ public static void register(RegisterCapabilitiesEvent event) { event.register(ICleanroomReceiver.class); event.register(IMaintenanceMachine.class); event.register(ILaserRelay.class); - event.register(IOpticalComputationProvider.class); + event.register(IComputationProvider.class); + event.register(IComputationUser.class); event.register(IDataAccess.class); event.register(IMedicalConditionTracker.class); event.register(IHazardParticleContainer.class); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java b/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java index c9bddb0b23..eb072beefd 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java @@ -5,6 +5,7 @@ import com.gregtechceu.gtceu.api.recipe.content.ContentModifier; import com.gregtechceu.gtceu.api.recipe.content.SerializerInteger; +import com.gregtechceu.gtceu.api.recipe.content.SerializerLong; import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.utils.LocalizationUtils; @@ -18,29 +19,29 @@ * @date 2023/2/20 * @implNote ItemRecipeCapability */ -public class CWURecipeCapability extends RecipeCapability { +public class CWURecipeCapability extends RecipeCapability { public final static CWURecipeCapability CAP = new CWURecipeCapability(); protected CWURecipeCapability() { - super("cwu", 0xFFEEEE00, false, 3, SerializerInteger.INSTANCE); + super("cwu", 0xFFEEEE00, false, 3, SerializerLong.INSTANCE); } @Override - public Integer copyInner(Integer content) { + public Long copyInner(Long content) { return content; } @Override - public Integer copyWithModifier(Integer content, ContentModifier modifier) { - return modifier.apply(content).intValue(); + public Long copyWithModifier(Long content, ContentModifier modifier) { + return modifier.apply(content).longValue(); } @Override public void addXEIInfo(WidgetGroup group, int xOffset, GTRecipe recipe, List contents, boolean perTick, boolean isInput, MutableInt yOffset) { if (perTick) { - int cwu = contents.stream().map(Content::getContent).mapToInt(CWURecipeCapability.CAP::of).sum(); + long cwu = contents.stream().map(Content::getContent).mapToLong(CWURecipeCapability.CAP::of).sum(); group.addWidget(new LabelWidget(3 - xOffset, yOffset.addAndGet(10), LocalizationUtils.format("gtceu.recipe.computation_per_tick", cwu))); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java index 029451a8c8..eed704f67d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java @@ -1,9 +1,11 @@ package com.gregtechceu.gtceu.api.machine.trait; +import com.google.common.primitives.Ints; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationHatch; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationReceiver; +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; +import com.gregtechceu.gtceu.api.capability.data.IComputationUser; +import com.gregtechceu.gtceu.api.capability.data.query.ComputationQuery; +import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.capability.recipe.CWURecipeCapability; import com.gregtechceu.gtceu.api.capability.recipe.IO; @@ -16,6 +18,7 @@ import com.gregtechceu.gtceu.api.recipe.GTRecipe; import com.gregtechceu.gtceu.utils.GTUtil; +import com.gregtechceu.gtceu.utils.reference.WeakHashSet; import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; @@ -27,16 +30,20 @@ import java.util.Collections; import java.util.List; -public class NotifiableComputationContainer extends NotifiableRecipeHandlerTrait - implements IOpticalComputationHatch, IOpticalComputationReceiver { +import static com.jozufozu.flywheel.backend.instancing.InstancedRenderRegistry.getController; + +public class NotifiableComputationContainer extends NotifiableRecipeHandlerTrait + implements IComputationProvider, IComputationUser { @Getter protected IO handlerIO; @Getter protected boolean transmitter; + private final WeakHashSet recentQueries = new WeakHashSet<>(); + protected long lastTimeStamp; - private int currentOutputCwu = 0, lastOutputCwu = 0; + private long currentOutputCwu = 0, lastOutputCwu = 0; public NotifiableComputationContainer(MetaMachine machine, IO handlerIO, boolean transmitter) { super(machine); @@ -47,7 +54,7 @@ public NotifiableComputationContainer(MetaMachine machine, IO handlerIO, boolean } @Override - public int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { + public long supplyCWU(long requested, boolean simulate) { var latestTimeStamp = getMachine().getOffsetTimer(); if (lastTimeStamp < latestTimeStamp) { lastOutputCwu = currentOutputCwu; @@ -55,23 +62,22 @@ public int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { - seen.add(this); + public long requestCWU(long requested, boolean simulate) { + var latestTimeStamp = getMachine().getOffsetTimer(); + if (lastTimeStamp < latestTimeStamp) { + lastOutputCwu = currentOutputCwu; + currentOutputCwu = 0; + lastTimeStamp = latestTimeStamp; + } + if (handlerIO == IO.IN) { if (isTransmitter()) { // Ask the Multiblock controller, which *should* be an IOpticalComputationProvider - if (machine instanceof IOpticalComputationProvider provider) { - return provider.getMaxCWUt(seen); + if (machine instanceof IComputationUser user) { + return user.requestCWU(requested, simulate); } else if (machine instanceof IMultiPart part) { if (part.getControllers().isEmpty()) { return 0; } for (IMultiController controller : part.getControllers()) { - if (!controller.isFormed()) { - continue; - } - if (controller instanceof IOpticalComputationProvider provider) { - return provider.getMaxCWUt(seen); + if (controller instanceof IComputationUser provider) { + return provider.requestCWU(requested, simulate); } for (MachineTrait trait : controller.self().getTraits()) { - if (trait instanceof IOpticalComputationProvider provider) { - return provider.getMaxCWUt(seen); + if (trait instanceof IComputationUser provider) { + return provider.requestCWU(requested, simulate); } } } - GTCEu.LOGGER.error( - "NotifiableComputationContainer could not get maximum CWU/t from its machine's controller!"); + GTCEu.LOGGER + .error("NotifiableComputationContainer could request CWU/t from its machine's controller!"); return 0; } else { - GTCEu.LOGGER.error("NotifiableComputationContainer could not get maximum CWU/t from its machine!"); + GTCEu.LOGGER.error("NotifiableComputationContainer could request CWU/t from its machine!"); return 0; } } else { // Ask the attached Transmitter hatch, if it exists - IOpticalComputationProvider provider = getOpticalNetProvider(); + IComputationUser provider = getOpticalNetUser(); if (provider == null) return 0; - return provider.getMaxCWUt(seen); + return provider.requestCWU(requested, simulate); } } else { - return lastOutputCwu; + lastOutputCwu = lastOutputCwu - requested; + return Math.min(lastOutputCwu, requested); } } @Override - public boolean canBridge(@NotNull Collection seen) { - seen.add(this); + public long maxCWUt() { if (handlerIO == IO.IN) { if (isTransmitter()) { // Ask the Multiblock controller, which *should* be an IOpticalComputationProvider - if (machine instanceof IOpticalComputationProvider provider) { - return provider.canBridge(seen); + if (machine instanceof IComputationProvider provider) { + return provider.maxCWUt(); } else if (machine instanceof IMultiPart part) { if (part.getControllers().isEmpty()) { - return false; + return 0; } for (IMultiController controller : part.getControllers()) { if (!controller.isFormed()) { continue; } - if (controller instanceof IOpticalComputationProvider provider) { - return provider.canBridge(seen); + if (controller instanceof IComputationProvider provider) { + return provider.maxCWUt(); } for (MachineTrait trait : controller.self().getTraits()) { - if (trait instanceof IOpticalComputationProvider provider) { - return provider.canBridge(seen); + if (trait instanceof IComputationProvider provider) { + return provider.maxCWUt(); } } } GTCEu.LOGGER.error( - "NotifiableComputationContainer could not test bridge status of its machine's controller!"); - return false; + "NotifiableComputationContainer could not get maximum CWU/t from its machine's controller!"); + return 0; } else { - GTCEu.LOGGER.error("NotifiableComputationContainer could not test bridge status of its machine!"); - return false; + GTCEu.LOGGER.error("NotifiableComputationContainer could not get maximum CWU/t from its machine!"); + return 0; } } else { // Ask the attached Transmitter hatch, if it exists - IOpticalComputationProvider provider = getOpticalNetProvider(); - if (provider == null) return true; // nothing found, so don't report a problem, just pass quietly - return provider.canBridge(seen); + IComputationProvider provider = getOpticalNetProvider(); + if (provider == null) return 0; + return provider.maxCWUt(); + } + } else { + return lastOutputCwu; + } + } + + @Override + public boolean supportsBridging() { + if (isTransmitter()) { + // Ask the Multiblock controller, which *should* be an IOpticalComputationProvider + if (machine instanceof IComputationProvider provider) { + return provider.supportsBridging(); + } else if (machine instanceof IMultiPart part) { + if (part.getControllers().isEmpty()) { + return false; + } + for (IMultiController controller : part.getControllers()) { + if (!controller.isFormed()) { + continue; + } + if (controller instanceof IComputationProvider provider) { + return provider.supportsBridging(); + } + for (MachineTrait trait : controller.self().getTraits()) { + if (trait instanceof IComputationProvider provider) { + return provider.supportsBridging(); + } + } + } + GTCEu.LOGGER.error( + "NotifiableComputationContainer could not test bridge status of its machine's controller!"); + return false; + } else { + GTCEu.LOGGER.error("NotifiableComputationContainer could not test bridge status of its machine!"); + return false; } } else { - return false; + // Ask the attached Transmitter hatch, if it exists + IComputationProvider provider = getOpticalNetProvider(); + if (provider == null) return true; // nothing found, so don't report a problem, just pass quietly + return provider.supportsBridging(); } } @Override - public List handleRecipeInner(IO io, GTRecipe recipe, List left, @Nullable String slotName, + public List handleRecipeInner(IO io, GTRecipe recipe, List left, @Nullable String slotName, boolean simulate) { - IOpticalComputationProvider provider = getOpticalNetProvider(); + IComputationProvider provider = getOpticalNetProvider(); if (provider == null) return left; - int sum = left.stream().reduce(0, Integer::sum); + long sum = left.stream().reduce(0L, Long::sum); if (io == IO.IN) { - int availableCWUt = requestCWUt(Integer.MAX_VALUE, true); + long availableCWUt = requestCWU(Integer.MAX_VALUE, true); if (availableCWUt >= sum) { if (recipe.data.getBoolean("duration_is_total_cwu")) { - int drawn = provider.requestCWUt(availableCWUt, simulate); + int drawn = Ints.saturatedCast(provider.supplyCWU(availableCWUt, simulate)); if (!simulate) { if (machine instanceof IRecipeLogicMachine rlm) { // first, remove the progress the recipe logic adds. @@ -208,11 +255,11 @@ public List handleRecipeInner(IO io, GTRecipe recipe, List lef } sum -= drawn; } else { - sum -= provider.requestCWUt(sum, simulate); + sum -= provider.supplyCWU(sum, simulate); } } } else if (io == IO.OUT) { - int canInput = this.getMaxCWUt() - this.lastOutputCwu; + long canInput = this.maxCWUt() - this.lastOutputCwu; if (!simulate) { this.currentOutputCwu = Math.min(canInput, sum); } @@ -232,50 +279,25 @@ public double getTotalContentAmount() { } @Override - public RecipeCapability getCapability() { + public RecipeCapability getCapability() { return CWURecipeCapability.CAP; } @Nullable - @Override - public IOpticalComputationProvider getComputationProvider() { - if (this.handlerIO.support(IO.OUT)) { - return this; - } - if (machine instanceof IOpticalComputationReceiver receiver) { - return receiver.getComputationProvider(); - } else if (machine instanceof IOpticalComputationProvider provider) { - return provider; - } else if (machine instanceof IRecipeCapabilityHolder recipeCapabilityHolder) { - if (recipeCapabilityHolder.getCapabilitiesProxy().contains(IO.IN, CWURecipeCapability.CAP) && - !recipeCapabilityHolder.getCapabilitiesProxy().get(IO.IN, CWURecipeCapability.CAP).isEmpty()) { - var provider = (IOpticalComputationProvider) recipeCapabilityHolder.getCapabilitiesProxy() - .get(IO.IN, CWURecipeCapability.CAP).get(0); - if (provider != this) { - return provider; - } - } - } + private IComputationProvider getOpticalNetProvider() { for (Direction direction : GTUtil.DIRECTIONS) { BlockEntity blockEntity = machine.getLevel().getBlockEntity(machine.getPos().relative(direction)); - if (blockEntity == null) continue; - - // noinspection DataFlowIssue can be null just fine. - IOpticalComputationProvider provider = blockEntity - .getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, direction.getOpposite()).orElse(null); - // noinspection ConstantValue can be null because above. - if (provider != null && provider != this) { - return provider; - } + return blockEntity.getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, direction.getOpposite()) + .resolve().orElse(null); } return null; } @Nullable - private IOpticalComputationProvider getOpticalNetProvider() { + private IComputationUser getOpticalNetUser() { for (Direction direction : GTUtil.DIRECTIONS) { BlockEntity blockEntity = machine.getLevel().getBlockEntity(machine.getPos().relative(direction)); - return blockEntity.getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, direction.getOpposite()) + return blockEntity.getCapability(GTCapability.CAPABILITY_COMPUTATION_USER, direction.getOpposite()) .resolve().orElse(null); } return null; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java index f402658b8a..58d5782a10 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java @@ -1,8 +1,6 @@ package com.gregtechceu.gtceu.common.machine.multiblock.electric.research; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationHatch; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; import com.gregtechceu.gtceu.api.capability.recipe.IO; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MetaMachine; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java index 31614b70d8..63b5fee4f0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java @@ -1,8 +1,6 @@ package com.gregtechceu.gtceu.common.machine.multiblock.electric.research; import com.gregtechceu.gtceu.api.capability.IObjectHolder; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationReceiver; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.capability.recipe.CWURecipeCapability; import com.gregtechceu.gtceu.api.capability.recipe.IO; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java index ce8a64fd97..4af205bff1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.common.machine.storage; -import com.gregtechceu.gtceu.api.capability.IOpticalComputationProvider; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MetaMachine; From 6fae2fe1c2d5d6e423857d7af7fa3c605eadfcf1 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 12:56:12 +0300 Subject: [PATCH 27/70] I think? it works can't test rn --- .../blockentity/MetaMachineBlockEntity.java | 15 +- .../api/capability/GTCapabilityHelper.java | 12 +- .../api/capability/data/IDataAccess.java | 2 +- .../data/query/ComputationQuery.java | 1 + .../data/query/DataQueryObject.java | 12 +- .../recipe/CWURecipeCapability.java | 3 +- .../gtceu/api/graphnet/IGraphNet.java | 2 +- .../DynamicWeightsShortestPathsAlgorithm.java | 3 +- .../api/graphnet/logic/ChannelCountLogic.java | 3 +- .../graphnet/logic/MultiNetCountLogic.java | 5 +- .../api/graphnet/logic/NetLogicData.java | 5 +- .../api/graphnet/logic/NetLogicEntry.java | 2 +- .../api/graphnet/logic/NetLogicEntryType.java | 4 + .../api/graphnet/logic/NetLogicRegistry.java | 7 +- .../api/graphnet/logic/ThroughputLogic.java | 3 +- .../api/graphnet/logic/WeightFactorLogic.java | 3 +- .../gtceu/api/graphnet/path/INetPath.java | 1 - .../api/graphnet/pipenet/WorldPipeNet.java | 1 - .../logic/EdgeCoverReferenceLogic.java | 3 +- .../pipenet/logic/TemperatureLogic.java | 3 +- .../pipenet/physical/IPipeStructure.java | 3 +- .../physical/PipeStructureRegistry.java | 1 - .../pipenet/physical/block/PipeBlock.java | 1 - .../physical/tile/PipeBlockEntity.java | 60 +++--- .../api/graphnet/worldnet/WorldPosNet.java | 2 + .../multiblock/MultiblockDisplayText.java | 2 +- .../trait/NotifiableComputationContainer.java | 65 +++++- .../client/particle/GTOverheatParticle.java | 1 - .../renderer/pipe/AbstractPipeModel.java | 3 +- .../renderer/pipe/PipeModelRegistry.java | 3 +- .../renderer/pipe/cache/ColorQuadCache.java | 5 +- .../renderer/pipe/quad/PipeQuadHelper.java | 1 + .../client/renderer/pipe/quad/QuadHelper.java | 3 +- .../pipe/quad/RecolorableBakedQuad.java | 19 +- .../client/renderer/pipe/quad/UVMapper.java | 2 +- .../gtceu/client/util/StaticFaceBakery.java | 5 +- .../common/cover/FluidRegulatorCover.java | 2 +- .../gtceu/common/cover/RobotArmCover.java | 2 +- .../gtceu/common/data/GTBlocks.java | 1 - .../gtceu/common/data/GTModels.java | 6 +- .../common/data/GTRecipeCapabilities.java | 2 +- .../common/item/PortableScannerBehavior.java | 8 +- .../electric/research/DataBankMachine.java | 2 - .../electric/research/HPCAMachine.java | 48 +++-- .../research/NetworkSwitchMachine.java | 195 ++---------------- .../research/ResearchStationMachine.java | 57 ++--- .../part/OpticalDataHatchMachine.java | 2 - .../CreativeComputationProviderMachine.java | 24 +-- .../properties/MaterialEnergyProperties.java | 20 +- .../properties/MaterialFluidProperties.java | 8 +- .../properties/MaterialItemProperties.java | 4 +- .../pipelike/net/energy/EnergyFlowLogic.java | 5 +- .../net/energy/EnergyTraverseData.java | 2 +- .../net/energy/SuperconductorLogic.java | 4 +- .../net/energy/VoltageLimitLogic.java | 3 +- .../pipelike/net/energy/VoltageLossLogic.java | 3 +- .../net/fluid/FluidContainmentLogic.java | 3 +- .../net/fluid/FluidEQTraverseData.java | 10 +- .../pipelike/net/item/ItemEQTraverseData.java | 5 +- .../data/recipe/builder/GTRecipeBuilder.java | 4 +- .../gtceu/integration/GTRecipeWidget.java | 4 +- .../gtceu/integration/jade/GTJadePlugin.java | 1 - .../top/provider/CableInfoProvider.java | 2 +- 63 files changed, 308 insertions(+), 385 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java index c915a4a2fb..4ec11b87c7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/blockentity/MetaMachineBlockEntity.java @@ -3,6 +3,8 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.capability.*; +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; +import com.gregtechceu.gtceu.api.capability.data.IComputationUser; import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.item.tool.GTToolType; @@ -258,14 +260,23 @@ public static LazyOptional getCapability(MetaMachine machine, @NotNull Ca LazyOptional.of(() -> list.size() == 1 ? list.get(0) : new LaserContainerList(list))); } } else if (cap == GTCapability.CAPABILITY_COMPUTATION_PROVIDER) { - if (machine instanceof IOpticalComputationProvider computationProvider) { + if (machine instanceof IComputationProvider computationProvider) { return GTCapability.CAPABILITY_COMPUTATION_PROVIDER.orEmpty(cap, LazyOptional.of(() -> computationProvider)); } - var list = getCapabilitiesFromTraits(machine.getTraits(), side, IOpticalComputationProvider.class); + var list = getCapabilitiesFromTraits(machine.getTraits(), side, IComputationProvider.class); if (!list.isEmpty()) { return GTCapability.CAPABILITY_COMPUTATION_PROVIDER.orEmpty(cap, LazyOptional.of(() -> list.get(0))); } + } else if (cap == GTCapability.CAPABILITY_COMPUTATION_USER) { + if (machine instanceof IComputationUser computationProvider) { + return GTCapability.CAPABILITY_COMPUTATION_USER.orEmpty(cap, + LazyOptional.of(() -> computationProvider)); + } + var list = getCapabilitiesFromTraits(machine.getTraits(), side, IComputationUser.class); + if (!list.isEmpty()) { + return GTCapability.CAPABILITY_COMPUTATION_USER.orEmpty(cap, LazyOptional.of(() -> list.get(0))); + } } else if (cap == GTCapability.CAPABILITY_DATA_ACCESS) { if (machine instanceof IDataAccess computationProvider) { return GTCapability.CAPABILITY_DATA_ACCESS.orEmpty(cap, LazyOptional.of(() -> computationProvider)); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java b/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java index 9a62f5659e..a12d65177a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/GTCapabilityHelper.java @@ -1,5 +1,7 @@ package com.gregtechceu.gtceu.api.capability; +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; +import com.gregtechceu.gtceu.api.capability.data.IComputationUser; import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMaintenanceMachine; @@ -96,11 +98,17 @@ public static ILaserRelay getLaser(Level level, BlockPos pos, @Nullable Directio } @Nullable - public static IOpticalComputationProvider getOpticalComputationProvider(Level level, BlockPos pos, - @Nullable Direction side) { + public static IComputationProvider getComputationProvider(Level level, BlockPos pos, + @Nullable Direction side) { return getBlockEntityCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER, level, pos, side); } + @Nullable + public static IComputationUser getComputationUser(Level level, BlockPos pos, + @Nullable Direction side) { + return getBlockEntityCapability(GTCapability.CAPABILITY_COMPUTATION_USER, level, pos, side); + } + @Nullable public static IDataAccess getDataAccess(Level level, BlockPos pos, @Nullable Direction side) { return getBlockEntityCapability(GTCapability.CAPABILITY_DATA_ACCESS, level, pos, side); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java index 57ce3a31e5..95bbe14772 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java @@ -45,7 +45,7 @@ static boolean accessData(@NotNull Iterable accesses, for (IDataAccess access : accesses) { query.setShouldTriggerWalker(false); cancelled = access.accessData(query); - if (!walk) walk = query.shouldTriggerWalker(); + if (!walk) walk = query.isShouldTriggerWalker(); if (cancelled) break; } query.setShouldTriggerWalker(walk); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java index d5cb83927e..7d52722734 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/ComputationQuery.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.capability.data.query; import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; + import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java index b11063de9e..2e7c9584b6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java @@ -1,5 +1,7 @@ package com.gregtechceu.gtceu.api.capability.data.query; +import lombok.Getter; +import lombok.Setter; import org.jetbrains.annotations.NotNull; public abstract class DataQueryObject { @@ -8,20 +10,14 @@ public abstract class DataQueryObject { private final int id; + @Getter + @Setter private boolean shouldTriggerWalker = false; public DataQueryObject() { this.id = ID++; } - public void setShouldTriggerWalker(boolean shouldTriggerWalker) { - this.shouldTriggerWalker = shouldTriggerWalker; - } - - public boolean shouldTriggerWalker() { - return shouldTriggerWalker; - } - @NotNull public abstract DataQueryFormat getFormat(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java b/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java index eb072beefd..cbb81d1d30 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/recipe/CWURecipeCapability.java @@ -3,9 +3,8 @@ import com.gregtechceu.gtceu.api.recipe.GTRecipe; import com.gregtechceu.gtceu.api.recipe.content.Content; import com.gregtechceu.gtceu.api.recipe.content.ContentModifier; -import com.gregtechceu.gtceu.api.recipe.content.SerializerInteger; - import com.gregtechceu.gtceu.api.recipe.content.SerializerLong; + import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.utils.LocalizationUtils; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java index 41a0aac219..af099245d0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java @@ -125,7 +125,7 @@ default AbstractGroupData getBlankGroupData() { */ @NotNull default NetLogicData getDefaultNodeData() { - return new NetLogicData().setLogicEntry(WeightFactorLogic.TYPE.getWith(1)); + return new NetLogicData().setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(1)); } /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java index e9aa579e9e..961c673e33 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/alg/DynamicWeightsShortestPathsAlgorithm.java @@ -92,7 +92,8 @@ private void calculateNext() { private boolean isUnique(Path path) { for (Path other : visited) { if (path.getOrderedNodes().equals(other.getOrderedNodes()) && - path.getOrderedEdges().equals(other.getOrderedEdges())) return false; + path.getOrderedEdges().equals(other.getOrderedEdges())) + return false; } return true; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java index 03a79b22c2..a27f9c780c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java @@ -2,7 +2,8 @@ public final class ChannelCountLogic extends AbstractIntLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("ChannelCount", () -> new ChannelCountLogic().setValue(1)); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("ChannelCount", + () -> new ChannelCountLogic().setValue(1)); public ChannelCountLogic() { super(TYPE); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java index d474fd6a15..e9d72ac92c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java @@ -2,10 +2,11 @@ public final class MultiNetCountLogic extends AbstractIntLogicData { - public static final MultiNetCountLogic INSTANCE = new MultiNetCountLogic().setValue(1); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("MultiNetCount", + () -> new MultiNetCountLogic().setValue(1)); public MultiNetCountLogic() { - super("MultiNetCount"); + super(TYPE); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index 9009ef558f..5e7e20c2ca 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import com.jozufozu.flywheel.util.WeakHashSet; import com.lowdragmc.lowdraglib.syncdata.IContentChangeAware; import com.lowdragmc.lowdraglib.syncdata.ITagSerializable; @@ -10,17 +9,15 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.StringRepresentable; +import com.jozufozu.flywheel.util.WeakHashSet; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import lombok.Getter; import lombok.Setter; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Set; - /** * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on * logics, diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java index 84a5fa4606..d2019d2047 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java @@ -6,11 +6,11 @@ import com.lowdragmc.lowdraglib.networking.IPacket; -import lombok.Getter; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.common.util.INBTSerializable; +import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java index a1f5290688..f34e0b27bb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java @@ -11,6 +11,10 @@ public record NetLogicEntryType>(String id, Suppli NetLogicRegistry.register(this); } + public T getNew() { + return supplier.get(); + } + @Override public String getSerializedName() { return id; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index 93a2f1b402..18b6407467 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -1,8 +1,9 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -37,7 +38,8 @@ public static void throwNonexistenceError() { private static class EmptyLogicEntry extends NetLogicEntry { - private static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Empty", EmptyLogicEntry::new); + private static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Empty", + EmptyLogicEntry::new); protected EmptyLogicEntry() { super(TYPE); @@ -62,6 +64,5 @@ public void encode(FriendlyByteBuf buf, boolean fullChange) { public void decode(FriendlyByteBuf buf, boolean fullChange) { throw new RuntimeException("Can't deserialize empty logic entry!"); } - } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java index 07cea6dc47..b4d02f0a75 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java @@ -2,7 +2,8 @@ public final class ThroughputLogic extends AbstractLongLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Throughput", () -> new ThroughputLogic().setValue(0)); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Throughput", + () -> new ThroughputLogic().setValue(0)); private ThroughputLogic() { super(TYPE); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java index 8307071b9b..a5abf68d5b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java @@ -2,7 +2,8 @@ public final class WeightFactorLogic extends AbstractDoubleLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("WeightFactor", () -> new WeightFactorLogic().setValue(0.1d)); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("WeightFactor", + () -> new WeightFactorLogic().setValue(0.1d)); private WeightFactorLogic() { super(TYPE); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java index 4971bdd26f..b47c6f0ee6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/path/INetPath.java @@ -4,7 +4,6 @@ import com.gregtechceu.gtceu.api.graphnet.edge.NetEdge; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jgrapht.alg.util.ToleranceDoubleComparator; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index 879f077cc4..1b23d405a6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -11,7 +11,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; -import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldNet; import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldPosNet; import com.gregtechceu.gtceu.utils.GTUtil; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java index 8767151d68..3dc2f6d018 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java @@ -26,7 +26,8 @@ public final class EdgeCoverReferenceLogic extends NetLogicEntry { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EdgeCoverReference", EdgeCoverReferenceLogic::new); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EdgeCoverReference", + EdgeCoverReferenceLogic::new); @Nullable private WeakReference coverSource; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index f97fb4f0f2..585dc56265 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -29,7 +29,8 @@ public final class TemperatureLogic extends NetLogicEntry { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Temperature", TemperatureLogic::new); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Temperature", + TemperatureLogic::new); public static final int DEFAULT_TEMPERATURE = 298; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java index f8cbccc2d0..e37267721f 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/IPipeStructure.java @@ -48,7 +48,8 @@ default VoxelShape getPipeBoxes(@NotNull PipeBlockEntity tileContext) { pipeBoxes = Shapes.or(pipeBoxes, getSideBox(null, thickness)); } for (Direction facing : GTUtil.DIRECTIONS) { - if (tileContext.isConnectedCoverAdjusted(facing)) pipeBoxes = Shapes.or(pipeBoxes, getSideBox(facing, thickness)); + if (tileContext.isConnectedCoverAdjusted(facing)) + pipeBoxes = Shapes.or(pipeBoxes, getSideBox(facing, thickness)); } return pipeBoxes; } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java index 4f7f6b5140..5da094110d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -7,7 +7,6 @@ import org.jetbrains.annotations.NotNull; import java.util.Collections; -import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index b8fb254f84..4844b3aaf3 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -49,7 +49,6 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.storage.loot.LootParams; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 1495008c7c..d71223aff1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -131,7 +131,6 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity @DescSynced @Getter protected final PipeCoverHolder coverHolder = new PipeCoverHolder(this); - @Getter private final Object2ObjectOpenHashMap, IPipeCapabilityObject> capabilities = new Object2ObjectOpenHashMap<>(); private final Object2ObjectOpenCustomHashMap netCapabilities = WorldPipeNet .getSensitiveHashMap(); @@ -244,6 +243,17 @@ public boolean renderClosed(Direction facing) { return (this.renderMask & 1 << facing.ordinal()) > 0; } + public byte getCoverAdjustedConnectionMask() { + byte connectionMask = this.connectionMask; + for (Direction dir : GTUtil.DIRECTIONS) { + CoverBehavior cover = getCoverHolder().getCoverAtSide(dir); + if (cover != null) { + if (cover.forcePipeRenderConnection()) connectionMask |= 1 << dir.ordinal(); + } + } + return connectionMask; + } + public void setBlocked(Direction facing) { this.blockedMask |= (byte) (1 << facing.ordinal()); scheduleRenderUpdate(); @@ -527,30 +537,30 @@ protected void initialize() { } /* - @Override - public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { - buf.writeVarInt(netLogicDatas.size()); - for (var entry : netLogicDatas.int2ObjectEntrySet()) { - buf.writeVarInt(entry.getIntKey()); - entry.getValue().encode(buf); - } - } - - @Override - public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { - if (level.isClientSide) { - netLogicDatas.clear(); - int count = buf.readVarInt(); - for (int i = 0; i < count; i++) { - int networkID = buf.readVarInt(); - NetLogicData data = new NetLogicData(); - data.decode(buf); - netLogicDatas.put(networkID, data); - } - } - scheduleRenderUpdate(); - } - */ + * @Override + * public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { + * buf.writeVarInt(netLogicDatas.size()); + * for (var entry : netLogicDatas.int2ObjectEntrySet()) { + * buf.writeVarInt(entry.getIntKey()); + * entry.getValue().encode(buf); + * } + * } + * + * @Override + * public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { + * if (level.isClientSide) { + * netLogicDatas.clear(); + * int count = buf.readVarInt(); + * for (int i = 0; i < count; i++) { + * int networkID = buf.readVarInt(); + * NetLogicData data = new NetLogicData(); + * data.decode(buf); + * netLogicDatas.put(networkID, data); + * } + * } + * scheduleRenderUpdate(); + * } + */ @Override public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java index 9c7f34fe57..403c726a62 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldPosNet.java @@ -4,7 +4,9 @@ import com.gregtechceu.gtceu.api.graphnet.NetNode; import com.gregtechceu.gtceu.api.graphnet.alg.AlgorithmBuilder; import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; + import net.minecraft.core.BlockPos; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/MultiblockDisplayText.java b/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/MultiblockDisplayText.java index cd2637cb83..4660a30bc9 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/MultiblockDisplayText.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/MultiblockDisplayText.java @@ -209,7 +209,7 @@ public Builder addEnergyProductionAmpsLine(long maxVoltage, int amperage) { *
* Added if the structure is formed and if the max CWU/t is greater than zero. */ - public Builder addComputationUsageLine(int maxCWUt) { + public Builder addComputationUsageLine(long maxCWUt) { if (!isStructureFormed) return this; if (maxCWUt > 0) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java index eed704f67d..5a7ed17d73 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java @@ -1,15 +1,18 @@ package com.gregtechceu.gtceu.api.machine.trait; -import com.google.common.primitives.Ints; import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; +import com.gregtechceu.gtceu.api.capability.IWorkable; +import com.gregtechceu.gtceu.api.capability.data.IComputationDataAccess; import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; import com.gregtechceu.gtceu.api.capability.data.IComputationUser; -import com.gregtechceu.gtceu.api.capability.data.query.ComputationQuery; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; +import com.gregtechceu.gtceu.api.capability.data.query.IBridgeable; +import com.gregtechceu.gtceu.api.capability.data.query.IComputationQuery; import com.gregtechceu.gtceu.api.capability.forge.GTCapability; import com.gregtechceu.gtceu.api.capability.recipe.CWURecipeCapability; import com.gregtechceu.gtceu.api.capability.recipe.IO; -import com.gregtechceu.gtceu.api.capability.recipe.IRecipeCapabilityHolder; import com.gregtechceu.gtceu.api.capability.recipe.RecipeCapability; import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.feature.IRecipeLogicMachine; @@ -17,23 +20,22 @@ import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiPart; import com.gregtechceu.gtceu.api.recipe.GTRecipe; import com.gregtechceu.gtceu.utils.GTUtil; - import com.gregtechceu.gtceu.utils.reference.WeakHashSet; + import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; +import com.google.common.primitives.Ints; import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collection; +import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static com.jozufozu.flywheel.backend.instancing.InstancedRenderRegistry.getController; - public class NotifiableComputationContainer extends NotifiableRecipeHandlerTrait - implements IComputationProvider, IComputationUser { + implements IComputationProvider, IComputationUser, IComputationDataAccess { @Getter protected IO handlerIO; @@ -53,6 +55,51 @@ public NotifiableComputationContainer(MetaMachine machine, IO handlerIO, boolean this.lastTimeStamp = Long.MIN_VALUE; } + @Override + public boolean accessData(@NotNull DataQueryObject queryObject) { + if (!supportsQuery(queryObject) || !recentQueries.add(queryObject)) return false; + + if (isTransmitter()) { + MetaMachine machine = getMachine(); + if (machine instanceof IWorkable workable && !workable.isActive()) return false; + + List accesses = new ArrayList<>(); + if (machine instanceof IComputationProvider provider && + queryObject instanceof IComputationQuery cq) { + cq.registerProvider(provider); + } + if (machine instanceof IComputationDataAccess dataAccess) { + accesses.add(dataAccess); + } + if (machine instanceof IMultiPart part) { + for (IMultiController controller : part.getControllers()) { + if (controller instanceof IComputationProvider provider && + queryObject instanceof IComputationQuery cq) { + cq.registerProvider(provider); + } + if (controller instanceof IComputationDataAccess dataAccess) { + accesses.add(dataAccess); + } + for (MachineTrait trait : controller.self().getTraits()) { + if (trait instanceof IComputationDataAccess dataAccess) { + accesses.add(dataAccess); + } + } + } + } + if (queryObject instanceof IBridgeable bridgeable && accesses.size() > 1) { + bridgeable.setBridged(); + } + return IDataAccess.accessData(accesses, queryObject); + } else { + Direction front = machine.getFrontFacing(); + IDataAccess access = GTCapabilityHelper.getDataAccess(machine.getLevel(), machine.getPos().relative(front), + front.getOpposite()); + if (access == null) return false; + return access.accessData(queryObject); + } + } + @Override public long supplyCWU(long requested, boolean simulate) { var latestTimeStamp = getMachine().getOffsetTimer(); @@ -229,7 +276,7 @@ public boolean supportsBridging() { @Override public List handleRecipeInner(IO io, GTRecipe recipe, List left, @Nullable String slotName, - boolean simulate) { + boolean simulate) { IComputationProvider provider = getOpticalNetProvider(); if (provider == null) return left; diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java index afa2e5d9b4..79a497dafc 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java @@ -11,7 +11,6 @@ import com.gregtechceu.gtceu.client.util.EffectRenderContext; import com.gregtechceu.gtceu.client.util.RenderBufferHelper; -import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.shimmer.client.shader.RenderUtils; import net.minecraft.client.Minecraft; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index 90c452c01d..cc95730e0b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -10,8 +10,8 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; - import com.gregtechceu.gtceu.utils.reference.WeakHashSet; + import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.RenderType; @@ -69,6 +69,7 @@ public AbstractPipeModel() { pipeCache = new Object2ObjectOpenHashMap<>(); PIPE_CACHES.add(pipeCache); } + public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData modelData, @Nullable RenderType renderType) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java index 8e9c5ac1cf..7669fc670e 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -182,7 +182,8 @@ private static void initPipes() { array[1] = new PipeModel(pipeSmallWood, pipeSideWood, false); array[2] = new PipeModel(pipeNormalWood, pipeSideWood, false); array[3] = new PipeModel(pipeLargeWood, pipeSideWood, false); - registerPipeOverride(new MaterialModelOverride.StandardOverride<>(array, m -> m != null && m.hasProperty(PropertyKey.WOOD))); + registerPipeOverride( + new MaterialModelOverride.StandardOverride<>(array, m -> m != null && m.hasProperty(PropertyKey.WOOD))); array = new PipeModel[PIPE_MODEL_COUNT]; array[0] = new PipeModel(pipeTiny, pipeSide, true); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java index 3f494917e5..3ee4058f31 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java @@ -3,8 +3,6 @@ import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; -import com.gregtechceu.gtceu.utils.reference.RegeneratingSoftReference; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -13,7 +11,6 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.List; -import java.util.Map; @OnlyIn(Dist.CLIENT) public final class ColorQuadCache { @@ -35,7 +32,7 @@ public List getQuads(ColorData data) { existing.add(quad.withColor(data)); } cache.put(data, existing); -// if (cache.size() > 20) cache.removeLast(); + // if (cache.size() > 20) cache.removeLast(); } return existing; } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java index 1ce57e376c..565ba67612 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -79,6 +79,7 @@ private void generateBox(float xS, float xL, float yS, float yL, float zS, float float large = 0.5f + thickness / 2; return new PipeQuadHelper((float) x, (float) y, (float) z, small, large); } + @Contract("_ -> new") public static @NotNull PipeQuadHelper create(float thickness) { return create(thickness, 0, 0, 0); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java index 8952a34a55..f65a626311 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -26,7 +26,8 @@ public final class QuadHelper { private QuadHelper() {} public static @NotNull RecolorableBakedQuad buildQuad(Direction normal, Pair box, - @NotNull UVMapper uv, @NotNull SpriteInformation targetSprite) { + @NotNull UVMapper uv, + @NotNull SpriteInformation targetSprite) { BlockElementFace face = new BlockElementFace(null, -1, targetSprite.sprite().contents().name().toString(), uv.map(normal, box), ForgeFaceData.DEFAULT); return StaticFaceBakery.bakeRecolorableQuad(box.getLeft(), box.getRight(), face, targetSprite, normal, diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java index cb9b1d5d99..44b8ac8580 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java @@ -3,19 +3,12 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.QuadTransformers; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.blaze3d.vertex.VertexFormatElement; -import lombok.Setter; -import lombok.experimental.Accessors; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import static net.minecraftforge.client.model.IQuadTransformer.*; @@ -28,7 +21,8 @@ public class RecolorableBakedQuad extends BakedQuad { /** * Create a new recolorable quad based off of a baked quad prototype. - * @param prototype the prototype. + * + * @param prototype the prototype. * @param spriteInformation the sprite information of this baked quad. */ public RecolorableBakedQuad(BakedQuad prototype, SpriteInformation spriteInformation) { @@ -36,7 +30,8 @@ public RecolorableBakedQuad(BakedQuad prototype, SpriteInformation spriteInforma } protected RecolorableBakedQuad(BakedQuad prototype, int tintIndex, - SpriteInformation spriteInformation, Int2ObjectOpenHashMap cache) { + SpriteInformation spriteInformation, + Int2ObjectOpenHashMap cache) { super(prototype.getVertices(), tintIndex, prototype.getDirection(), spriteInformation.sprite(), prototype.isShade(), prototype.hasAmbientOcclusion()); this.spriteInformation = spriteInformation; @@ -45,12 +40,14 @@ protected RecolorableBakedQuad(BakedQuad prototype, int tintIndex, /** * Get a recolorable quad based off of this quad but aligned with the given color data. + * * @param data the color data. * @return a quad colored based on the color data. */ public RecolorableBakedQuad withColor(ColorData data) { if (!spriteInformation.colorable()) return this; int argb = data.colorsARGB()[spriteInformation.colorID()]; - return cache.computeIfAbsent(argb, (c) -> new RecolorableBakedQuad(this, c, this.spriteInformation, this.cache)); + return cache.computeIfAbsent(argb, + (c) -> new RecolorableBakedQuad(this, c, this.spriteInformation, this.cache)); } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java index b5adea09c0..16e026e537 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/UVMapper.java @@ -1,11 +1,11 @@ package com.gregtechceu.gtceu.client.renderer.pipe.quad; -import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import net.minecraft.client.renderer.block.model.BlockFaceUV; import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import org.apache.commons.lang3.tuple.Pair; import org.joml.Vector3f; diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java index a41554a9d9..cefb19d20d 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java @@ -170,8 +170,9 @@ public static RecolorableBakedQuad bakeRecolorableQuad( ForgeHooksClient.fillNormal(aint, direction); ForgeFaceData data = face.getFaceData(); - RecolorableBakedQuad quad = new RecolorableBakedQuad(aint, face.tintIndex, direction, sprite, shade, - data.ambientOcclusion()); + RecolorableBakedQuad quad = new RecolorableBakedQuad( + new BakedQuad(aint, face.tintIndex, direction, sprite.sprite(), shade, data.ambientOcclusion()), + sprite); if (!ForgeFaceData.DEFAULT.equals(data)) { QuadTransformers.applyingLightmap(data.blockLight(), data.skyLight()).processInPlace(quad); QuadTransformers.applyingColor(data.color()).processInPlace(quad); diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java index 251d0bef47..dd28f84747 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/FluidRegulatorCover.java @@ -292,7 +292,7 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReach if (contained >= kept) continue; availableFlow -= IFluidTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(kept - contained, flowPerDestination), container, !simulating()); + (int) Math.min(kept - contained, flowPerDestination), container, !simulating()); } } return flowReachingNode - availableFlow; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java index 6c31823e70..8324e120b6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/RobotArmCover.java @@ -356,7 +356,7 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReach if (contained >= kept) continue; availableFlow = IItemTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(kept - contained, flowPerDestination), container, simulating()); + (int) Math.min(kept - contained, flowPerDestination), container, simulating()); } } return flowReachingNode - availableFlow; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 19edc8f016..68efb37423 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -36,7 +36,6 @@ import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; -import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; import com.gregtechceu.gtceu.common.pipelike.longdistance.fluid.LDFluidPipeType; import com.gregtechceu.gtceu.common.pipelike.longdistance.item.LDItemPipeType; import com.gregtechceu.gtceu.core.mixins.BlockPropertiesAccessor; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java index 3670f522c3..989b19cfcc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java @@ -2,8 +2,8 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTCEuAPI; -import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.block.ActiveBlock; +import com.gregtechceu.gtceu.api.block.BlockProperties; import com.gregtechceu.gtceu.api.block.ICoilType; import com.gregtechceu.gtceu.api.block.IFilterType; import com.gregtechceu.gtceu.api.block.IFusionCasingType; @@ -14,6 +14,8 @@ import com.gregtechceu.gtceu.api.fluids.store.FluidStorage; import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKey; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; +import com.gregtechceu.gtceu.api.machine.multiblock.IBatteryData; +import com.gregtechceu.gtceu.common.block.*; import com.gregtechceu.gtceu.common.block.LampBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableBlock; import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; @@ -26,8 +28,6 @@ import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; import com.gregtechceu.gtceu.common.pipelike.handlers.properties.MaterialEnergyProperties; -import com.gregtechceu.gtceu.api.machine.multiblock.IBatteryData; -import com.gregtechceu.gtceu.common.block.*; import com.gregtechceu.gtceu.core.MixinHelpers; import com.gregtechceu.gtceu.data.pack.GTDynamicResourcePack; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipeCapabilities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipeCapabilities.java index 4e24361a11..8258841716 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipeCapabilities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTRecipeCapabilities.java @@ -22,7 +22,7 @@ public class GTRecipeCapabilities { public final static RecipeCapability FLUID = FluidRecipeCapability.CAP; public final static RecipeCapability BLOCK_STATE = BlockStateRecipeCapability.CAP; public final static RecipeCapability EU = EURecipeCapability.CAP; - public final static RecipeCapability CWU = CWURecipeCapability.CAP; + public final static RecipeCapability CWU = CWURecipeCapability.CAP; public final static RecipeCapability SU = StressRecipeCapability.CAP; public static void init() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index 6abd197153..634089829f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -31,6 +31,7 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; + import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -376,7 +377,7 @@ else if (machine instanceof IDataInfoProvider) int cumulativeCount = 0; long cumulativeVoltage = 0; long cumulativeAmperage = 0; - for (var memory : data.getLogicEntryDefaultable(EnergyFlowLogic.INSTANCE).getMemory().entrySet()) { + for (var memory : data.getLogicEntryDefaultable(EnergyFlowLogic.TYPE).getMemory().entrySet()) { cumulativeCount++; int count = 0; double voltage = 0; @@ -386,7 +387,8 @@ else if (machine instanceof IDataInfoProvider) long prev = amperage; amperage += flow.amperage(); // weighted average - voltage = voltage * prev / amperage + (double) (flow.voltage() * flow.amperage()) / amperage; + voltage = voltage * prev / amperage + + (double) (flow.voltage() * flow.amperage()) / amperage; } if (count != 0) { cumulativeVoltage += voltage / count; @@ -406,7 +408,7 @@ else if (machine instanceof IDataInfoProvider) .withStyle(ChatFormatting.RED))); long tick = Platform.getMinecraftServer().getTickCount(); - int temp = data.getLogicEntryDefaultable(TemperatureLogic.INSTANCE).getTemperature(tick); + int temp = data.getLogicEntryDefaultable(TemperatureLogic.TYPE).getTemperature(tick); list.add(Component.translatable("behavior.portable_scanner.temperature", Component.translatable(FormattingUtil.formatNumbers(temp)) .withStyle(ChatFormatting.RED))); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/DataBankMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/DataBankMachine.java index 60bf7592ba..8d6ffb8339 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/DataBankMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/DataBankMachine.java @@ -18,8 +18,6 @@ import com.gregtechceu.gtceu.api.misc.EnergyContainerList; import com.gregtechceu.gtceu.config.ConfigHolder; -import com.lowdragmc.lowdraglib.gui.widget.*; - import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.network.chat.Component; import net.minecraft.server.TickTask; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/HPCAMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/HPCAMachine.java index 68ceec0eaf..618703f5be 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/HPCAMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/HPCAMachine.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.capability.*; +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; import com.gregtechceu.gtceu.api.capability.recipe.EURecipeCapability; import com.gregtechceu.gtceu.api.capability.recipe.FluidRecipeCapability; import com.gregtechceu.gtceu.api.capability.recipe.IO; @@ -55,7 +56,6 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import lombok.Getter; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; @@ -66,7 +66,7 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class HPCAMachine extends WorkableElectricMultiblockMachine - implements IOpticalComputationProvider, IControllable { + implements IComputationProvider, IControllable { private static final double IDLE_TEMPERATURE = 200; private static final double DAMAGE_TEMPERATURE = 1000; @@ -78,8 +78,6 @@ public class HPCAMachine extends WorkableElectricMultiblockMachine @DescSynced private final HPCAGridHandler hpcaHandler; - private boolean hasNotEnoughEnergy; - @Persisted private double temperature = IDLE_TEMPERATURE; // start at idle temperature @@ -166,20 +164,17 @@ public void onStructureInvalid() { } @Override - public int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { - seen.add(this); - return isActive() && isWorkingEnabled() && !hasNotEnoughEnergy ? hpcaHandler.allocateCWUt(cwut, simulate) : 0; + public long supplyCWU(long requested, boolean simulate) { + return isActive() && isWorkingEnabled() ? hpcaHandler.allocateCWUt(requested, simulate) : 0; } @Override - public int getMaxCWUt(@NotNull Collection seen) { - seen.add(this); - return isActive() && isWorkingEnabled() ? hpcaHandler.getMaxCWUt() : 0; + public long maxCWUt() { + return isActive() && isWorkingEnabled() ? hpcaHandler.maxCWUt() : 0; } @Override - public boolean canBridge(@NotNull Collection seen) { - seen.add(this); + public boolean supportsBridging() { // don't show a problem if the structure is not yet formed return !isFormed() || hpcaHandler.hasHPCABridge(); } @@ -215,22 +210,25 @@ private void consumeEnergy() { energyToConsume += maintenance.getNumMaintenanceProblems() * energyToConsume / 10; } - if (this.hasNotEnoughEnergy && energyContainer.getInputPerSec() > 19L * energyToConsume) { - this.hasNotEnoughEnergy = false; + if (recipeLogic.getStatus() == RecipeLogic.Status.SUSPEND) { + return; + } + + if (recipeLogic.getStatus() == RecipeLogic.Status.WAITING && + energyContainer.getInputPerSec() > 19L * energyToConsume) { + recipeLogic.setStatus(RecipeLogic.Status.WORKING); } if (this.energyContainer.getEnergyStored() >= energyToConsume) { - if (!hasNotEnoughEnergy) { + if (recipeLogic.getStatus() != RecipeLogic.Status.WAITING) { long consumed = this.energyContainer.removeEnergy(energyToConsume); if (consumed == energyToConsume) { getRecipeLogic().setStatus(RecipeLogic.Status.WORKING); } else { - this.hasNotEnoughEnergy = true; getRecipeLogic().setStatus(RecipeLogic.Status.WAITING); } } } else { - this.hasNotEnoughEnergy = true; getRecipeLogic().setStatus(RecipeLogic.Status.WAITING); } } @@ -287,7 +285,7 @@ public void addDisplayText(List textList) { // Provided Computation Component cwutInfo = Component.literal( - hpcaHandler.cachedCWUt + " / " + hpcaHandler.getMaxCWUt() + " CWU/t") + hpcaHandler.cachedCWUt + " / " + hpcaHandler.maxCWUt() + " CWU/t") .withStyle(ChatFormatting.AQUA); tl.add(Component.translatable( "gtceu.multiblock.hpca.computation", @@ -446,7 +444,7 @@ public void tick() { */ public double calculateTemperatureChange(IFluidTransfer coolantTank, boolean forceCoolWithActive) { // calculate temperature increase - int maxCWUt = Math.max(1, getMaxCWUt()); // avoids dividing by 0 and the behavior is no different + int maxCWUt = Math.max(1, maxCWUt()); // avoids dividing by 0 and the behavior is no different int maxCoolingDemand = getMaxCoolingDemand(); // temperature increase is proportional to the amount of actively used computation @@ -541,10 +539,10 @@ public void attemptDamageHPCA() { } /** Allocate computation on a given request. Allocates for one tick. */ - public int allocateCWUt(int cwut, boolean simulate) { - int maxCWUt = getMaxCWUt(); + public long allocateCWUt(long requested, boolean simulate) { + int maxCWUt = maxCWUt(); int availableCWUt = maxCWUt - this.allocatedCWUt; - int toAllocate = Math.min(cwut, availableCWUt); + long toAllocate = Math.min(requested, availableCWUt); if (!simulate) { this.allocatedCWUt += toAllocate; } @@ -552,7 +550,7 @@ public int allocateCWUt(int cwut, boolean simulate) { } /** The maximum amount of CWUs (Compute Work Units) created per tick. */ - public int getMaxCWUt() { + public int maxCWUt() { int maxCWUt = 0; for (var computationProvider : computationProviders) { maxCWUt += computationProvider.getCWUPerTick(); @@ -562,7 +560,7 @@ public int getMaxCWUt() { /** The current EU/t this HPCA should use, considering passive drain, current computation, etc.. */ public long getCurrentEUt() { - long maximumCWUt = Math.max(1, getMaxCWUt()); // behavior is no different setting this to 1 if it is 0 + long maximumCWUt = Math.max(1, maxCWUt()); // behavior is no different setting this to 1 if it is 0 long maximumEUt = getMaxEUt(); long upkeepEUt = getUpkeepEUt(); @@ -635,7 +633,7 @@ public int getMaxCoolantDemand() { public void addInfo(List textList) { // Max Computation - MutableComponent data = Component.literal(Integer.toString(getMaxCWUt())).withStyle(ChatFormatting.AQUA); + MutableComponent data = Component.literal(Integer.toString(maxCWUt())).withStyle(ChatFormatting.AQUA); textList.add(Component.translatable("gtceu.multiblock.hpca.info_max_computation", data) .withStyle(ChatFormatting.GRAY)); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java index 58d5782a10..2dff8f5c88 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/NetworkSwitchMachine.java @@ -1,36 +1,30 @@ package com.gregtechceu.gtceu.common.machine.multiblock.electric.research; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.capability.recipe.IO; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; +import com.gregtechceu.gtceu.api.capability.data.query.ComputationQuery; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; -import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.multiblock.MultiblockDisplayText; import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; -import com.gregtechceu.gtceu.api.machine.trait.NotifiableComputationContainer; + +import com.lowdragmc.lowdraglib.Platform; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.Block; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import lombok.AccessLevel; -import lombok.Getter; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.Collection; import java.util.List; -import java.util.Set; import javax.annotation.ParametersAreNonnullByDefault; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault -public class NetworkSwitchMachine extends DataBankMachine implements IOpticalComputationProvider { +public class NetworkSwitchMachine extends DataBankMachine { public static final int EUT_PER_HATCH = GTValues.VA[GTValues.IV]; - private final MultipleComputationHandler computationHandler = new MultipleComputationHandler(this); + private long nextQueryTick; + private ComputationQuery query; public NetworkSwitchMachine(IMachineBlockEntity holder) { super(holder); @@ -49,68 +43,7 @@ protected int calculateEnergyUsage() { ++transmitters; } } - return GTValues.VA[GTValues.IV] * (receivers + transmitters); - } - - @Override - public void onStructureFormed() { - super.onStructureFormed(); - List receivers = new ArrayList<>(); - List transmitters = new ArrayList<>(); - for (var part : this.getParts()) { - if (part instanceof IOpticalComputationHatch hatch) { - Block block = part.self().getBlockState().getBlock(); - if (PartAbility.COMPUTATION_DATA_RECEPTION.isApplicable(block)) { - receivers.add(hatch); - } - if (PartAbility.COMPUTATION_DATA_TRANSMISSION.isApplicable(block)) { - transmitters.add(hatch); - } - } else if (part.getRecipeHandlers().stream().anyMatch(IOpticalComputationHatch.class::isInstance)) { - var hatch = part.getRecipeHandlers().stream().filter(IOpticalComputationHatch.class::isInstance) - .map(IOpticalComputationHatch.class::cast).findFirst().orElse(null); - if (hatch != null) { - Block block = part.self().getBlockState().getBlock(); - if (PartAbility.COMPUTATION_DATA_RECEPTION.isApplicable(block)) { - receivers.add(hatch); - } - if (PartAbility.COMPUTATION_DATA_TRANSMISSION.isApplicable(block)) { - transmitters.add(hatch); - } - } - } - } - computationHandler.onStructureForm(receivers, transmitters); - } - - @Override - public void onStructureInvalid() { - super.onStructureInvalid(); - computationHandler.reset(); - } - - @Override - public int getEnergyUsage() { - return isFormed() ? computationHandler.getEUt() : 0; - } - - @Override - public int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { - seen.add(this); - return isActive() && !getRecipeLogic().isWaiting() ? computationHandler.requestCWUt(cwut, simulate, seen) : 0; - } - - @Override - public int getMaxCWUt(@NotNull Collection seen) { - seen.add(this); - return isFormed() ? computationHandler.getMaxCWUt(seen) : 0; - } - - // allows chaining Network Switches together - @Override - public boolean canBridge(@NotNull Collection seen) { - seen.add(this); - return true; + return EUT_PER_HATCH * (receivers + transmitters); } @Override @@ -122,7 +55,7 @@ public void addDisplayText(List textList) { "gtceu.multiblock.idling", "gtceu.multiblock.data_bank.providing") .addEnergyUsageExactLine(getEnergyUsage()) - .addComputationUsageLine(computationHandler.getMaxCWUtForDisplay()) + .addComputationUsageLine(queryConnected().maxCWUt()) .addWorkingStatusLine(); } @@ -137,105 +70,17 @@ public void addDisplayText(List textList) { * } */ - /** Handles computation load across multiple receivers and to multiple transmitters. */ - private static class MultipleComputationHandler extends NotifiableComputationContainer { - - // providers in the NS provide distributable computation to the NS - private final Set providers = new ObjectOpenHashSet<>(); - // transmitters in the NS give computation to other multis - private final Set transmitters = new ObjectOpenHashSet<>(); - - /** The EU/t cost of this Network Switch given the attached providers and transmitters. */ - @Getter(value = AccessLevel.PRIVATE) - private int EUt; - - public MultipleComputationHandler(MetaMachine machine) { - super(machine, IO.IN, false); - } - - private void onStructureForm(Collection providers, - Collection transmitters) { - reset(); - this.providers.addAll(providers); - this.transmitters.addAll(transmitters); - this.EUt = (providers.size() + transmitters.size()) * EUT_PER_HATCH; - } - - private void reset() { - providers.clear(); - transmitters.clear(); - EUt = 0; - } - - @Override - public int requestCWUt(int cwut, boolean simulate, @NotNull Collection seen) { - if (seen.contains(this)) return 0; - // The max CWU/t that this Network Switch can provide, combining all its inputs. - seen.add(this); - Collection bridgeSeen = new ArrayList<>(seen); - int allocatedCWUt = 0; - for (var provider : providers) { - if (!provider.canBridge(bridgeSeen)) continue; - int allocated = provider.requestCWUt(cwut, simulate, seen); - allocatedCWUt += allocated; - cwut -= allocated; - if (cwut == 0) break; - } - return allocatedCWUt; - } - - public int getMaxCWUtForDisplay() { - Collection seen = new ArrayList<>(); - // The max CWU/t that this Network Switch can provide, combining all its inputs. - seen.add(this); - Collection bridgeSeen = new ArrayList<>(seen); - int maximumCWUt = 0; - for (var provider : providers) { - if (!provider.canBridge(bridgeSeen)) continue; - maximumCWUt += provider.getMaxCWUt(seen); - } - return maximumCWUt; - } - - public int getMaxCWUt(@NotNull Collection seen) { - if (seen.contains(this)) return 0; - // The max CWU/t that this Network Switch can provide, combining all its inputs. - seen.add(this); - Collection bridgeSeen = new ArrayList<>(seen); - int maximumCWUt = 0; - for (var provider : providers) { - if (!provider.canBridge(bridgeSeen)) continue; - maximumCWUt += provider.getMaxCWUt(seen); - } - return maximumCWUt; - } - - @Override - public boolean canBridge(@NotNull Collection seen) { - if (seen.contains(this)) return false; - seen.add(this); - for (var provider : providers) { - if (provider.canBridge(seen)) { - return true; - } - } - return false; - } - - /** Test if any of the provider hatches do not allow bridging */ - private boolean hasNonBridgingConnections() { - Collection seen = new ArrayList<>(); - for (var provider : providers) { - if (!provider.canBridge(seen)) { - return true; - } - } - return false; - } - - @Override - public IOpticalComputationProvider getComputationProvider() { - return this; + private ComputationQuery queryConnected() { + long tick = Platform.getMinecraftServer().getTickCount(); + if (tick >= nextQueryTick) { + this.query = new ComputationQuery(); + List dataAccesses = getParts().stream() + .filter(IDataAccess.class::isInstance) + .map(IDataAccess.class::cast) + .toList(); + IDataAccess.accessData(dataAccesses, query); + this.nextQueryTick = tick + 10; } + return this.query; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java index 63b5fee4f0..f594e5e6bd 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/research/ResearchStationMachine.java @@ -1,7 +1,9 @@ package com.gregtechceu.gtceu.common.machine.multiblock.electric.research; import com.gregtechceu.gtceu.api.capability.IObjectHolder; -import com.gregtechceu.gtceu.api.capability.forge.GTCapability; +import com.gregtechceu.gtceu.api.capability.data.IComputationUser; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; +import com.gregtechceu.gtceu.api.capability.data.query.ComputationQuery; import com.gregtechceu.gtceu.api.capability.recipe.CWURecipeCapability; import com.gregtechceu.gtceu.api.capability.recipe.IO; import com.gregtechceu.gtceu.api.capability.recipe.IRecipeCapabilityHolder; @@ -22,15 +24,14 @@ import java.util.Collections; import java.util.Iterator; +import java.util.List; import javax.annotation.ParametersAreNonnullByDefault; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault -public class ResearchStationMachine extends WorkableElectricMultiblockMachine implements IOpticalComputationReceiver { +public class ResearchStationMachine extends WorkableElectricMultiblockMachine implements IComputationUser { - @Getter - private IOpticalComputationProvider computationProvider; @Getter private IObjectHolder objectHolder; @@ -52,36 +53,26 @@ public ResearchStationRecipeLogic getRecipeLogic() { public void onStructureFormed() { super.onStructureFormed(); for (IMultiPart part : getParts()) { - IOpticalComputationProvider provider = part.self().holder.self() - .getCapability(GTCapability.CAPABILITY_COMPUTATION_PROVIDER).resolve().orElse(null); - if (provider != null) { - this.computationProvider = provider; - } - if (part instanceof IObjectHolder objectHolder) { - this.objectHolder = objectHolder; + if (part instanceof IObjectHolder holder) { + if (part.self().getFrontFacing() != this.getFrontFacing().getOpposite()) { + onStructureInvalid(); + return; + } + this.objectHolder = holder; this.getCapabilitiesProxy().put(IO.IN, ItemRecipeCapability.CAP, - Collections.singletonList(objectHolder.getAsHandler())); + Collections.singletonList(holder.getAsHandler())); + break; } } // should never happen, but would rather do this than have an obscure NPE - if (computationProvider == null || objectHolder == null) { - onStructureInvalid(); - } - } - - @Override - public boolean checkPattern() { - boolean isFormed = super.checkPattern(); - if (isFormed && objectHolder != null && objectHolder.getFrontFacing() != getFrontFacing().getOpposite()) { + if (objectHolder == null) { onStructureInvalid(); } - return isFormed; } @Override public void onStructureInvalid() { - computationProvider = null; // recheck the ability to make sure it wasn't the one broken for (IMultiPart part : getParts()) { if (part instanceof IObjectHolder holder) { @@ -99,6 +90,21 @@ public boolean dampingWhenWaiting() { return false; } + @Override + public long requestCWU(long requested, boolean simulate) { + return queryConnected().requestCWU(requested, simulate); + } + + private ComputationQuery queryConnected() { + ComputationQuery query = new ComputationQuery(); + List dataAccesses = getParts().stream() + .filter(IDataAccess.class::isInstance) + .map(IDataAccess.class::cast) + .toList(); + IDataAccess.accessData(dataAccesses, query); + return query; + } + private static class ResearchStationRecipeLogic extends RecipeLogic { public ResearchStationRecipeLogic(ResearchStationMachine metaBlockEntity) { @@ -217,9 +223,10 @@ public void onRecipeFinish() { holder.setHeldItem(ItemStack.EMPTY); ItemStack outputItem = ItemStack.EMPTY; - if (lastRecipe.getOutputContents(ItemRecipeCapability.CAP).size() >= 1) { + var outputContents = lastRecipe.getOutputContents(ItemRecipeCapability.CAP); + if (!outputContents.isEmpty()) { outputItem = ItemRecipeCapability.CAP - .of(getLastRecipe().getOutputContents(ItemRecipeCapability.CAP).get(0).content).getItems()[0]; + .of(outputContents.get(0).content).getItems()[0]; } holder.setDataItem(outputItem); holder.setLocked(false); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java index 2a0475c6c6..0d95852a68 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java @@ -97,8 +97,6 @@ public boolean canShared() { @Override public GTRecipe modifyRecipe(GTRecipe recipe) { // creative hatches do not need to check, they always have the recipe - // TODO creative data access hatch - // if (this.isCreative()) return recipe; RecipeDataQuery query = new RecipeDataQuery(recipe); // hatches need to have the recipe available diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java index 4af205bff1..bb49427b00 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/storage/CreativeComputationProviderMachine.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.machine.storage; +import com.gregtechceu.gtceu.api.capability.data.IComputationProvider; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MetaMachine; @@ -20,25 +21,22 @@ import net.minecraft.world.entity.player.Player; import lombok.Getter; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collection; - import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class CreativeComputationProviderMachine extends MetaMachine - implements IUIMachine, IOpticalComputationProvider { + implements IUIMachine, IComputationProvider { public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder( CreativeComputationProviderMachine.class, MetaMachine.MANAGED_FIELD_HOLDER); @Persisted - private int maxCWUt; - private int lastRequestedCWUt; - private int requestedCWUPerSec; + private long maxCWUt; + private long lastRequestedCWUt; + private long requestedCWUPerSec; @Persisted @Getter private boolean active; @@ -74,10 +72,8 @@ protected void updateComputationTick() { } @Override - public int requestCWUt( - int cwut, boolean simulate, @NotNull Collection seen) { - seen.add(this); - int requestedCWUt = active ? Math.min(cwut, maxCWUt) : 0; + public long supplyCWU(long cwut, boolean simulate) { + long requestedCWUt = active ? Math.min(cwut, maxCWUt) : 0; if (!simulate) { this.requestedCWUPerSec += requestedCWUt; } @@ -85,14 +81,12 @@ public int requestCWUt( } @Override - public int getMaxCWUt(@NotNull Collection seen) { - seen.add(this); + public long maxCWUt() { return active ? maxCWUt : 0; } @Override - public boolean canBridge(@NotNull Collection seen) { - seen.add(this); + public boolean supportsBridging() { return true; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java index 0378e2d031..6203b9efda 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java @@ -173,15 +173,15 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { // insulated cables cool down half as fast float coolingFactor = (float) (Math.sqrt(cable.material()) / (insulated ? 8 : 4)); data.setLogicEntry(VoltageLossLogic.INSTANCE.supplier().get().getWith(loss)) - .setLogicEntry(WeightFactorLogic.TYPE.supplier().get().getWith(loss + 0.001 / amperage)) - .setLogicEntry(ThroughputLogic.TYPE.getWith(amperage)) - .setLogicEntry(VoltageLimitLogic.TYPE.supplier().get().getWith(voltageLimit)) - .setLogicEntry(TemperatureLogic.TYPE.supplier().get() + .setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.TYPE.getNew().getWith(voltageLimit)) + .setLogicEntry(TemperatureLogic.TYPE.getNew() .getWith(TemperatureLossFunction.getOrCreateCable(coolingFactor), materialMeltTemperature, 1, 100 * cable.material(), cable.partialBurnThreshold())); if (superconductorCriticalTemperature > 0) { - data.setLogicEntry(SuperconductorLogic.TYPE.supplier().get().getWith(superconductorCriticalTemperature)); + data.setLogicEntry(SuperconductorLogic.TYPE.getNew().getWith(superconductorCriticalTemperature)); } } else if (structure instanceof MaterialPipeStructure pipe) { long amperage = getAmperage(structure); @@ -189,14 +189,14 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { long loss = getLoss(structure); float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); data.setLogicEntry(VoltageLossLogic.INSTANCE.supplier().get().getWith(loss)) - .setLogicEntry(WeightFactorLogic.TYPE.supplier().get().getWith(loss + 0.001 / amperage)) - .setLogicEntry(ThroughputLogic.TYPE.supplier().get().getWith(amperage)) - .setLogicEntry(VoltageLimitLogic.TYPE.supplier().get().getWith(voltageLimit)) - .setLogicEntry(TemperatureLogic.TYPE.supplier().get() + .setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.TYPE.getNew().getWith(voltageLimit)) + .setLogicEntry(TemperatureLogic.TYPE.getNew() .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, 1, 50 * pipe.material(), null)); if (superconductorCriticalTemperature > 0) { - data.setLogicEntry(SuperconductorLogic.TYPE.supplier().get().getWith(superconductorCriticalTemperature)); + data.setLogicEntry(SuperconductorLogic.TYPE.getNew().getWith(superconductorCriticalTemperature)); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java index f09e4a4ff1..ad01defcf7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java @@ -178,11 +178,11 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { if (structure instanceof MaterialPipeStructure pipe) { long throughput = getThroughput(structure); float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); - data.setLogicEntry(WeightFactorLogic.TYPE.getWith(getFlowPriority(structure))) - .setLogicEntry(ThroughputLogic.TYPE.getWith(throughput)) - .setLogicEntry(FluidContainmentLogic.TYPE.getWith(containableStates, containedAttributes, + data.setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(throughput)) + .setLogicEntry(FluidContainmentLogic.TYPE.getNew().getWith(containableStates, containedAttributes, maxFluidTemperature)) - .setLogicEntry(TemperatureLogic.TYPE + .setLogicEntry(TemperatureLogic.TYPE.getNew() .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, minFluidTemperature, 50 * pipe.material(), null)); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java index 39eee87be6..0074acfbe3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java @@ -83,8 +83,8 @@ public WorldPipeNetNode getOrCreateFromNet(ServerLevel world, BlockPos pos, IPip public void mutateData(NetLogicData data, IPipeStructure structure) { if (structure instanceof MaterialPipeStructure pipe) { long throughput = baseItemsPer5Ticks * pipe.material(); - data.setLogicEntry(WeightFactorLogic.TYPE.getWith(getFlowPriority(structure))) - .setLogicEntry(ThroughputLogic.TYPE.getWith(throughput)); + data.setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(throughput)); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java index 7edc8e43a1..4b9367311d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java @@ -1,8 +1,8 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; - import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; + import net.minecraft.nbt.ByteTag; import net.minecraft.network.FriendlyByteBuf; @@ -17,7 +17,8 @@ public class EnergyFlowLogic extends NetLogicEntry { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EnergyFlow", EnergyFlowLogic::new); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EnergyFlow", + EnergyFlowLogic::new); private final AveragingPerTickCounter averageVoltageCounter = new AveragingPerTickCounter(); private final AveragingPerTickCounter averageAmperageCounter = new AveragingPerTickCounter(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java index 23b0c5fbc6..da375bdbb7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java @@ -128,7 +128,7 @@ public void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNo private void recordFlow(@NotNull NetNode node, long amperes) { EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.TYPE); if (logic == null) { - logic = EnergyFlowLogic.TYPE.supplier().get(); + logic = EnergyFlowLogic.TYPE.getNew(); node.getData().setLogicEntry(logic); } logic.recordFlow(getQueryTick(), new EnergyFlowData(amperes, pathVoltage)); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java index cd4b080630..af77671332 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java @@ -5,7 +5,8 @@ public final class SuperconductorLogic extends AbstractIntLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Superconductor", () -> new SuperconductorLogic().setValue(0)); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Superconductor", + () -> new SuperconductorLogic().setValue(0)); public SuperconductorLogic() { super(TYPE); @@ -14,5 +15,4 @@ public SuperconductorLogic() { public boolean canSuperconduct(int temp) { return this.getValue() > temp; } - } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java index 70b47ee9a6..7759ed7892 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java @@ -6,7 +6,8 @@ public final class VoltageLimitLogic extends AbstractLongLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("VoltageLimit", () -> new VoltageLimitLogic().setValue(0)); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("VoltageLimit", + () -> new VoltageLimitLogic().setValue(0)); private VoltageLimitLogic() { super(TYPE); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java index 86fb4df271..47f533974f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java @@ -6,7 +6,8 @@ public final class VoltageLossLogic extends AbstractLongLogicData { - public static final NetLogicEntryType INSTANCE = new NetLogicEntryType<>("VoltageLoss", () -> new VoltageLossLogic().setValue(0)); + public static final NetLogicEntryType INSTANCE = new NetLogicEntryType<>("VoltageLoss", + () -> new VoltageLossLogic().setValue(0)); private VoltageLossLogic() { super(INSTANCE); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java index 42fbf11c56..23fe6a7cc5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java @@ -24,7 +24,8 @@ public final class FluidContainmentLogic extends NetLogicEntry { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("FluidContainment", () -> new FluidContainmentLogic().contain(FluidState.LIQUID)); + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("FluidContainment", + () -> new FluidContainmentLogic().contain(FluidState.LIQUID)); private int maximumTemperature; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java index c5a3d9338f..9a7a594362 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidEQTraverseData.java @@ -9,13 +9,12 @@ import com.lowdragmc.lowdraglib.side.fluid.FluidTransferHelper; import com.lowdragmc.lowdraglib.side.fluid.IFluidTransfer; - import com.lowdragmc.lowdraglib.side.fluid.forge.FluidTransferHelperImpl; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; - import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.fluids.capability.IFluidHandler; + import org.jetbrains.annotations.NotNull; public class FluidEQTraverseData extends FluidTraverseData @@ -78,12 +77,13 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReach continue; // anti insert-to-our-source logic var containerCap = capability.getValue() - .getCapability(ForgeCapabilities.FLUID_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + .getCapability(ForgeCapabilities.FLUID_HANDLER, capability.getKey().getOpposite()).resolve() + .orElse(null); if (containerCap != null) { IFluidTransfer container = FluidTransferHelperImpl.toFluidTransfer(containerCap); availableFlow -= IFluidTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(Integer.MAX_VALUE, flowPerDestination), container, !simulating()); + (int) Math.min(Integer.MAX_VALUE, flowPerDestination), container, !simulating()); } } return flowReachingNode - availableFlow; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java index 44696bc048..35a980fc02 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemEQTraverseData.java @@ -79,12 +79,13 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode node, long flowReach continue; // anti insert-to-our-source logic IItemHandler containerCap = capability.getValue() - .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve().orElse(null); + .getCapability(ForgeCapabilities.ITEM_HANDLER, capability.getKey().getOpposite()).resolve() + .orElse(null); if (containerCap != null) { IItemTransfer container = ItemTransferHelperImpl.toItemTransfer(containerCap); availableFlow = IItemTransferController.CONTROL.get(node.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())).insertToHandler(getTestObject(), - (int) Math.min(Integer.MAX_VALUE, flowPerDestination), container, simulating()); + (int) Math.min(Integer.MAX_VALUE, flowPerDestination), container, simulating()); } } return flowReachingNode - availableFlow; diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/builder/GTRecipeBuilder.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/builder/GTRecipeBuilder.java index 3292ec89e5..ca683d4a5b 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/builder/GTRecipeBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/builder/GTRecipeBuilder.java @@ -243,7 +243,7 @@ public GTRecipeBuilder outputEU(long eu) { return output(EURecipeCapability.CAP, eu); } - public GTRecipeBuilder inputCWU(int cwu) { + public GTRecipeBuilder inputCWU(long cwu) { return input(CWURecipeCapability.CAP, cwu); } @@ -268,7 +268,7 @@ public GTRecipeBuilder totalCWU(int cwu) { return this; } - public GTRecipeBuilder outputCWU(int cwu) { + public GTRecipeBuilder outputCWU(long cwu) { return output(CWURecipeCapability.CAP, cwu); } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/GTRecipeWidget.java b/src/main/java/com/gregtechceu/gtceu/integration/GTRecipeWidget.java index 8a34fcfd0c..dafe8df004 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/GTRecipeWidget.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/GTRecipeWidget.java @@ -191,8 +191,8 @@ private static List getRecipeParaText(GTRecipe recipe, int duration, // sadly we still need a custom override here, since computation uses duration and EU/t very differently if (recipe.data.getBoolean("duration_is_total_cwu") && recipe.tickInputs.containsKey(CWURecipeCapability.CAP)) { - int minimumCWUt = Math.max(recipe.tickInputs.get(CWURecipeCapability.CAP).stream() - .map(Content::getContent).mapToInt(CWURecipeCapability.CAP::of).sum(), 1); + long minimumCWUt = Math.max(recipe.tickInputs.get(CWURecipeCapability.CAP).stream() + .map(Content::getContent).mapToLong(CWURecipeCapability.CAP::of).sum(), 1); texts.add(Component.translatable("gtceu.recipe.max_eu", FormattingUtil.formatNumbers(euTotal / minimumCWUt))); } else { diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java index e2128f8a6f..f0fc0397f5 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/GTJadePlugin.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.integration.jade; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.MaterialPipeBlockEntity; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.integration.jade.provider.*; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java index 7b5b3dc90d..0e33195c9d 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/CableInfoProvider.java @@ -36,7 +36,7 @@ public void addProbeInfo(ProbeMode probeMode, IProbeInfo iProbeInfo, Player play return; } WorldPipeNetNode node = WorldEnergyNet.getWorldNet(serverLevel).getNode(iProbeHitData.getPos()); - EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.INSTANCE); + EnergyFlowLogic logic = node.getData().getLogicEntryNullable(EnergyFlowLogic.TYPE); long currentTick = serverLevel.getServer().getTickCount(); long totalVoltage = 0L; From 3b91b68a4420e96e50dcea50a2d8312c8af26391 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 19:08:12 +0300 Subject: [PATCH 28/70] remove ancient "fixers" that are definitely no longer needed --- .../gtceu/forge/ForgeCommonEventListener.java | 54 ------------------- 1 file changed, 54 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index 2cf95924d5..ca0ac78bfc 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -1,9 +1,7 @@ package com.gregtechceu.gtceu.forge; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.GTCEuAPI; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.block.MaterialBlock; import com.gregtechceu.gtceu.api.block.MetaMachineBlock; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.IMedicalConditionTracker; @@ -13,10 +11,8 @@ import com.gregtechceu.gtceu.api.data.chemical.material.properties.HazardProperty; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.data.medicalcondition.MedicalCondition; -import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.item.DrumMachineItem; import com.gregtechceu.gtceu.api.item.IComponentItem; -import com.gregtechceu.gtceu.api.item.TagPrefixItem; import com.gregtechceu.gtceu.api.item.armor.ArmorComponentItem; import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.feature.IInteractedMachine; @@ -82,16 +78,9 @@ import net.minecraftforge.items.IItemHandler; import net.minecraftforge.registries.MissingMappingsEvent; -import com.tterrag.registrate.util.entry.BlockEntry; -import com.tterrag.registrate.util.entry.ItemEntry; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.gregtechceu.gtceu.utils.FormattingUtil.toLowerCaseUnder; - /** * @author KilaBash * @date 2022/8/27 @@ -386,17 +375,6 @@ public static void onChunkUnWatch(ChunkWatchEvent.UnWatch event) { @SubscribeEvent public static void remapIds(MissingMappingsEvent event) { - event.getMappings(Registries.BLOCK, GTCEu.MOD_ID).forEach(mapping -> { - if (mapping.getKey().equals(GTCEu.id("tungstensteel_coil_block"))) { - mapping.remap(GTBlocks.COIL_RTMALLOY.get()); - } - }); - event.getMappings(Registries.ITEM, GTCEu.MOD_ID).forEach(mapping -> { - if (mapping.getKey().equals(GTCEu.id("tungstensteel_coil_block"))) { - mapping.remap(GTBlocks.COIL_RTMALLOY.get().asItem()); - } - }); - event.getMappings(Registries.BLOCK, "gregiceng").forEach(mapping -> { String path = mapping.getKey().getPath(); switch (path) { @@ -474,37 +452,5 @@ public static void remapIds(MissingMappingsEvent event) { } } }); - - for (TagPrefix prefix : TagPrefix.values()) { - String first = prefix.invertedName ? toLowerCaseUnder(prefix.name) : "(.+?)"; - String last = prefix.invertedName ? "(.+?)" : toLowerCaseUnder(prefix.name); - Pattern idPattern = Pattern.compile(first + "_" + last); - event.getMappings(Registries.BLOCK, GTCEu.MOD_ID).forEach(mapping -> { - Matcher matcher = idPattern.matcher(mapping.getKey().getPath()); - if (matcher.matches()) { - BlockEntry block = GTBlocks.MATERIAL_BLOCKS.get(prefix, - GTCEuAPI.materialManager.getRegistry(GTCEu.MOD_ID).get(matcher.group(1))); - if (block != null && block.isPresent()) { - mapping.remap(block.get()); - } - } - }); - event.getMappings(Registries.ITEM, GTCEu.MOD_ID).forEach(mapping -> { - Matcher matcher = idPattern.matcher(mapping.getKey().getPath()); - if (matcher.matches()) { - BlockEntry block = GTBlocks.MATERIAL_BLOCKS.get(prefix, - GTCEuAPI.materialManager.getRegistry(GTCEu.MOD_ID).get(matcher.group(1))); - if (block != null && block.isPresent()) { - mapping.remap(block.asItem()); - } else { - ItemEntry item = GTItems.MATERIAL_ITEMS.get(prefix, - GTCEuAPI.materialManager.getRegistry(GTCEu.MOD_ID).get(matcher.group(1))); - if (item != null && item.isPresent()) { - mapping.remap(item.asItem()); - } - } - } - }); - } } } From de5bb4da495454b0154903b02c36a37f0d7bc020 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 19:09:42 +0300 Subject: [PATCH 29/70] add datafixer internal code --- .../com/gregtechceu/gtceu/api/GTCEuAPI.java | 2 + .../api/datafixer/DataFixesInternals.java | 99 +++++++++ .../api/datafixer/DataFixesInternalsImpl.java | 82 +++++++ .../gtceu/api/datafixer/EmptySchema.java | 52 +++++ .../gtceu/api/datafixer/FirstSchema.java | 50 +++++ .../gregtechceu/gtceu/api/datafixer/LICENSE | 205 ++++++++++++++++++ .../api/datafixer/NoOpDataFixesInternals.java | 60 +++++ .../core/mixins/ChunkSerializerMixin.java | 23 ++ .../gtceu/core/mixins/DataFixTypesMixin.java | 28 +++ .../gtceu/core/mixins/HotbarManagerMixin.java | 25 +++ .../gtceu/core/mixins/IOWorkerMixin.java | 26 +++ .../gtceu/core/mixins/StructureMixin.java | 22 ++ src/main/resources/gtceu.mixins.json | 5 + 13 files changed, 679 insertions(+) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternals.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternalsImpl.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/datafixer/EmptySchema.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/datafixer/FirstSchema.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/datafixer/LICENSE create mode 100644 src/main/java/com/gregtechceu/gtceu/api/datafixer/NoOpDataFixesInternals.java create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/ChunkSerializerMixin.java create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/DataFixTypesMixin.java create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/HotbarManagerMixin.java create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/IOWorkerMixin.java create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/StructureMixin.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/GTCEuAPI.java b/src/main/java/com/gregtechceu/gtceu/api/GTCEuAPI.java index 1214cdbf1e..eb5bc0be78 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/GTCEuAPI.java +++ b/src/main/java/com/gregtechceu/gtceu/api/GTCEuAPI.java @@ -28,6 +28,8 @@ public class GTCEuAPI { + public static final int GT_DATA_VERSION = 2; + /** Will always be available */ public static GTCEu instance; /** Will be available at the Construction stage */ diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternals.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternals.java new file mode 100644 index 0000000000..2394224938 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternals.java @@ -0,0 +1,99 @@ +/* + * Copyright 2022 QuiltMC + * Modified by the Steam 'n' Rails (Railways) team + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.config.ConfigHolder; + +import net.minecraft.SharedConstants; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.util.datafix.DataFixers; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixUtils; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.*; + +import java.util.function.BiFunction; + +import static com.google.common.base.Preconditions.checkArgument; + +@ApiStatus.Internal +public abstract class DataFixesInternals { + + public static final BiFunction BASE_SCHEMA = (version, parent) -> { + checkArgument(version == 0, "version must be 0"); + checkArgument(parent == null, "parent must be null"); + return get().createBaseSchema(); + }; + + public record DataFixerEntry(DataFixer dataFixer, int currentVersion) {} + + @Contract(pure = true) + @Range(from = 0, to = Integer.MAX_VALUE) + public static int getModDataVersion(@NotNull Dynamic compound) { + return compound.get("GTCEu_DataVersion").asInt(0); + } + + private static DataFixesInternals instance; + + public static @NotNull DataFixesInternals get() { + if (instance == null) { + // Init config in case it's not loaded yet + ConfigHolder.init(); + if (!ConfigHolder.INSTANCE.compat.doDatafixers) { + instance = new NoOpDataFixesInternals(); + return instance; + } + + Schema latestVanillaSchema; + try { + latestVanillaSchema = DataFixers.getDataFixer() + .getSchema(DataFixUtils + .makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion())); + } catch (Exception e) { + latestVanillaSchema = null; + } + + if (latestVanillaSchema == null) { + GTCEu.LOGGER.warn("[GTCEuM DFU] Failed to initialize! Either someone stopped DFU from initializing,"); + GTCEu.LOGGER.warn("[GTCEuM DFU] or this Minecraft build is hosed."); + GTCEu.LOGGER.warn("[GTCEuM DFU] Using no-op implementation."); + instance = new NoOpDataFixesInternals(); + } else { + instance = new DataFixesInternalsImpl(latestVanillaSchema); + } + } + + return instance; + } + + public abstract void registerFixer(@Range(from = 0, to = Integer.MAX_VALUE) int currentVersion, + @NotNull DataFixer dataFixer); + + public abstract @Nullable DataFixerEntry getFixerEntry(); + + @Contract(value = "-> new", pure = true) + public abstract @NotNull Schema createBaseSchema(); + + public abstract @NotNull Dynamic updateWithAllFixers(DSL.TypeReference dataFixTypes, + @NotNull Dynamic dynamic); + + public abstract @NotNull CompoundTag addModDataVersions(@NotNull CompoundTag compound); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternalsImpl.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternalsImpl.java new file mode 100644 index 0000000000..9337f273f7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternalsImpl.java @@ -0,0 +1,82 @@ +/* + * Copyright 2022 QuiltMC + * Modified by the Steam 'n' Rails (Railways) team + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.gregtechceu.gtceu.common.datafixer.schemas.V0; + +import net.minecraft.nbt.CompoundTag; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Range; + +@ApiStatus.Internal +public final class DataFixesInternalsImpl extends DataFixesInternals { + + private final @NotNull Schema latestVanillaSchema; + + private DataFixerEntry dataFixer; + + public DataFixesInternalsImpl(@NotNull Schema latestVanillaSchema) { + this.latestVanillaSchema = latestVanillaSchema; + + this.dataFixer = null; + } + + @Override + public void registerFixer(@Range(from = 0, to = Integer.MAX_VALUE) int currentVersion, + @NotNull DataFixer dataFixer) { + if (this.dataFixer != null) { + throw new IllegalArgumentException("GTCEu already has a registered data fixer"); + } + + this.dataFixer = new DataFixerEntry(dataFixer, currentVersion); + } + + @Override + public @Nullable DataFixerEntry getFixerEntry() { + return dataFixer; + } + + @Override + public @NotNull Schema createBaseSchema() { + return new V0(0, this.latestVanillaSchema); + } + + @Override + public @NotNull Dynamic updateWithAllFixers(DSL.TypeReference type, @NotNull Dynamic dynamic) { + if (dataFixer != null) { + int modDataVersion = DataFixesInternals.getModDataVersion(dynamic); + dynamic = dataFixer.dataFixer().update(type, dynamic, modDataVersion, dataFixer.currentVersion()); + } + + return dynamic; + } + + @Override + public @NotNull CompoundTag addModDataVersions(@NotNull CompoundTag compound) { + if (dataFixer != null) + compound.putInt("GTCEu_DataVersion", dataFixer.currentVersion()); + + return compound; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/EmptySchema.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/EmptySchema.java new file mode 100644 index 0000000000..d52a41cd07 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/EmptySchema.java @@ -0,0 +1,52 @@ +/* + * Copyright 2022 QuiltMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.Type; +import com.mojang.datafixers.types.templates.TypeTemplate; +import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; +import org.jetbrains.annotations.Range; + +import java.util.Map; +import java.util.function.Supplier; + +/** + * Represents an empty {@link Schema}, having no parent and containing no type definitions. + */ +public final class EmptySchema extends FirstSchema { + + /** + * Constructs an empty schema. + * + * @param versionKey the data version key + */ + public EmptySchema(@Range(from = 0, to = Integer.MAX_VALUE) int versionKey) { + super(versionKey); + } + + // Ensure the schema stays empty. + @Override + public void registerType(boolean recursive, DSL.TypeReference type, Supplier template) { + throw new UnsupportedOperationException(); + } + + @Override + protected Map> buildTypes() { + return Object2ObjectMaps.emptyMap(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/FirstSchema.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/FirstSchema.java new file mode 100644 index 0000000000..a04730bf6d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/FirstSchema.java @@ -0,0 +1,50 @@ +/* + * Copyright 2022 QuiltMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.templates.TypeTemplate; +import org.jetbrains.annotations.Range; + +import java.util.Map; +import java.util.function.Supplier; + +public class FirstSchema extends Schema { + + /** + * Creates a schema. + * + * @param versionKey the data version key + */ + public FirstSchema(@Range(from = 0, to = Integer.MAX_VALUE) int versionKey) { + super(versionKey, null); + } + + // all of these methods refer to this.parent without checking if its null + @Override + public void registerTypes(Schema schema, Map> entityTypes, + Map> blockEntityTypes) {} + + @Override + public Map> registerEntities(Schema schema) { + return Map.of(); + } + + @Override + public Map> registerBlockEntities(Schema schema) { + return Map.of(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/LICENSE b/src/main/java/com/gregtechceu/gtceu/api/datafixer/LICENSE new file mode 100644 index 0000000000..ad5b29c1e3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/LICENSE @@ -0,0 +1,205 @@ +Certain portions of the datafixer are taken from the +Quilt Standard Library (https://github.com/QuiltMC/quilt-standard-libraries), +and as such are licensed under the following license: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/NoOpDataFixesInternals.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/NoOpDataFixesInternals.java new file mode 100644 index 0000000000..473f347558 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/NoOpDataFixesInternals.java @@ -0,0 +1,60 @@ +/* + * Copyright 2022 QuiltMC + * Modified by the Steam 'n' Rails (Railways) team + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import net.minecraft.nbt.CompoundTag; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Range; + +public class NoOpDataFixesInternals extends DataFixesInternals { + + private final Schema schema; + + public NoOpDataFixesInternals() { + schema = new EmptySchema(0); + } + + @Override + public void registerFixer(@Range(from = 0, to = Integer.MAX_VALUE) int currentVersion, + @NotNull DataFixer dataFixer) {} + + @Override + public @Nullable DataFixerEntry getFixerEntry() { + return null; + } + + @Override + public @NotNull Schema createBaseSchema() { + return schema; + } + + @Override + public @NotNull Dynamic updateWithAllFixers(DSL.TypeReference dataFixTypes, @NotNull Dynamic dynamic) { + return dynamic; + } + + @Override + public @NotNull CompoundTag addModDataVersions(@NotNull CompoundTag compound) { + return compound; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/ChunkSerializerMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/ChunkSerializerMixin.java new file mode 100644 index 0000000000..845ab6103e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/ChunkSerializerMixin.java @@ -0,0 +1,23 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.chunk.storage.ChunkSerializer; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +@Mixin(ChunkSerializer.class) +public abstract class ChunkSerializerMixin { + + @ModifyVariable( + method = "write", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/nbt/CompoundTag;putInt(Ljava/lang/String;I)V", + ordinal = 0)) + private static CompoundTag addModDataVersions(CompoundTag compound) { + return DataFixesInternals.get().addModDataVersions(compound); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/DataFixTypesMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/DataFixTypesMixin.java new file mode 100644 index 0000000000..2c3d2ab48e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/DataFixTypesMixin.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.util.datafix.DataFixTypes; + +import com.llamalad7.mixinextras.injector.ModifyReturnValue; +import com.mojang.datafixers.DSL; +import com.mojang.serialization.Dynamic; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(DataFixTypes.class) +public class DataFixTypesMixin { + + @Shadow + @Final + private DSL.TypeReference type; + + // ModifyReturnValue to inject our fixes *after* vanilla ones + @ModifyReturnValue(method = "update(Lcom/mojang/datafixers/DataFixer;Lcom/mojang/serialization/Dynamic;II)Lcom/mojang/serialization/Dynamic;", + at = @At(value = "RETURN")) + private Dynamic gtceu$injectDataFixers(Dynamic value) { + return DataFixesInternals.get().updateWithAllFixers(this.type, value); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/HotbarManagerMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/HotbarManagerMixin.java new file mode 100644 index 0000000000..1816463f50 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/HotbarManagerMixin.java @@ -0,0 +1,25 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.client.HotbarManager; +import net.minecraft.nbt.CompoundTag; + +import com.llamalad7.mixinextras.sugar.Local; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(HotbarManager.class) +public abstract class HotbarManagerMixin { + + @Inject( + method = "save", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/nbt/NbtIo;write(Lnet/minecraft/nbt/CompoundTag;Ljava/io/File;)V", + shift = At.Shift.AFTER)) + private void addModDataVersions(CallbackInfo ci, @Local CompoundTag tag) { + DataFixesInternals.get().addModDataVersions(tag); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/IOWorkerMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/IOWorkerMixin.java new file mode 100644 index 0000000000..7a7e1698c3 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/IOWorkerMixin.java @@ -0,0 +1,26 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.storage.IOWorker; + +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.concurrent.CompletableFuture; + +@Mixin(IOWorker.class) +public class IOWorkerMixin { + + @Inject(method = "store", at = @At("HEAD")) + private void storeDFUVersion(ChunkPos chunkPos, @Nullable CompoundTag chunkData, + CallbackInfoReturnable> cir) { + if (chunkData != null) + DataFixesInternals.get().addModDataVersions(chunkData); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/StructureMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/StructureMixin.java new file mode 100644 index 0000000000..cc956bf3ea --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/StructureMixin.java @@ -0,0 +1,22 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(StructureTemplate.class) +public abstract class StructureMixin { + + @Inject(method = "save", at = @At("TAIL"), cancellable = true) + private void addModDataVersions(CompoundTag compound, CallbackInfoReturnable cir) { + CompoundTag out = cir.getReturnValue(); + DataFixesInternals.get().addModDataVersions(out); + cir.setReturnValue(out); + } +} diff --git a/src/main/resources/gtceu.mixins.json b/src/main/resources/gtceu.mixins.json index 67db6275ee..0eef6cb1fd 100644 --- a/src/main/resources/gtceu.mixins.json +++ b/src/main/resources/gtceu.mixins.json @@ -13,6 +13,7 @@ "GuiGraphicsAccessor", "GuiGraphicsMixin", "GuiHeartTypeMixin", + "HotbarManagerMixin", "LevelRendererMixin", "ModelManagerMixin", "MultiPlayerGameModeMixin", @@ -25,12 +26,15 @@ "BlockPropertiesAccessor", "ChunkGeneratorMixin", "ChunkMixin", + "ChunkSerializerMixin", "CreeperMixin", + "DataFixTypesMixin", "EntityMixin", "IFoliagePlacerTypeAccessor", "IngredientAccessor", "IntersectionIngredientAccessor", "InventoryMixin", + "IOWorkerMixin", "ItemValueAccessor", "ITrunkPlacerTypeAccessor", "LevelMixin", @@ -50,6 +54,7 @@ "ShapedRecipeAccessor", "SidedRedstoneConnectivityMixin", "StrictNBTIngredientAccessor", + "StructureMixin", "TagLoaderMixin", "TagManagerMixin", "TagValueAccessor", From fe851d52485628d335fbb6f83d2cfae836b4ddd3 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 19:11:01 +0300 Subject: [PATCH 30/70] add datafixers from 1.21 and pipe remap fix --- .../gtceu/api/data/tag/TagPrefix.java | 2 +- .../api/machine/MachineCoverContainer.java | 2 +- .../gregtechceu/gtceu/common/CommonProxy.java | 2 + .../gtceu/common/block/StoneTypes.java | 2 +- .../gtceu/common/data/GTBedrockFluids.java | 4 +- .../gtceu/common/data/GTItems.java | 2 +- .../gtceu/common/data/GTMaterials.java | 8 +- .../common/data/datafixer/GTDataFixers.java | 95 +++++++ .../common/data/datafixer/GTReferences.java | 25 ++ .../data/materials/ElementMaterials.java | 4 +- .../data/materials/SecondDegreeMaterials.java | 2 +- .../UnknownCompositionMaterials.java | 6 +- .../datafixer/fixes/OilVariantsRenameFix.java | 20 ++ .../datafixer/schemas/BaseGTSchema.java | 36 +++ .../gtceu/common/datafixer/schemas/V0.java | 254 ++++++++++++++++++ .../gtceu/common/datafixer/schemas/V2.java | 44 +++ .../gtceu/config/ConfigHolder.java | 6 + .../gtceu/data/lang/LangHandler.java | 4 +- .../gtceu/data/recipe/misc/FuelRecipes.java | 4 +- .../data/recipe/misc/MachineRecipeLoader.java | 4 +- .../data/recipe/misc/MiscRecipeLoader.java | 4 +- .../data/recipe/misc/WoodMachineRecipes.java | 2 +- .../chemistry/PetrochemRecipes.java | 4 +- .../chemistry/SeparationRecipes.java | 2 +- .../gtceu/data/tags/BlockTagLoader.java | 4 +- 25 files changed, 512 insertions(+), 30 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTReferences.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/BaseGTSchema.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java index 5fba6fc0f5..4c15dedcd6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/tag/TagPrefix.java @@ -113,7 +113,7 @@ public static TagPrefix get(String name) { public static final TagPrefix oreRedGranite = oreTagPrefix("red_granite", BlockTags.MINEABLE_WITH_PICKAXE) .langValue("Red Granite %s Ore") - .registerOre(() -> GTBlocks.RED_GRANITE.getDefaultState(), () -> GTMaterials.GraniteRed, + .registerOre(() -> GTBlocks.RED_GRANITE.getDefaultState(), () -> GTMaterials.RedGranite, BlockBehaviour.Properties.of().mapColor(MapColor.TERRACOTTA_RED).requiresCorrectToolForDrops() .strength(3.0F, 3.0F), GTCEu.id("block/red_granite")); diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java index ac54841c49..14258539c7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/MachineCoverContainer.java @@ -271,7 +271,7 @@ private CoverBehavior deserializeCoverUid(CompoundTag uid) { return definition.createCoverBehavior(this, side); } GTCEu.LOGGER.error("couldn't find cover definition {}", definitionId); - throw new RuntimeException(); + throw new RuntimeException("couldn't find cover definition " + definitionId); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java index 00355d94e1..f1b931e29a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java @@ -25,6 +25,7 @@ import com.gregtechceu.gtceu.api.recipe.ingredient.SizedIngredient; import com.gregtechceu.gtceu.api.registry.GTRegistries; import com.gregtechceu.gtceu.common.data.*; +import com.gregtechceu.gtceu.common.data.datafixer.GTDataFixers; import com.gregtechceu.gtceu.common.data.materials.GTFoods; import com.gregtechceu.gtceu.common.item.tool.rotation.CustomBlockRotations; import com.gregtechceu.gtceu.common.network.GTNetwork; @@ -173,6 +174,7 @@ public static void init() { GTFeatures.register(); CustomBlockRotations.init(); KeyBind.init(); + GTDataFixers.init(); } private static void initMaterials() { diff --git a/src/main/java/com/gregtechceu/gtceu/common/block/StoneTypes.java b/src/main/java/com/gregtechceu/gtceu/common/block/StoneTypes.java index 96706d4a42..8ec9e8610b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/block/StoneTypes.java +++ b/src/main/java/com/gregtechceu/gtceu/common/block/StoneTypes.java @@ -22,7 +22,7 @@ public enum StoneTypes implements StringRepresentable { DEEPSLATE("deepslate", MapColor.DEEPSLATE, true, () -> Blocks.DEEPSLATE::defaultBlockState, GTMaterials.Deepslate, false), RED_GRANITE("red_granite", MapColor.COLOR_RED, true, () -> GTBlocks.RED_GRANITE::getDefaultState, - GTMaterials.GraniteRed), + GTMaterials.RedGranite), MARBLE("marble", MapColor.QUARTZ, true, () -> GTBlocks.MARBLE::getDefaultState, GTMaterials.Marble), ANDESITE("andesite", MapColor.STONE, true, () -> Blocks.ANDESITE::defaultBlockState, GTMaterials.Andesite, false), GRANITE("granite", MapColor.DIRT, true, () -> Blocks.GRANITE::defaultBlockState, GTMaterials.Granite, false), diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBedrockFluids.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBedrockFluids.java index 6ed969bb59..8d83864569 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBedrockFluids.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBedrockFluids.java @@ -30,7 +30,7 @@ public class GTBedrockFluids { // ******** OVERWORLD ********// ////////////////////////////////////// public static BedrockFluidDefinition HEAVY_OIL = create(GTCEu.id("heavy_oil_deposit"), builder -> builder - .fluid(GTMaterials.OilHeavy::getFluid) + .fluid(GTMaterials.HeavyOil::getFluid) .weight(15) .yield(100, 200) .depletionAmount(1) @@ -41,7 +41,7 @@ public class GTBedrockFluids { .dimensions(overworld())); public static BedrockFluidDefinition LIGHT_OIL = create(GTCEu.id("light_oil_deposit"), builder -> builder - .fluid(GTMaterials.OilLight::getFluid) + .fluid(GTMaterials.LightOil::getFluid) .weight(25) .yield(175, 300) .depletionAmount(1) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java index 3c6799326f..2f0604d2a7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java @@ -2661,7 +2661,7 @@ public Component getItemName(ItemStack stack) { .tag(Tags.Items.ARMORS_CHESTPLATES) .register(); public static ItemEntry NANO_CHESTPLATE_ADVANCED = REGISTRATE - .item("avanced_nanomuscle_chestplate", + .item("advanced_nanomuscle_chestplate", (p) -> new ArmorComponentItem(GTArmorMaterials.ARMOR, ArmorItem.Type.CHESTPLATE, p) .setArmorLogic(new AdvancedNanoMuscleSuite(512, 12_800_000L * (long) Math.max(1, diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java index f98673ff01..15809e6006 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java @@ -163,7 +163,7 @@ public static void init() { rock.setIgnored(Marble, SupplierMemoizer.memoizeBlockSupplier(() -> GTBlocks.MARBLE.get())); rock.setIgnored(Granite, Blocks.GRANITE); rock.setIgnored(Granite, Blocks.POLISHED_GRANITE); - rock.setIgnored(GraniteRed, SupplierMemoizer.memoizeBlockSupplier(() -> GTBlocks.RED_GRANITE.get())); + rock.setIgnored(RedGranite, SupplierMemoizer.memoizeBlockSupplier(() -> GTBlocks.RED_GRANITE.get())); rock.setIgnored(Andesite, Blocks.ANDESITE); rock.setIgnored(Andesite, Blocks.POLISHED_ANDESITE); rock.setIgnored(Diorite, Blocks.DIORITE); @@ -774,9 +774,9 @@ private static void excludeAllGemsButNormal(Material material) { public static Material ConstructionFoam; public static Material Oil; - public static Material OilHeavy; + public static Material HeavyOil; public static Material RawOil; - public static Material OilLight; + public static Material LightOil; public static Material NaturalGas; public static Material SulfuricHeavyFuel; public static Material HeavyFuel; @@ -907,7 +907,7 @@ private static void excludeAllGemsButNormal(Material material) { public static Material GarnetYellow; public static Material Marble; public static Material Deepslate; - public static Material GraniteRed; + public static Material RedGranite; public static Material VanadiumMagnetite; public static Material QuartzSand; public static Material Pollucite; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java new file mode 100644 index 0000000000..2687e21e45 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java @@ -0,0 +1,95 @@ +package com.gregtechceu.gtceu.common.data.datafixer; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.GTCEuAPI; +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; +import com.gregtechceu.gtceu.common.datafixer.fixes.OilVariantsRenameFix; +import com.gregtechceu.gtceu.common.datafixer.schemas.V2; +import com.gregtechceu.gtceu.config.ConfigHolder; + +import net.minecraft.util.datafix.DataFixTypes; +import net.minecraft.util.datafix.fixes.AddNewChoices; +import net.minecraft.util.datafix.fixes.BlockRenameFix; +import net.minecraft.util.datafix.fixes.ItemRenameFix; +import net.minecraft.util.datafix.fixes.References; +import net.minecraft.util.datafix.schemas.NamespacedSchema; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.DataFixerBuilder; +import com.mojang.datafixers.schemas.Schema; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.BiFunction; +import java.util.function.UnaryOperator; +import java.util.regex.Pattern; + +import static com.gregtechceu.gtceu.api.datafixer.DataFixesInternals.BASE_SCHEMA; + +public class GTDataFixers { + + private static final BiFunction SAME_NAMESPACED = NamespacedSchema::new; + + public static void init() { + if (!ConfigHolder.INSTANCE.compat.doDatafixers) { + return; + } + + GTCEu.LOGGER.info("Registering data fixers"); + + DataFixesInternals api = DataFixesInternals.get(); + + DataFixerBuilder builder = new DataFixerBuilder(GTCEuAPI.GT_DATA_VERSION); + addFixers(builder); + + ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() + .setNameFormat("GTM Datafixer Bootstrap").setDaemon(true).setPriority(1).build()); + DataFixer result = builder.buildOptimized(DataFixTypes.TYPES_FOR_LEVEL_LIST, executor); + api.registerFixer(GTCEuAPI.GT_DATA_VERSION, result); + } + + public static void addFixers(DataFixerBuilder builder) { + Schema schemaV0 = builder.addSchema(0, BASE_SCHEMA); + builder.addFixer(new AddNewChoices(schemaV0, "Added GT block entities", References.BLOCK_ENTITY)); + + Schema schemaV1 = builder.addSchema(1, SAME_NAMESPACED); + builder.addFixer(ItemRenameFix.create(schemaV1, "advanced_nanomuscle_chestplate rename fix", + createRenamer("gtceu:avanced_nanomuscle_chestplate", "gtceu:advanced_nanomuscle_chestplate"))); + + builder.addFixer(ItemRenameFix.create(schemaV1, "U238 rename fix", + createRenamer(Pattern.compile("gtceu:uranium_"), "gtceu:uranium_238_"))); + builder.addFixer(ItemRenameFix.create(schemaV1, "Pu239 rename fix", + createRenamer(Pattern.compile("gtceu:plutonium_"), "gtceu:plutonium_239_"))); + builder.addFixer(ItemRenameFix.create(schemaV1, "Red granite rename fix", + createRenamer(Pattern.compile("gtceu:granite_red"), "gtceu:red_granite"))); + + builder.addFixer(ItemRenameFix.create(schemaV1, "Raw oil bucket rename fix", + createRenamer(OilVariantsRenameFix.RENAMED_ITEM_IDS))); + builder.addFixer(BlockRenameFix.create(schemaV1, "Raw oil block rename fix", + createRenamer(OilVariantsRenameFix.RENAMED_BLOCK_IDS))); + + Schema schemaV2 = builder.addSchema(2, V2::new); + builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe block entities", References.BLOCK_ENTITY)); + builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe blocks", References.BLOCK_NAME)); + builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe items", References.ITEM_NAME)); + builder.addFixer(ItemRenameFix.create(schemaV2, "Item pipe rename fix", + createRenamer(Pattern.compile("_item_pipe"), "_pipe"))); + builder.addFixer(ItemRenameFix.create(schemaV2, "Fluid pipe rename fix", + createRenamer(Pattern.compile("_fluid_pipe"), "_pipe"))); + } + + private static UnaryOperator createRenamer(String pOldName, String pNewName) { + return id -> Objects.equals(NamespacedSchema.ensureNamespaced(id), pOldName) ? pNewName : id; + } + + private static UnaryOperator createRenamer(Map pRenameMap) { + return id -> pRenameMap.getOrDefault(NamespacedSchema.ensureNamespaced(id), id); + } + + private static UnaryOperator createRenamer(Pattern check, String replaceWith) { + return id -> check.matcher(NamespacedSchema.ensureNamespaced(id)).replaceAll(replaceWith); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTReferences.java b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTReferences.java new file mode 100644 index 0000000000..0255fe5f9e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTReferences.java @@ -0,0 +1,25 @@ +package com.gregtechceu.gtceu.common.data.datafixer; + +import com.mojang.datafixers.DSL; + +public class GTReferences { + + public static final DSL.TypeReference MATERIAL_NAME = reference("material_name"); + public static final DSL.TypeReference COVER_NAME = reference("cover_name"); + public static final DSL.TypeReference COVER = reference("cover"); + + public static DSL.TypeReference reference(final String pName) { + return new DSL.TypeReference() { + + @Override + public String typeName() { + return pName; + } + + @Override + public String toString() { + return "@" + pName; + } + }; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java index 93621acf58..eb15074b3e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java @@ -620,7 +620,7 @@ public static void register() { .itemPipeProperties(512, 4.0f) .buildAndRegister(); - Plutonium239 = new Material.Builder(GTCEu.id("plutonium")) + Plutonium239 = new Material.Builder(GTCEu.id("plutonium_239")) .ingot(3) .liquid(new FluidBuilder().temperature(913)) .ore(true) @@ -870,7 +870,7 @@ public static void register() { .blastTemp(3600, GasTier.MID, GTValues.VA[GTValues.EV], 1800) .buildAndRegister(); - Uranium238 = new Material.Builder(GTCEu.id("uranium")) + Uranium238 = new Material.Builder(GTCEu.id("uranium_238")) .ingot(3) .liquid(new FluidBuilder().temperature(1405)) .color(0x1d891d).secondaryColor(0x33342c).iconSet(RADIOACTIVE) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java index 8565875ea6..aebdcd0b7d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java @@ -195,7 +195,7 @@ public static void register() { .components(SiliconDioxide, 4, Biotite, 1) .buildAndRegister(); - GraniteRed = new Material.Builder(GTCEu.id("granite_red")) + RedGranite = new Material.Builder(GTCEu.id("red_granite")) .dust() .color(0xFF0080).iconSet(ROUGH) .flags(NO_SMASHING) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/UnknownCompositionMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/UnknownCompositionMaterials.java index 7b17c82f3d..92c7663184 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/UnknownCompositionMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/UnknownCompositionMaterials.java @@ -277,19 +277,19 @@ public static void register() { .flags(STICKY, FLAMMABLE) .buildAndRegister(); - OilHeavy = new Material.Builder(GTCEu.id("oil_heavy")) + HeavyOil = new Material.Builder(GTCEu.id("heavy_oil")) .liquid(new FluidBuilder().block().customStill()) .color(0x0A0A0A) .flags(STICKY, FLAMMABLE) .buildAndRegister(); - RawOil = new Material.Builder(GTCEu.id("oil_medium")) + RawOil = new Material.Builder(GTCEu.id("raw_oil")) .liquid(new FluidBuilder().block().customStill()) .color(0x0A0A0A) .flags(STICKY, FLAMMABLE) .buildAndRegister(); - OilLight = new Material.Builder(GTCEu.id("oil_light")) + LightOil = new Material.Builder(GTCEu.id("light_oil")) .liquid(new FluidBuilder().block().customStill()) .color(0x0A0A0A) .flags(STICKY, FLAMMABLE) diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java new file mode 100644 index 0000000000..b4efc7f665 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java @@ -0,0 +1,20 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class OilVariantsRenameFix { + + public static final Map RENAMED_ITEM_IDS = ImmutableMap.builder() + .put("gtceu:oil_heavy_bucket", "gtceu:heavy_oil_bucket") + .put("gtceu:oil_light_bucket", "gtceu:light_oil_bucket") + .put("gtceu:oil_medium_bucket", "gtceu:raw_oil_bucket") + .build(); + + public static final Map RENAMED_BLOCK_IDS = ImmutableMap.builder() + .put("gtceu:oil_heavy", "gtceu:heavy_oil") + .put("gtceu:oil_light", "gtceu:light_oil") + .put("gtceu:oil_medium", "gtceu:raw_oil") + .build(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/BaseGTSchema.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/BaseGTSchema.java new file mode 100644 index 0000000000..9d2c2222c9 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/BaseGTSchema.java @@ -0,0 +1,36 @@ +package com.gregtechceu.gtceu.common.datafixer.schemas; + +import com.gregtechceu.gtceu.common.data.datafixer.GTReferences; + +import net.minecraft.util.datafix.schemas.NamespacedSchema; + +import com.google.common.collect.Maps; +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.templates.TypeTemplate; + +import java.util.Map; +import java.util.function.Supplier; + +public class BaseGTSchema extends NamespacedSchema { + + public BaseGTSchema(int versionKey, Schema parent) { + super(versionKey, parent); + } + + @Override + public void registerTypes(Schema schema, Map> entityTypes, + Map> blockEntityTypes) { + super.registerTypes(schema, entityTypes, blockEntityTypes); + schema.registerType(false, GTReferences.MATERIAL_NAME, () -> DSL.constType(namespacedString())); + schema.registerType(false, GTReferences.COVER_NAME, () -> DSL.constType(namespacedString())); + + Map> coverTypes = registerCoverDefinitions(schema); + schema.registerType(true, GTReferences.COVER, + () -> DSL.taggedChoiceLazy("id", namespacedString(), coverTypes)); + } + + public Map> registerCoverDefinitions(final Schema schema) { + return Maps.newHashMap(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java new file mode 100644 index 0000000000..3a67e1217b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java @@ -0,0 +1,254 @@ +package com.gregtechceu.gtceu.common.datafixer.schemas; + +import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.api.machine.MachineDefinition; +import com.gregtechceu.gtceu.api.registry.GTRegistries; +import com.gregtechceu.gtceu.common.data.GTCovers; +import com.gregtechceu.gtceu.common.data.datafixer.GTReferences; + +import net.minecraft.util.datafix.fixes.References; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.templates.TypeTemplate; + +import java.util.Map; +import java.util.function.Supplier; + +@SuppressWarnings("Convert2MethodRef") +public class V0 extends BaseGTSchema { + + public V0(int versionKey, Schema parent) { + super(versionKey, parent); + } + + @Override + public void registerTypes(Schema schema, Map> entityTypes, + Map> blockEntityTypes) { + super.registerTypes(schema, entityTypes, blockEntityTypes); + } + + // Register schemas for all covers. + public Map> registerCoverDefinitions(final Schema schema) { + Map> map = super.registerCoverDefinitions(schema); + + schema.register(map, "gtceu:facade", () -> DSL.field("facadeState", References.BLOCK_STATE.in(schema))); + schema.register(map, "gtceu:item_filter", () -> DSL.field("filterMode", DSL.remainder())); + schema.register(map, "gtceu:fluid_filter", () -> DSL.remainder()); + schema.register(map, "gtceu:infinite_water", () -> DSL.remainder()); + schema.register(map, "gtceu:shutter", () -> DSL.field("workingEnabled", DSL.bool().template())); + schema.register(map, "gtceu:machine_controller", () -> DSL.fields( + "isInverted", DSL.bool().template(), + "minRedstoneStrength", DSL.intType().template(), + "controllerMode", DSL.string().template())); + for (CoverDefinition cover : GTCovers.CONVEYORS) { + schema.register(map, cover.getId().toString(), () -> DSL.and( + DSL.fields( + "transferRate", DSL.intType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))))); + } + for (CoverDefinition cover : GTCovers.ROBOT_ARMS) { + schema.register(map, cover.getId().toString(), () -> DSL.and( + DSL.fields( + "transferRate", DSL.intType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "transferMode", DSL.string().template()), + DSL.fields( + "globalTransferLimit", DSL.intType().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))))); + } + for (CoverDefinition cover : GTCovers.PUMPS) { + schema.register(map, cover.getId().toString(), () -> DSL.and( + DSL.fields( + "currentMilliBucketsPerTick", DSL.longType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "bucketMode", DSL.string().template()), + DSL.fields( + "globalTransferLimit", DSL.intType().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))))); + } + for (CoverDefinition cover : GTCovers.FLUID_REGULATORS) { + schema.register(map, cover.getId().toString(), () -> DSL.and( + DSL.fields( + "currentMilliBucketsPerTick", DSL.longType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "bucketMode", DSL.string().template()), + DSL.fields("globalTransferLimit", DSL.intType().template(), + "transferMode", DSL.string().template(), + "globalTransferSizeMillibuckets", DSL.longType().template()), + DSL.fields( + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))))); + } + schema.register(map, "gtceu:item_voiding", () -> DSL.and( + DSL.fields( + "transferRate", DSL.intType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))), + DSL.fields("isEnabled", DSL.bool().template()))); + schema.register(map, "gtceu:item_voiding_advanced", () -> DSL.and( + DSL.fields( + "transferRate", DSL.intType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))), + DSL.fields( + "isEnabled", DSL.bool().template(), + "voidingMode", DSL.string().template(), + "globalVoidingLimit", DSL.intType().template()))); + schema.register(map, "gtceu:fluid_voiding", () -> DSL.and( + DSL.fields( + "currentMilliBucketsPerTick", DSL.longType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "bucketMode", DSL.string().template()), + DSL.fields( + "globalTransferLimit", DSL.intType().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))), + DSL.fields("isEnabled", DSL.bool().template()))); + schema.register(map, "gtceu:fluid_voiding_advanced", () -> DSL.and( + DSL.fields( + "currentMilliBucketsPerTick", DSL.longType().template(), + "distributionMode", DSL.string().template(), + "io", DSL.string().template()), + DSL.fields( + "manualIOMode", DSL.string().template(), + "isWorkingEnabled", DSL.bool().template(), + "bucketMode", DSL.string().template()), + DSL.fields( + "globalTransferLimit", DSL.intType().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))), + DSL.fields( + "isEnabled", DSL.bool().template(), + "voidingMode", DSL.string().template(), + "globalVoidingLimit", DSL.intType().template()))); + schema.register(map, "gtceu:activity_detector", () -> DSL.fields( + "isWorkingEnabled", DSL.bool().template(), + "isInverted", DSL.bool().template())); + schema.register(map, "gtceu:activity_detector_advanced", () -> DSL.fields( + "isWorkingEnabled", DSL.bool().template(), + "isInverted", DSL.bool().template())); + schema.register(map, "gtceu:fluid_detector", () -> DSL.fields( + "isWorkingEnabled", DSL.bool().template(), + "isInverted", DSL.bool().template())); + schema.register(map, "gtceu:fluid_detector_advanced", () -> DSL.and( + DSL.fields( + "isWorkingEnabled", DSL.bool().template(), + "isInverted", DSL.bool().template(), + "minValue", DSL.longType().template()), + DSL.fields( + "maxValue", DSL.longType().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))))); + schema.register(map, "gtceu:item_detector", () -> DSL.fields( + "isWorkingEnabled", DSL.bool().template(), + "isInverted", DSL.bool().template())); + schema.register(map, "gtceu:item_detector_advanced", () -> DSL.and( + DSL.fields( + "isWorkingEnabled", DSL.bool().template(), + "isInverted", DSL.bool().template(), + "minValue", DSL.intType().template()), + DSL.fields( + "maxValue", DSL.intType().template(), + "filterHandler", DSL.field( + "filterItem", References.ITEM_STACK.in(schema))))); + schema.register(map, "gtceu:energy_detector", () -> DSL.remainder()); + schema.register(map, "gtceu:energy_detector_advanced", () -> DSL.and( + DSL.fields( + "isWorkingEnabled", DSL.bool().template(), + "isInverted", DSL.bool().template(), + "minValue", DSL.longType().template()), + DSL.fields( + "maxValue", DSL.longType().template(), + "outputAmount", DSL.intType().template(), + "usePercent", DSL.bool().template()))); + schema.register(map, "gtceu:maintenance_detector", () -> DSL.remainder()); + for (CoverDefinition cover : GTCovers.SOLAR_PANEL) { + schema.register(map, cover.getId().toString(), () -> DSL.remainder()); + } + return map; + } + + @Override + public Map> registerBlockEntities(Schema schema) { + Map> map = super.registerBlockEntities(schema); + for (MachineDefinition definition : GTRegistries.MACHINES) { + registerInventory(schema, map, definition.getId().toString()); + } + return map; + } + + protected static void registerInventory(Schema schema, Map> map, String name) { + TypeTemplate cover = DSL.fields( + "side", DSL.intType().template(), + GTReferences.COVER.in(schema)); + TypeTemplate covers = DSL.and( + DSL.fields( + "up", cover, + "down", cover, + "north", cover), + DSL.fields( + "south", cover, + "west", cover, + "east", cover)); + + schema.register(map, name, () -> DSL.or( + DSL.fields( + "importItems", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema)))), + "exportItems", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema)))), + DSL.field("cover", covers)), + DSL.or( + DSL.fields( + "inventory", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema))))), + DSL.or( + DSL.fields( + "cache", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema))))), + DSL.remainder())))); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java new file mode 100644 index 0000000000..ea66df179b --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java @@ -0,0 +1,44 @@ +package com.gregtechceu.gtceu.common.datafixer.schemas; + +import com.gregtechceu.gtceu.common.data.datafixer.GTReferences; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.templates.TypeTemplate; + +import java.util.Map; +import java.util.function.Supplier; + +public class V2 extends BaseGTSchema { + + public V2(int versionKey, Schema parent) { + super(versionKey, parent); + } + + @Override + public Map> registerBlockEntities(Schema schema) { + Map> map = super.registerBlockEntities(schema); + TypeTemplate covers = DSL.field("Covers", DSL.list( + DSL.fields( + "side", DSL.byteType().template(), + GTReferences.COVER.in(schema)))); + final TypeTemplate pipe = DSL.and( + DSL.fields( + "connectionMask", DSL.byteType().template(), + "renderMask", DSL.byteType().template(), + "coverHolder", covers), + DSL.fields( + "blockedMask", DSL.byteType().template(), + "paintingColor", DSL.intType().template(), + "frameMaterial", GTReferences.MATERIAL_NAME.in(schema))); + + schema.register(map, "gtceu:pipe", () -> pipe); + schema.register(map, + "gtceu:activable_pipe", + () -> DSL.fields( + "active", DSL.bool().template(), + pipe)); + schema.register(map, "gtceu:material_pipe", () -> pipe); + return map; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java index d5f2538c62..68a13c93b6 100644 --- a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java @@ -133,6 +133,12 @@ public static class RecipeConfigs { public static class CompatibilityConfigs { + @Configurable + @Configurable.Comment({ "Whether to run datafixers on world load.", + "Do note that mods like ModernFix will interfere with this.", + "Default: true" }) + public boolean doDatafixers = true; + @Configurable @Configurable.Comment("Config options regarding GTEU compatibility with other energy systems") public EnergyCompatConfig energy = new EnergyCompatConfig(); diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java index 80ecd8337d..0d8b28ea3a 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java @@ -483,9 +483,9 @@ public static void init(RegistrateLangProvider provider) { replace(provider, GTMaterials.TungstenSteel.getUnlocalizedName(), "Tungstensteel"); replace(provider, GTMaterials.Iron3Chloride.getUnlocalizedName(), "Iron III Chloride"); replace(provider, GTMaterials.Iron2Chloride.getUnlocalizedName(), "Iron II Chloride"); - replace(provider, GTMaterials.OilHeavy.getUnlocalizedName(), "Heavy Oil"); + replace(provider, GTMaterials.HeavyOil.getUnlocalizedName(), "Heavy Oil"); replace(provider, "block.gtceu.oil_heavy", "Heavy Oil"); - replace(provider, GTMaterials.OilLight.getUnlocalizedName(), "Light Oil"); + replace(provider, GTMaterials.LightOil.getUnlocalizedName(), "Light Oil"); replace(provider, "block.gtceu.oil_light", "Light Oil"); replace(provider, GTMaterials.RawOil.getUnlocalizedName(), "Raw Oil"); replace(provider, "block.gtceu.oil_medium", "Raw Oil"); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/FuelRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/FuelRecipes.java index 6f120c7a9d..96bf552302 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/FuelRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/FuelRecipes.java @@ -72,7 +72,7 @@ public static void init(Consumer provider) { .save(provider); LARGE_BOILER_RECIPES.recipeBuilder("oil_heavy") - .inputFluids(OilHeavy.getFluid(32)) + .inputFluids(HeavyOil.getFluid(32)) .duration(10) .save(provider); @@ -171,7 +171,7 @@ public static void init(Consumer provider) { .save(provider); COMBUSTION_GENERATOR_FUELS.recipeBuilder("light_oil") - .inputFluids(OilLight.getFluid(32)) + .inputFluids(LightOil.getFluid(32)) .duration(5) .EUt(-V[LV]) .save(provider); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java index 557f4c9937..e48abca6c1 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MachineRecipeLoader.java @@ -1158,8 +1158,8 @@ private static void registerRecyclingRecipes(Consumer provider) .save(provider); MACERATOR_RECIPES.recipeBuilder("macerate_red_granite") - .inputItems(rock, GraniteRed) - .outputItems(dust, GraniteRed) + .inputItems(rock, RedGranite) + .outputItems(dust, RedGranite) .chancedOutput(dust, Uranium238, 10, 5) .duration(150).EUt(2) .save(provider); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MiscRecipeLoader.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MiscRecipeLoader.java index c774185737..56ee0b7ba4 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MiscRecipeLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/MiscRecipeLoader.java @@ -178,8 +178,8 @@ public static void init(Consumer provider) { .save(provider); ROCK_BREAKER_RECIPES.recipeBuilder("red_granite") - .notConsumable(rock, GraniteRed) - .outputItems(rock, GraniteRed) + .notConsumable(rock, RedGranite) + .outputItems(rock, RedGranite) .duration(16) .EUt(VHA[EV]) .addData("fluidA", "minecraft:lava") diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/WoodMachineRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/WoodMachineRecipes.java index 44ef34d4be..597afb5545 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/WoodMachineRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/WoodMachineRecipes.java @@ -929,7 +929,7 @@ private static void registerPyrolyseOvenRecipes(Consumer provide PYROLYSE_RECIPES.recipeBuilder("log_to_heavy_oil").circuitMeta(3) .inputItems(ItemTags.LOGS_THAT_BURN, 16) .outputItems(dust, Ash, 4) - .outputFluids(OilHeavy.getFluid(200)) + .outputFluids(HeavyOil.getFluid(200)) .duration(320).EUt(192) .save(provider); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/PetrochemRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/PetrochemRecipes.java index 6999945921..2c2fa0853d 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/PetrochemRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/PetrochemRecipes.java @@ -40,7 +40,7 @@ public static void init(Consumer provider) { .duration(20).EUt(96).save(provider); DISTILLATION_RECIPES.recipeBuilder("distill_light_oil") - .inputFluids(OilLight.getFluid(150)) + .inputFluids(LightOil.getFluid(150)) .outputFluids(SulfuricHeavyFuel.getFluid(10)) .outputFluids(SulfuricLightFuel.getFluid(20)) .outputFluids(SulfuricNaphtha.getFluid(30)) @@ -48,7 +48,7 @@ public static void init(Consumer provider) { .duration(20).EUt(96).save(provider); DISTILLATION_RECIPES.recipeBuilder("distill_heavy_oil") - .inputFluids(OilHeavy.getFluid(100)) + .inputFluids(HeavyOil.getFluid(100)) .outputFluids(SulfuricHeavyFuel.getFluid(250)) .outputFluids(SulfuricLightFuel.getFluid(45)) .outputFluids(SulfuricNaphtha.getFluid(15)) diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/SeparationRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/SeparationRecipes.java index d9a22a273d..4ae00ecf1c 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/SeparationRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/serialized/chemistry/SeparationRecipes.java @@ -56,7 +56,7 @@ public static void init(Consumer provider) { CENTRIFUGE_RECIPES.recipeBuilder("oilsands_dust_separation") .inputItems(dust, Oilsands) .chancedOutput(new ItemStack(Blocks.SAND), 5000, 5000) - .outputFluids(OilHeavy.getFluid(2000)) + .outputFluids(HeavyOil.getFluid(2000)) .duration(200).EUt(30).save(provider); CENTRIFUGE_RECIPES.recipeBuilder("nether_wart_separation").duration(144).EUt(5) diff --git a/src/main/java/com/gregtechceu/gtceu/data/tags/BlockTagLoader.java b/src/main/java/com/gregtechceu/gtceu/data/tags/BlockTagLoader.java index f9726f9cca..c8c931d8d0 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/tags/BlockTagLoader.java +++ b/src/main/java/com/gregtechceu/gtceu/data/tags/BlockTagLoader.java @@ -33,8 +33,8 @@ public static void init(RegistrateTagsProvider provider) { create(provider, BlockTags.REPLACEABLE, GTMaterials.Oil.getFluid().defaultFluidState().createLegacyBlock().getBlock(), - GTMaterials.OilLight.getFluid().defaultFluidState().createLegacyBlock().getBlock(), - GTMaterials.OilHeavy.getFluid().defaultFluidState().createLegacyBlock().getBlock(), + GTMaterials.LightOil.getFluid().defaultFluidState().createLegacyBlock().getBlock(), + GTMaterials.HeavyOil.getFluid().defaultFluidState().createLegacyBlock().getBlock(), GTMaterials.RawOil.getFluid().defaultFluidState().createLegacyBlock().getBlock(), GTMaterials.NaturalGas.getFluid().defaultFluidState().createLegacyBlock().getBlock()); } From 8b43e3e34b33cdc885f4c296d4bf882865cc24e9 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 20:33:23 +0300 Subject: [PATCH 31/70] :weary: --- .../renderer/pipe/PipeModelRegistry.java | 2 +- .../common/data/datafixer/GTDataFixers.java | 29 +++++++--- .../fixes/ActivablePipeConnectionFix.java | 16 ++++++ .../datafixer/fixes/PipeConnectionFix.java | 24 +++++++++ .../gtceu/common/datafixer/schemas/V0.java | 53 +++++++++++++++---- .../gtceu/common/datafixer/schemas/V2.java | 12 ++--- .../net/optical/DataCapabilityObject.java | 2 +- 7 files changed, 115 insertions(+), 23 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/ActivablePipeConnectionFix.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java index 7669fc670e..68f1dd5e44 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -239,7 +239,7 @@ private static void initCables() { return new CableModel(material); } return new CableModel(material, CableModel.INSULATION[insulation - 1], CableModel.INSULATION_FULL); - }, Objects::nonNull)); + }, m -> true)); ResourceLocation loc = GTCEu.id("block/cable"); for (int i = 0; i < CABLE_MODEL_COUNT; i++) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java index 2687e21e45..c82e1207d7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java @@ -3,15 +3,14 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTCEuAPI; import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; +import com.gregtechceu.gtceu.common.datafixer.fixes.ActivablePipeConnectionFix; +import com.gregtechceu.gtceu.common.datafixer.fixes.PipeConnectionFix; import com.gregtechceu.gtceu.common.datafixer.fixes.OilVariantsRenameFix; import com.gregtechceu.gtceu.common.datafixer.schemas.V2; import com.gregtechceu.gtceu.config.ConfigHolder; import net.minecraft.util.datafix.DataFixTypes; -import net.minecraft.util.datafix.fixes.AddNewChoices; -import net.minecraft.util.datafix.fixes.BlockRenameFix; -import net.minecraft.util.datafix.fixes.ItemRenameFix; -import net.minecraft.util.datafix.fixes.References; +import net.minecraft.util.datafix.fixes.*; import net.minecraft.util.datafix.schemas.NamespacedSchema; import com.google.common.util.concurrent.ThreadFactoryBuilder; @@ -73,12 +72,30 @@ public static void addFixers(DataFixerBuilder builder) { Schema schemaV2 = builder.addSchema(2, V2::new); builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe block entities", References.BLOCK_ENTITY)); - builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe blocks", References.BLOCK_NAME)); - builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe items", References.ITEM_NAME)); builder.addFixer(ItemRenameFix.create(schemaV2, "Item pipe rename fix", createRenamer(Pattern.compile("_item_pipe"), "_pipe"))); builder.addFixer(ItemRenameFix.create(schemaV2, "Fluid pipe rename fix", createRenamer(Pattern.compile("_fluid_pipe"), "_pipe"))); + builder.addFixer(BlockRenameFix.create(schemaV2, "Item pipe rename fix", + createRenamer(Pattern.compile("_item_pipe"), "_pipe"))); + builder.addFixer(BlockRenameFix.create(schemaV2, "Fluid pipe rename fix", + createRenamer(Pattern.compile("_fluid_pipe"), "_pipe"))); + builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:cable")); + builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:fluid_pipe")); + builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:item_pipe")); + builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:item_pipe")); + builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:duct_pipe")); + builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:laser_pipe")); + builder.addFixer(new ActivablePipeConnectionFix(schemaV2, false, "gtceu:optical_pipe")); + builder.addFixer(BlockEntityRenameFix.create(schemaV2, "Pipe block entity rename fix", + createRenamer(Map.of( + "gtceu:cable", "gtceu:material_pipe", + "gtceu:fluid_pipe", "gtceu:material_pipe", + "gtceu:item_pipe", "gtceu:material_pipe", + "gtceu:laser_pipe", "gtceu:activable_pipe", + "gtceu:optical_pipe", "gtceu:activable_pipe", + "gtceu:duct_pipe", "gtceu:pipe" + )))); } private static UnaryOperator createRenamer(String pOldName, String pNewName) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/ActivablePipeConnectionFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/ActivablePipeConnectionFix.java new file mode 100644 index 0000000000..480a9119a4 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/ActivablePipeConnectionFix.java @@ -0,0 +1,16 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; + +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; + +public class ActivablePipeConnectionFix extends PipeConnectionFix { + + public ActivablePipeConnectionFix(Schema outputSchema, boolean changesType, String type) { + super(outputSchema, changesType, type); + } + + public Dynamic fixTag(Dynamic tag) { + tag = super.fixTag(tag); + return tag.set("active", tag.get("isActive").result().get()); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java new file mode 100644 index 0000000000..68d2d19550 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java @@ -0,0 +1,24 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.Typed; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import net.minecraft.util.datafix.fixes.NamedEntityFix; +import net.minecraft.util.datafix.fixes.References; + +public class PipeConnectionFix extends NamedEntityFix { + public PipeConnectionFix(Schema outputSchema, boolean changesType, String type) { + super(outputSchema, changesType, "PipeConnectionFix", References.BLOCK_ENTITY, type); + } + + public Dynamic fixTag(Dynamic tag) { + tag = tag.set("connectionMask", tag.get("connections").result().get()); + return tag.set("blockedMask", tag.get("blockedConnections").result().get()); + } + + @Override + protected Typed fix(Typed typed) { + return typed.update(DSL.remainderFinder(), this::fixTag); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java index 3a67e1217b..833358c3d7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java @@ -209,22 +209,57 @@ public Map> registerBlockEntities(Schema schema) for (MachineDefinition definition : GTRegistries.MACHINES) { registerInventory(schema, map, definition.getId().toString()); } + Supplier cover = () -> DSL.fields( + "side", DSL.intType().template(), + GTReferences.COVER.in(schema)); + Supplier covers = () -> DSL.and( + DSL.fields( + "up", cover.get(), + "down", cover.get(), + "north", cover.get()), + DSL.fields( + "south", cover.get(), + "west", cover.get(), + "east", cover.get())); + final Supplier pipe = () -> DSL.and( + DSL.fields( + "connections", DSL.intType().template(), + "blockedConnections", DSL.intType().template(), + "cover", covers.get() + ), + DSL.fields( + "paintingColor", DSL.intType().template(), + "frameMaterial", GTReferences.MATERIAL_NAME.in(schema) + )); + + schema.register(map, "gtceu:cable", () -> DSL.fields( + "temperature", DSL.intType().template(), + pipe.get())); + schema.register(map, "gtceu:fluid_pipe", pipe); + schema.register(map, "gtceu:item_pipe", pipe); + schema.register(map, "gtceu:laser_pipe", () -> DSL.fields( + "active", DSL.bool().template(), + pipe.get())); + schema.register(map, "gtceu:optical_pipe", () -> DSL.fields( + "isActive", DSL.bool().template(), + pipe.get())); + schema.register(map, "gtceu:duct_pipe", pipe); return map; } protected static void registerInventory(Schema schema, Map> map, String name) { - TypeTemplate cover = DSL.fields( + Supplier cover = () -> DSL.fields( "side", DSL.intType().template(), GTReferences.COVER.in(schema)); - TypeTemplate covers = DSL.and( + Supplier covers = () -> DSL.and( DSL.fields( - "up", cover, - "down", cover, - "north", cover), + "up", cover.get(), + "down", cover.get(), + "north", cover.get()), DSL.fields( - "south", cover, - "west", cover, - "east", cover)); + "south", cover.get(), + "west", cover.get(), + "east", cover.get())); schema.register(map, name, () -> DSL.or( DSL.fields( @@ -236,7 +271,7 @@ protected static void registerInventory(Schema schema, Map> registerBlockEntities(Schema schema) { Map> map = super.registerBlockEntities(schema); - TypeTemplate covers = DSL.field("Covers", DSL.list( + final Supplier covers = () -> DSL.field("covers", DSL.list( DSL.fields( "side", DSL.byteType().template(), GTReferences.COVER.in(schema)))); - final TypeTemplate pipe = DSL.and( + final Supplier pipe = () -> DSL.and( DSL.fields( "connectionMask", DSL.byteType().template(), "renderMask", DSL.byteType().template(), - "coverHolder", covers), + "coverHolder", covers.get()), DSL.fields( "blockedMask", DSL.byteType().template(), "paintingColor", DSL.intType().template(), "frameMaterial", GTReferences.MATERIAL_NAME.in(schema))); - schema.register(map, "gtceu:pipe", () -> pipe); + schema.register(map, "gtceu:pipe", pipe); schema.register(map, "gtceu:activable_pipe", () -> DSL.fields( "active", DSL.bool().template(), - pipe)); - schema.register(map, "gtceu:material_pipe", () -> pipe); + pipe.get())); + schema.register(map, "gtceu:material_pipe", pipe); return map; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java index 5fa9ebf7e1..fd23122db7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java @@ -64,7 +64,7 @@ public boolean accessData(@NotNull DataQueryObject queryObject) { .get(destination.getBlockEntity().getCoverHolder() .getCoverAtSide(capability.getKey())) .queryHandler(queryObject, access); - if (queryObject.shouldTriggerWalker()) { + if (queryObject.isShouldTriggerWalker()) { SlowActiveWalker.dispatch(tile.getLevel(), path, 1); } if (cancelled) return true; From 1805167807a7f712b62345f97c98672aa226fb0b Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 5 Sep 2024 23:21:15 +0300 Subject: [PATCH 32/70] work pls --- .../api/graphnet/logic/NetLogicEntryType.java | 4 +- .../physical/tile/PipeBlockEntity.java | 2 +- .../client/renderer/pipe/quad/QuadHelper.java | 2 +- .../pipe/quad/RecolorableBakedQuad.java | 5 +- .../gtceu/client/util/StaticFaceBakery.java | 1 + .../common/data/datafixer/GTDataFixers.java | 22 +++++---- .../datafixer/fixes/OilVariantsRenameFix.java | 3 ++ .../gtceu/common/datafixer/schemas/V0.java | 46 +++++++++---------- .../gtceu/common/datafixer/schemas/V2.java | 9 ++-- .../gtceu/config/ConfigHolder.java | 2 +- .../gtceu/forge/ForgeCommonEventListener.java | 4 ++ 11 files changed, 57 insertions(+), 43 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java index f34e0b27bb..9b6ba0091c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java @@ -7,7 +7,9 @@ public record NetLogicEntryType>(String id, Supplier supplier) implements StringRepresentable { - public NetLogicEntryType { + public NetLogicEntryType(String id, Supplier supplier) { + this.id = id; + this.supplier = supplier; NetLogicRegistry.register(this); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index d71223aff1..f0b72079c2 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -576,7 +576,7 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { this.netLogicDatas.computeIfPresent(networkID, (k, v) -> v.removeLogicEntry(logic)); } else { if (fullChange) { - NetLogicEntry logic = NetLogicRegistry.getTypeErroring(identifier).supplier().get(); + NetLogicEntry logic = NetLogicRegistry.getTypeErroring(identifier).getNew(); logic.decode(buf, true); this.netLogicDatas.compute(networkID, (k, v) -> { if (v == null) v = new NetLogicData(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java index f65a626311..638a1b86cd 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -40,7 +40,7 @@ private QuadHelper() {} uv.map(normal, box)); return StaticFaceBakery.bakeQuad(box.getLeft(), box.getRight(), face, targetSprite, normal, BlockModelRotation.X0_Y0, - null, false, 15); + null, true, 0); } @Contract("_ -> new") diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java index 44b8ac8580..3f7b5faf55 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java @@ -10,6 +10,8 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import java.util.Arrays; + import static net.minecraftforge.client.model.IQuadTransformer.*; @MethodsReturnNonnullByDefault @@ -32,7 +34,8 @@ public RecolorableBakedQuad(BakedQuad prototype, SpriteInformation spriteInforma protected RecolorableBakedQuad(BakedQuad prototype, int tintIndex, SpriteInformation spriteInformation, Int2ObjectOpenHashMap cache) { - super(prototype.getVertices(), tintIndex, prototype.getDirection(), spriteInformation.sprite(), + super(Arrays.copyOf(prototype.getVertices(), prototype.getVertices().length), tintIndex, + prototype.getDirection(), spriteInformation.sprite(), prototype.isShade(), prototype.hasAmbientOcclusion()); this.spriteInformation = spriteInformation; this.cache = cache; diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java index cefb19d20d..4b5000f779 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.client.util; import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.lowdragmc.lowdraglib.client.bakedpipeline.FaceQuad; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java index c82e1207d7..4a4760c533 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java @@ -71,21 +71,25 @@ public static void addFixers(DataFixerBuilder builder) { createRenamer(OilVariantsRenameFix.RENAMED_BLOCK_IDS))); Schema schemaV2 = builder.addSchema(2, V2::new); - builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe block entities", References.BLOCK_ENTITY)); - builder.addFixer(ItemRenameFix.create(schemaV2, "Item pipe rename fix", - createRenamer(Pattern.compile("_item_pipe"), "_pipe"))); - builder.addFixer(ItemRenameFix.create(schemaV2, "Fluid pipe rename fix", - createRenamer(Pattern.compile("_fluid_pipe"), "_pipe"))); - builder.addFixer(BlockRenameFix.create(schemaV2, "Item pipe rename fix", - createRenamer(Pattern.compile("_item_pipe"), "_pipe"))); - builder.addFixer(BlockRenameFix.create(schemaV2, "Fluid pipe rename fix", - createRenamer(Pattern.compile("_fluid_pipe"), "_pipe"))); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:cable")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:fluid_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:item_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:item_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:duct_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:laser_pipe")); + builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe block entities", References.BLOCK_ENTITY)); + builder.addFixer(ItemRenameFix.create(schemaV2, "Item pipe rename fix", + createRenamer(Pattern.compile("(.+?)_(.+?)_item_pipe"), "$2_$1_pipe"))); + builder.addFixer(ItemRenameFix.create(schemaV2, "Fluid pipe rename fix", + createRenamer(Pattern.compile("(.+?)_(.+?)_fluid_pipe"), "$2_$1_pipe"))); + builder.addFixer(BlockRenameFix.create(schemaV2, "Item pipe rename fix", + createRenamer(Pattern.compile("(.+?)_(.+?)_item_pipe"), "$2_$1_pipe"))); + builder.addFixer(BlockRenameFix.create(schemaV2, "Fluid pipe rename fix", + createRenamer(Pattern.compile("(.+?)_(.+?)_fluid_pipe"), "$2_$1_pipe"))); + builder.addFixer(BlockRenameFix.create(schemaV2, "Optical cable rename fix", + createRenamer("gtceu:normal_optical_pipe", "gtceu:optical_fiber_cable"))); + builder.addFixer(BlockRenameFix.create(schemaV2, "Laser cable rename fix", + createRenamer("gtceu:normal_laser_pipe", "gtceu:laser_pipe"))); builder.addFixer(new ActivablePipeConnectionFix(schemaV2, false, "gtceu:optical_pipe")); builder.addFixer(BlockEntityRenameFix.create(schemaV2, "Pipe block entity rename fix", createRenamer(Map.of( diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java index b4efc7f665..88251ea955 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java @@ -14,7 +14,10 @@ public class OilVariantsRenameFix { public static final Map RENAMED_BLOCK_IDS = ImmutableMap.builder() .put("gtceu:oil_heavy", "gtceu:heavy_oil") + .put("gtceu:flowing_oil_heavy", "gtceu:flowing_heavy_oil") .put("gtceu:oil_light", "gtceu:light_oil") + .put("gtceu:flowing_oil_light", "gtceu:flowing_light_oil") .put("gtceu:oil_medium", "gtceu:raw_oil") + .put("gtceu:flowing_oil_medium", "gtceu:flowing_raw_oil") .build(); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java index 833358c3d7..4e6729a6ec 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java @@ -42,7 +42,7 @@ public Map> registerCoverDefinitions(final Schema "minRedstoneStrength", DSL.intType().template(), "controllerMode", DSL.string().template())); for (CoverDefinition cover : GTCovers.CONVEYORS) { - schema.register(map, cover.getId().toString(), () -> DSL.and( + schema.register(map, cover.getId().toString(), () -> DSL.allWithRemainder( DSL.fields( "transferRate", DSL.intType().template(), "distributionMode", DSL.string().template(), @@ -54,7 +54,7 @@ public Map> registerCoverDefinitions(final Schema "filterItem", References.ITEM_STACK.in(schema))))); } for (CoverDefinition cover : GTCovers.ROBOT_ARMS) { - schema.register(map, cover.getId().toString(), () -> DSL.and( + schema.register(map, cover.getId().toString(), () -> DSL.allWithRemainder( DSL.fields( "transferRate", DSL.intType().template(), "distributionMode", DSL.string().template(), @@ -69,7 +69,7 @@ public Map> registerCoverDefinitions(final Schema "filterItem", References.ITEM_STACK.in(schema))))); } for (CoverDefinition cover : GTCovers.PUMPS) { - schema.register(map, cover.getId().toString(), () -> DSL.and( + schema.register(map, cover.getId().toString(), () -> DSL.allWithRemainder( DSL.fields( "currentMilliBucketsPerTick", DSL.longType().template(), "distributionMode", DSL.string().template(), @@ -84,7 +84,7 @@ public Map> registerCoverDefinitions(final Schema "filterItem", References.ITEM_STACK.in(schema))))); } for (CoverDefinition cover : GTCovers.FLUID_REGULATORS) { - schema.register(map, cover.getId().toString(), () -> DSL.and( + schema.register(map, cover.getId().toString(), () -> DSL.allWithRemainder( DSL.fields( "currentMilliBucketsPerTick", DSL.longType().template(), "distributionMode", DSL.string().template(), @@ -100,7 +100,7 @@ public Map> registerCoverDefinitions(final Schema "filterHandler", DSL.field( "filterItem", References.ITEM_STACK.in(schema))))); } - schema.register(map, "gtceu:item_voiding", () -> DSL.and( + schema.register(map, "gtceu:item_voiding", () -> DSL.allWithRemainder( DSL.fields( "transferRate", DSL.intType().template(), "distributionMode", DSL.string().template(), @@ -111,7 +111,7 @@ public Map> registerCoverDefinitions(final Schema "filterHandler", DSL.field( "filterItem", References.ITEM_STACK.in(schema))), DSL.fields("isEnabled", DSL.bool().template()))); - schema.register(map, "gtceu:item_voiding_advanced", () -> DSL.and( + schema.register(map, "gtceu:item_voiding_advanced", () -> DSL.allWithRemainder( DSL.fields( "transferRate", DSL.intType().template(), "distributionMode", DSL.string().template(), @@ -125,7 +125,7 @@ public Map> registerCoverDefinitions(final Schema "isEnabled", DSL.bool().template(), "voidingMode", DSL.string().template(), "globalVoidingLimit", DSL.intType().template()))); - schema.register(map, "gtceu:fluid_voiding", () -> DSL.and( + schema.register(map, "gtceu:fluid_voiding", () -> DSL.allWithRemainder( DSL.fields( "currentMilliBucketsPerTick", DSL.longType().template(), "distributionMode", DSL.string().template(), @@ -139,7 +139,7 @@ public Map> registerCoverDefinitions(final Schema "filterHandler", DSL.field( "filterItem", References.ITEM_STACK.in(schema))), DSL.fields("isEnabled", DSL.bool().template()))); - schema.register(map, "gtceu:fluid_voiding_advanced", () -> DSL.and( + schema.register(map, "gtceu:fluid_voiding_advanced", () -> DSL.allWithRemainder( DSL.fields( "currentMilliBucketsPerTick", DSL.longType().template(), "distributionMode", DSL.string().template(), @@ -165,7 +165,7 @@ public Map> registerCoverDefinitions(final Schema schema.register(map, "gtceu:fluid_detector", () -> DSL.fields( "isWorkingEnabled", DSL.bool().template(), "isInverted", DSL.bool().template())); - schema.register(map, "gtceu:fluid_detector_advanced", () -> DSL.and( + schema.register(map, "gtceu:fluid_detector_advanced", () -> DSL.allWithRemainder( DSL.fields( "isWorkingEnabled", DSL.bool().template(), "isInverted", DSL.bool().template(), @@ -177,7 +177,7 @@ public Map> registerCoverDefinitions(final Schema schema.register(map, "gtceu:item_detector", () -> DSL.fields( "isWorkingEnabled", DSL.bool().template(), "isInverted", DSL.bool().template())); - schema.register(map, "gtceu:item_detector_advanced", () -> DSL.and( + schema.register(map, "gtceu:item_detector_advanced", () -> DSL.allWithRemainder( DSL.fields( "isWorkingEnabled", DSL.bool().template(), "isInverted", DSL.bool().template(), @@ -187,7 +187,7 @@ public Map> registerCoverDefinitions(final Schema "filterHandler", DSL.field( "filterItem", References.ITEM_STACK.in(schema))))); schema.register(map, "gtceu:energy_detector", () -> DSL.remainder()); - schema.register(map, "gtceu:energy_detector_advanced", () -> DSL.and( + schema.register(map, "gtceu:energy_detector_advanced", () -> DSL.allWithRemainder( DSL.fields( "isWorkingEnabled", DSL.bool().template(), "isInverted", DSL.bool().template(), @@ -212,7 +212,7 @@ public Map> registerBlockEntities(Schema schema) Supplier cover = () -> DSL.fields( "side", DSL.intType().template(), GTReferences.COVER.in(schema)); - Supplier covers = () -> DSL.and( + Supplier covers = () -> DSL.allWithRemainder( DSL.fields( "up", cover.get(), "down", cover.get(), @@ -221,27 +221,25 @@ public Map> registerBlockEntities(Schema schema) "south", cover.get(), "west", cover.get(), "east", cover.get())); - final Supplier pipe = () -> DSL.and( - DSL.fields( + final Supplier pipe = () -> DSL.allWithRemainder( + DSL.optionalFields( "connections", DSL.intType().template(), "blockedConnections", DSL.intType().template(), - "cover", covers.get() - ), - DSL.fields( + "cover", covers.get(), "paintingColor", DSL.intType().template(), "frameMaterial", GTReferences.MATERIAL_NAME.in(schema) )); - schema.register(map, "gtceu:cable", () -> DSL.fields( - "temperature", DSL.intType().template(), + schema.register(map, "gtceu:cable", () -> DSL.and( + DSL.optionalFields("temperature", DSL.intType().template()), pipe.get())); schema.register(map, "gtceu:fluid_pipe", pipe); schema.register(map, "gtceu:item_pipe", pipe); - schema.register(map, "gtceu:laser_pipe", () -> DSL.fields( - "active", DSL.bool().template(), + schema.register(map, "gtceu:laser_pipe", () -> DSL.and( + DSL.optionalFields("active", DSL.bool().template()), pipe.get())); - schema.register(map, "gtceu:optical_pipe", () -> DSL.fields( - "isActive", DSL.bool().template(), + schema.register(map, "gtceu:optical_pipe", () -> DSL.and( + DSL.optionalFields("isActive", DSL.bool().template()), pipe.get())); schema.register(map, "gtceu:duct_pipe", pipe); return map; @@ -251,7 +249,7 @@ protected static void registerInventory(Schema schema, Map cover = () -> DSL.fields( "side", DSL.intType().template(), GTReferences.COVER.in(schema)); - Supplier covers = () -> DSL.and( + Supplier covers = () -> DSL.allWithRemainder( DSL.fields( "up", cover.get(), "down", cover.get(), diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java index a60ad9b91c..22101b5500 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V2.java @@ -22,7 +22,7 @@ public Map> registerBlockEntities(Schema schema) DSL.fields( "side", DSL.byteType().template(), GTReferences.COVER.in(schema)))); - final Supplier pipe = () -> DSL.and( + final Supplier pipe = () -> DSL.allWithRemainder( DSL.fields( "connectionMask", DSL.byteType().template(), "renderMask", DSL.byteType().template(), @@ -33,10 +33,9 @@ public Map> registerBlockEntities(Schema schema) "frameMaterial", GTReferences.MATERIAL_NAME.in(schema))); schema.register(map, "gtceu:pipe", pipe); - schema.register(map, - "gtceu:activable_pipe", - () -> DSL.fields( - "active", DSL.bool().template(), + schema.register(map, "gtceu:activable_pipe", + () -> DSL.and( + DSL.optionalFields("active", DSL.bool().template()), pipe.get())); schema.register(map, "gtceu:material_pipe", pipe); return map; diff --git a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java index 68a13c93b6..85dda39b21 100644 --- a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java @@ -135,7 +135,7 @@ public static class CompatibilityConfigs { @Configurable @Configurable.Comment({ "Whether to run datafixers on world load.", - "Do note that mods like ModernFix will interfere with this.", + "Do note that mods like ModernFix will likely interfere with this.", "Default: true" }) public boolean doDatafixers = true; diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index ca0ac78bfc..4311ae73ff 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -452,5 +452,9 @@ public static void remapIds(MissingMappingsEvent event) { } } }); + + event.getMappings(Registries.BLOCK, GTCEu.MOD_ID).forEach(MissingMappingsEvent.Mapping::ignore); + event.getMappings(Registries.ITEM, GTCEu.MOD_ID).forEach(MissingMappingsEvent.Mapping::ignore); + event.getMappings(Registries.BLOCK_ENTITY_TYPE, GTCEu.MOD_ID).forEach(MissingMappingsEvent.Mapping::ignore); } } From 2dd726b7a532720bbc7155e02e9e200886fee2a7 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Fri, 6 Sep 2024 08:50:38 +0300 Subject: [PATCH 33/70] try to fix datafix --- .../gtceu/common/data/GTBlocks.java | 4 +- .../common/data/datafixer/GTDataFixers.java | 1 - .../gtceu/forge/ForgeCommonEventListener.java | 40 +++++++++++++++++-- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 68efb37423..d10b7fa049 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -357,9 +357,9 @@ private static void generateMaterialPipeBlocks() { GTCEu.LOGGER.debug("Generating GTCEu Material Pipe Blocks... Complete!"); } - private static boolean allowMaterialPipeBlock(Material material, MaterialPipeStructure fluidPipeType) { + private static boolean allowMaterialPipeBlock(Material material, MaterialPipeStructure pipeType) { return material.hasProperty(PropertyKey.PIPENET_PROPERTIES) && - material.getProperty(PropertyKey.PIPENET_PROPERTIES).generatesStructure(fluidPipeType); + material.getProperty(PropertyKey.PIPENET_PROPERTIES).generatesStructure(pipeType); } private static void registerMaterialPipeBlock(Material material, MaterialPipeStructure pipeType, diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java index 4a4760c533..fc071633be 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java @@ -74,7 +74,6 @@ public static void addFixers(DataFixerBuilder builder) { builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:cable")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:fluid_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:item_pipe")); - builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:item_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:duct_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:laser_pipe")); builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe block entities", References.BLOCK_ENTITY)); diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index 4311ae73ff..e0aa456ad1 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.forge; import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.GTCEuAPI; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.block.MetaMachineBlock; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; @@ -10,6 +11,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.properties.HazardProperty; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; +import com.gregtechceu.gtceu.api.data.chemical.material.registry.MaterialRegistry; import com.gregtechceu.gtceu.api.data.medicalcondition.MedicalCondition; import com.gregtechceu.gtceu.api.item.DrumMachineItem; import com.gregtechceu.gtceu.api.item.IComponentItem; @@ -24,6 +26,7 @@ import com.gregtechceu.gtceu.common.commands.HazardCommands; import com.gregtechceu.gtceu.common.commands.MedicalConditionCommands; import com.gregtechceu.gtceu.common.data.GTBlocks; +import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.common.data.GTMachines; import com.gregtechceu.gtceu.common.data.machines.GTAEMachines; @@ -81,6 +84,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * @author KilaBash * @date 2022/8/27 @@ -453,8 +459,36 @@ public static void remapIds(MissingMappingsEvent event) { } }); - event.getMappings(Registries.BLOCK, GTCEu.MOD_ID).forEach(MissingMappingsEvent.Mapping::ignore); - event.getMappings(Registries.ITEM, GTCEu.MOD_ID).forEach(MissingMappingsEvent.Mapping::ignore); - event.getMappings(Registries.BLOCK_ENTITY_TYPE, GTCEu.MOD_ID).forEach(MissingMappingsEvent.Mapping::ignore); + // remap pipe blocks (uses the datafixer in 1.21) + final Pattern itemPipe = Pattern.compile("(.+?)_(.+?)_item_pipe"); + final Pattern fluidPipe = Pattern.compile("(.+?)_(.+?)_fluid_pipe"); + for (MaterialRegistry registry : GTCEuAPI.materialManager.getRegistries()) { + String namespace = registry.getModid(); + event.getMappings(Registries.BLOCK, namespace).forEach(mapping -> { + remapPipe(itemPipe, mapping); + remapPipe(fluidPipe, mapping); + }); + event.getMappings(Registries.ITEM, namespace).forEach(mapping -> { + remapPipe(itemPipe, mapping); + remapPipe(fluidPipe, mapping); + }); + } + event.getMappings(Registries.BLOCK_ENTITY_TYPE, GTCEu.MOD_ID).forEach(mapping -> { + switch (mapping.getKey().getPath()) { + case "cable", "fluid_pipe", "item_pipe" -> mapping.remap(GTBlockEntities.MATERIAL_PIPE.get()); + case "laser_pipe", "optical_pipe" -> mapping.remap(GTBlockEntities.ACTIVABLE_PIPE.get()); + case "duct_pipe" -> mapping.remap(GTBlockEntities.PIPE.get()); + } + }); + } + + private static void remapPipe(Pattern pattern, MissingMappingsEvent.Mapping mapping) { + String namespace = mapping.getKey().getNamespace(); + String path = mapping.getKey().getPath(); + Matcher match = pattern.matcher(path); + if (match.matches()) { + ResourceLocation newBlock = new ResourceLocation(namespace, match.replaceAll("$2_$1_pipe")); + mapping.remap(mapping.getRegistry().getValue(newBlock)); + } } } From 31d1c8c12e19d85489367948d1ee9ca0b88b2e57 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Fri, 6 Sep 2024 08:53:43 +0300 Subject: [PATCH 34/70] datagen --- .../{oil_heavy.json => heavy_oil.json} | 2 +- .../{oil_light.json => light_oil.json} | 2 +- .../assets/gtceu/blockstates/oil_medium.json | 7 ------- .../assets/gtceu/blockstates/raw_oil.json | 7 +++++++ .../compass/nodes/generation/andesite.json | 2 +- .../compass/nodes/generation/basalt.json | 2 +- .../compass/nodes/generation/blackstone.json | 2 +- .../compass/nodes/generation/deepslate.json | 2 +- .../compass/nodes/generation/diorite.json | 2 +- .../compass/nodes/generation/endstone.json | 2 +- .../compass/nodes/generation/granite.json | 2 +- .../compass/nodes/generation/gravel.json | 2 +- .../compass/nodes/generation/marble.json | 2 +- .../compass/nodes/generation/netherrack.json | 2 +- .../compass/nodes/generation/red_granite.json | 2 +- .../compass/nodes/generation/red_sand.json | 2 +- .../gtceu/compass/nodes/generation/sand.json | 2 +- .../gtceu/compass/nodes/generation/stone.json | 2 +- .../gtceu/compass/nodes/generation/tuff.json | 2 +- .../resources/assets/gtceu/lang/en_ud.json | 18 ++++++++++-------- .../resources/assets/gtceu/lang/en_us.json | 18 ++++++++++-------- .../assets/gtceu/models/block/heavy_oil.json | 5 +++++ .../assets/gtceu/models/block/light_oil.json | 5 +++++ .../assets/gtceu/models/block/oil_heavy.json | 5 ----- .../assets/gtceu/models/block/oil_light.json | 5 ----- .../assets/gtceu/models/block/oil_medium.json | 5 ----- .../assets/gtceu/models/block/raw_oil.json | 5 +++++ ...on => advanced_nanomuscle_chestplate.json} | 2 +- .../p2p_attunements/fluid_p2p_tunnel.json | 10 +++++----- .../forge/tags/items/armors/chestplates.json | 2 +- .../data/gtceu/tags/items/ppe_armor.json | 2 +- .../configured_feature/raw_oil_sprout.json | 2 +- .../minecraft/tags/blocks/replaceable.json | 6 +++--- ...luid.oil_heavy.png => fluid.heavy_oil.png} | Bin ....png.mcmeta => fluid.heavy_oil.png.mcmeta} | 0 ...luid.oil_light.png => fluid.light_oil.png} | Bin ....png.mcmeta => fluid.light_oil.png.mcmeta} | 0 ...fluid.oil_medium.png => fluid.raw_oil.png} | Bin ...um.png.mcmeta => fluid.raw_oil.png.mcmeta} | 0 ...png => advanced_nanomuscle_chestplate.png} | Bin 40 files changed, 71 insertions(+), 67 deletions(-) rename src/generated/resources/assets/gtceu/blockstates/{oil_heavy.json => heavy_oil.json} (50%) rename src/generated/resources/assets/gtceu/blockstates/{oil_light.json => light_oil.json} (50%) delete mode 100644 src/generated/resources/assets/gtceu/blockstates/oil_medium.json create mode 100644 src/generated/resources/assets/gtceu/blockstates/raw_oil.json create mode 100644 src/generated/resources/assets/gtceu/models/block/heavy_oil.json create mode 100644 src/generated/resources/assets/gtceu/models/block/light_oil.json delete mode 100644 src/generated/resources/assets/gtceu/models/block/oil_heavy.json delete mode 100644 src/generated/resources/assets/gtceu/models/block/oil_light.json delete mode 100644 src/generated/resources/assets/gtceu/models/block/oil_medium.json create mode 100644 src/generated/resources/assets/gtceu/models/block/raw_oil.json rename src/generated/resources/assets/gtceu/models/item/{avanced_nanomuscle_chestplate.json => advanced_nanomuscle_chestplate.json} (52%) rename src/main/resources/assets/gtceu/textures/block/fluids/{fluid.oil_heavy.png => fluid.heavy_oil.png} (100%) rename src/main/resources/assets/gtceu/textures/block/fluids/{fluid.oil_heavy.png.mcmeta => fluid.heavy_oil.png.mcmeta} (100%) rename src/main/resources/assets/gtceu/textures/block/fluids/{fluid.oil_light.png => fluid.light_oil.png} (100%) rename src/main/resources/assets/gtceu/textures/block/fluids/{fluid.oil_light.png.mcmeta => fluid.light_oil.png.mcmeta} (100%) rename src/main/resources/assets/gtceu/textures/block/fluids/{fluid.oil_medium.png => fluid.raw_oil.png} (100%) rename src/main/resources/assets/gtceu/textures/block/fluids/{fluid.oil_medium.png.mcmeta => fluid.raw_oil.png.mcmeta} (100%) rename src/main/resources/assets/gtceu/textures/item/{avanced_nanomuscle_chestplate.png => advanced_nanomuscle_chestplate.png} (100%) diff --git a/src/generated/resources/assets/gtceu/blockstates/oil_heavy.json b/src/generated/resources/assets/gtceu/blockstates/heavy_oil.json similarity index 50% rename from src/generated/resources/assets/gtceu/blockstates/oil_heavy.json rename to src/generated/resources/assets/gtceu/blockstates/heavy_oil.json index 89572bbc66..58eb6297d3 100644 --- a/src/generated/resources/assets/gtceu/blockstates/oil_heavy.json +++ b/src/generated/resources/assets/gtceu/blockstates/heavy_oil.json @@ -1,7 +1,7 @@ { "variants": { "": { - "model": "gtceu:block/oil_heavy" + "model": "gtceu:block/heavy_oil" } } } \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/blockstates/oil_light.json b/src/generated/resources/assets/gtceu/blockstates/light_oil.json similarity index 50% rename from src/generated/resources/assets/gtceu/blockstates/oil_light.json rename to src/generated/resources/assets/gtceu/blockstates/light_oil.json index 7da636112e..da76726bc2 100644 --- a/src/generated/resources/assets/gtceu/blockstates/oil_light.json +++ b/src/generated/resources/assets/gtceu/blockstates/light_oil.json @@ -1,7 +1,7 @@ { "variants": { "": { - "model": "gtceu:block/oil_light" + "model": "gtceu:block/light_oil" } } } \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/blockstates/oil_medium.json b/src/generated/resources/assets/gtceu/blockstates/oil_medium.json deleted file mode 100644 index 810ef09ee0..0000000000 --- a/src/generated/resources/assets/gtceu/blockstates/oil_medium.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "gtceu:block/oil_medium" - } - } -} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/blockstates/raw_oil.json b/src/generated/resources/assets/gtceu/blockstates/raw_oil.json new file mode 100644 index 0000000000..c741baaffd --- /dev/null +++ b/src/generated/resources/assets/gtceu/blockstates/raw_oil.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "gtceu:block/raw_oil" + } + } +} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/andesite.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/andesite.json index 514c85962a..0e18db5b43 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/andesite.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/andesite.json @@ -17,7 +17,7 @@ "gtceu:andesite_nickel_ore", "gtceu:andesite_palladium_ore", "gtceu:andesite_platinum_ore", - "gtceu:andesite_plutonium_ore", + "gtceu:andesite_plutonium_239_ore", "gtceu:andesite_silver_ore", "gtceu:andesite_sulfur_ore", "gtceu:andesite_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/basalt.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/basalt.json index 68ab05ead3..cf0c2e43ae 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/basalt.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/basalt.json @@ -17,7 +17,7 @@ "gtceu:basalt_nickel_ore", "gtceu:basalt_palladium_ore", "gtceu:basalt_platinum_ore", - "gtceu:basalt_plutonium_ore", + "gtceu:basalt_plutonium_239_ore", "gtceu:basalt_silver_ore", "gtceu:basalt_sulfur_ore", "gtceu:basalt_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/blackstone.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/blackstone.json index e7aaf5e64b..80463f8420 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/blackstone.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/blackstone.json @@ -17,7 +17,7 @@ "gtceu:blackstone_nickel_ore", "gtceu:blackstone_palladium_ore", "gtceu:blackstone_platinum_ore", - "gtceu:blackstone_plutonium_ore", + "gtceu:blackstone_plutonium_239_ore", "gtceu:blackstone_silver_ore", "gtceu:blackstone_sulfur_ore", "gtceu:blackstone_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/deepslate.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/deepslate.json index 593ae09a46..c8a652f088 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/deepslate.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/deepslate.json @@ -17,7 +17,7 @@ "gtceu:deepslate_nickel_ore", "gtceu:deepslate_palladium_ore", "gtceu:deepslate_platinum_ore", - "gtceu:deepslate_plutonium_ore", + "gtceu:deepslate_plutonium_239_ore", "gtceu:deepslate_silver_ore", "gtceu:deepslate_sulfur_ore", "gtceu:deepslate_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/diorite.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/diorite.json index 3bee07fcab..f0c57efe4e 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/diorite.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/diorite.json @@ -17,7 +17,7 @@ "gtceu:diorite_nickel_ore", "gtceu:diorite_palladium_ore", "gtceu:diorite_platinum_ore", - "gtceu:diorite_plutonium_ore", + "gtceu:diorite_plutonium_239_ore", "gtceu:diorite_silver_ore", "gtceu:diorite_sulfur_ore", "gtceu:diorite_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/endstone.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/endstone.json index f3b450c854..4fd74f6f45 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/endstone.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/endstone.json @@ -17,7 +17,7 @@ "gtceu:endstone_nickel_ore", "gtceu:endstone_palladium_ore", "gtceu:endstone_platinum_ore", - "gtceu:endstone_plutonium_ore", + "gtceu:endstone_plutonium_239_ore", "gtceu:endstone_silver_ore", "gtceu:endstone_sulfur_ore", "gtceu:endstone_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/granite.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/granite.json index 9c6fba0d3e..17bffa7dc8 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/granite.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/granite.json @@ -17,7 +17,7 @@ "gtceu:granite_nickel_ore", "gtceu:granite_palladium_ore", "gtceu:granite_platinum_ore", - "gtceu:granite_plutonium_ore", + "gtceu:granite_plutonium_239_ore", "gtceu:granite_silver_ore", "gtceu:granite_sulfur_ore", "gtceu:granite_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/gravel.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/gravel.json index c54c07dc70..a9179d66ce 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/gravel.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/gravel.json @@ -17,7 +17,7 @@ "gtceu:gravel_nickel_ore", "gtceu:gravel_palladium_ore", "gtceu:gravel_platinum_ore", - "gtceu:gravel_plutonium_ore", + "gtceu:gravel_plutonium_239_ore", "gtceu:gravel_silver_ore", "gtceu:gravel_sulfur_ore", "gtceu:gravel_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/marble.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/marble.json index 2f7518d361..9684085568 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/marble.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/marble.json @@ -17,7 +17,7 @@ "gtceu:marble_nickel_ore", "gtceu:marble_palladium_ore", "gtceu:marble_platinum_ore", - "gtceu:marble_plutonium_ore", + "gtceu:marble_plutonium_239_ore", "gtceu:marble_silver_ore", "gtceu:marble_sulfur_ore", "gtceu:marble_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/netherrack.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/netherrack.json index 554656725c..e05e2b986b 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/netherrack.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/netherrack.json @@ -17,7 +17,7 @@ "gtceu:netherrack_nickel_ore", "gtceu:netherrack_palladium_ore", "gtceu:netherrack_platinum_ore", - "gtceu:netherrack_plutonium_ore", + "gtceu:netherrack_plutonium_239_ore", "gtceu:netherrack_silver_ore", "gtceu:netherrack_sulfur_ore", "gtceu:netherrack_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/red_granite.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/red_granite.json index af3ff88f99..d0b421a11e 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/red_granite.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/red_granite.json @@ -17,7 +17,7 @@ "gtceu:red_granite_nickel_ore", "gtceu:red_granite_palladium_ore", "gtceu:red_granite_platinum_ore", - "gtceu:red_granite_plutonium_ore", + "gtceu:red_granite_plutonium_239_ore", "gtceu:red_granite_silver_ore", "gtceu:red_granite_sulfur_ore", "gtceu:red_granite_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/red_sand.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/red_sand.json index e90b2bb6f2..69c5fc8df8 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/red_sand.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/red_sand.json @@ -17,7 +17,7 @@ "gtceu:red_sand_nickel_ore", "gtceu:red_sand_palladium_ore", "gtceu:red_sand_platinum_ore", - "gtceu:red_sand_plutonium_ore", + "gtceu:red_sand_plutonium_239_ore", "gtceu:red_sand_silver_ore", "gtceu:red_sand_sulfur_ore", "gtceu:red_sand_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/sand.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/sand.json index 32ebda4c75..4bddbe4935 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/sand.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/sand.json @@ -17,7 +17,7 @@ "gtceu:sand_nickel_ore", "gtceu:sand_palladium_ore", "gtceu:sand_platinum_ore", - "gtceu:sand_plutonium_ore", + "gtceu:sand_plutonium_239_ore", "gtceu:sand_silver_ore", "gtceu:sand_sulfur_ore", "gtceu:sand_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/stone.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/stone.json index 8728269bd9..5cfc884330 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/stone.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/stone.json @@ -17,7 +17,7 @@ "gtceu:nickel_ore", "gtceu:palladium_ore", "gtceu:platinum_ore", - "gtceu:plutonium_ore", + "gtceu:plutonium_239_ore", "gtceu:silver_ore", "gtceu:sulfur_ore", "gtceu:thorium_ore", diff --git a/src/generated/resources/assets/gtceu/compass/nodes/generation/tuff.json b/src/generated/resources/assets/gtceu/compass/nodes/generation/tuff.json index 890f3b4f56..30e1cbe4b4 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/generation/tuff.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/generation/tuff.json @@ -17,7 +17,7 @@ "gtceu:tuff_nickel_ore", "gtceu:tuff_palladium_ore", "gtceu:tuff_platinum_ore", - "gtceu:tuff_plutonium_ore", + "gtceu:tuff_plutonium_239_ore", "gtceu:tuff_silver_ore", "gtceu:tuff_sulfur_ore", "gtceu:tuff_thorium_ore", diff --git a/src/generated/resources/assets/gtceu/lang/en_ud.json b/src/generated/resources/assets/gtceu/lang/en_ud.json index 3a55a5b225..6fb896036a 100644 --- a/src/generated/resources/assets/gtceu/lang/en_ud.json +++ b/src/generated/resources/assets/gtceu/lang/en_ud.json @@ -14,7 +14,7 @@ "behavior.portable_scanner.debug_lag_count": "˙ɹǝʌɹǝS ǝɥʇ uo )sɯ%s uɐɥʇ ɹǝbuoן buıʞɐʇ buıɥʇʎuɐ( sbuıuɹɐM ǝʞıdS bɐꞀ %s pǝsnɐƆ", "behavior.portable_scanner.debug_machine": "%s :ᗡI-ɐʇǝW", "behavior.portable_scanner.debug_machine_invalid": "¡pıןɐʌuı ", - "behavior.portable_scanner.debug_machine_invalid_null=invalid! MetaTileEntity =": "¡ןןnu ", + "behavior.portable_scanner.debug_machine_invalid_null": "¡ןןnu = ʎʇıʇuƎǝןı⟘ɐʇǝW ¡pıןɐʌuı", "behavior.portable_scanner.debug_machine_valid": "pıןɐʌ ", "behavior.portable_scanner.divider": "=========================", "behavior.portable_scanner.energy_container_in": "Ɐ %s ʇɐ ∩Ǝ )%s( %s :NI xɐW", @@ -2236,6 +2236,7 @@ "config.gtceu.option.dev": "ʌǝp", "config.gtceu.option.disableManualCompression": "uoıssǝɹdɯoƆןɐnuɐWǝןqɐsıp", "config.gtceu.option.doBedrockOres": "sǝɹOʞɔoɹpǝᗺop", + "config.gtceu.option.doDatafixers": "sɹǝxıɟɐʇɐᗡop", "config.gtceu.option.doProcessingArray": "ʎɐɹɹⱯbuıssǝɔoɹԀop", "config.gtceu.option.doTerrainExplosion": "uoısoןdxƎuıɐɹɹǝ⟘op", "config.gtceu.option.doesExplosionDamagesTerrain": "uıɐɹɹǝ⟘sǝbɐɯɐᗡuoısoןdxƎsǝop", @@ -4075,6 +4076,7 @@ "item.gtceu.advanced_item_voiding_cover": "ɹǝʌoƆ buıpıoΛ ɯǝʇI pǝɔuɐʌpⱯ", "item.gtceu.advanced_item_voiding_cover.tooltip.0": "˙ㄥ§ɹǝʌoƆɟ§ sɐ ןoɹʇuoɔ ʇunoɯɐ ɥʇıʍ ㄥ§sɯǝʇIɟ§ spıoΛㄥ§", "item.gtceu.advanced_item_voiding_cover.tooltip.1": "˙ʇuǝɯǝɔɐןd ɹǝʇɟɐ ㄥ§ʇǝןןɐW ʇɟoSɟ§ ɥʇıʍ ǝʇɐʌıʇɔⱯ", + "item.gtceu.advanced_nanomuscle_chestplate": "ǝʇɐןdʇsǝɥƆ ǝʇınS ™ǝןɔsnWouɐN pǝɔuɐʌpⱯ", "item.gtceu.advanced_power_thruster": "ɹǝʇsnɹɥ⟘ ɹǝʍoԀ pǝɔuɐʌpⱯ", "item.gtceu.advanced_quarktech_chestplate": "ǝʇɐןdʇsǝɥƆ ǝʇınS ™ɥɔǝ⟘ʞɹɐnὉ pǝɔuɐʌpⱯ", "item.gtceu.advanced_smd_capacitor": "ɹoʇıɔɐdɐƆ ᗡWS pǝɔuɐʌpⱯ", @@ -4097,7 +4099,6 @@ "item.gtceu.anvil_casting_mold": ")ןıʌuⱯ( pןoW buıʇsɐƆ", "item.gtceu.anvil_casting_mold.tooltip": "sןıʌuⱯ buıdɐɥs ɹoɟ pןoWㄥ§", "item.gtceu.ash_dust": "sǝɥsⱯ", - "item.gtceu.avanced_nanomuscle_chestplate": "ǝʇɐןdʇsǝɥƆ ǝʇınS ™ǝןɔsnWouɐN pǝɔuɐʌpⱯ", "item.gtceu.axe_extruder_mold.tooltip": "sǝxⱯ buıʞɐɯ ɹoɟ ǝdɐɥS ɹǝpnɹʇxƎㄥ§", "item.gtceu.ball_casting_mold": ")ןןɐᗺ( pןoW buıʇsɐƆ", "item.gtceu.ball_casting_mold.tooltip": "sןןɐᗺ buıʞɐɯ ɹoɟ pןoWㄥ§", @@ -5256,6 +5257,7 @@ "material.gtceu.einsteinium": "ɯnıuıǝʇsuıƎ", "material.gtceu.electrotine": "ǝuıʇoɹʇɔǝןƎ", "material.gtceu.electrum": "ɯnɹʇɔǝןƎ", + "material.gtceu.elementium": "ɯnıʇuǝɯǝןƎ", "material.gtceu.emerald": "pןɐɹǝɯƎ", "material.gtceu.ender_air": "ɹıⱯ ɹǝpuƎ", "material.gtceu.ender_eye": "ǝʎƎ ɹǝpuƎ", @@ -5314,7 +5316,6 @@ "material.gtceu.goethite": "ǝʇıɥʇǝo⅁", "material.gtceu.gold": "pןo⅁", "material.gtceu.granite": "ǝʇıuɐɹ⅁", - "material.gtceu.granite_red": "pǝᴚ ǝʇıuɐɹ⅁", "material.gtceu.granitic_mineral_sand": "puɐS ןɐɹǝuıW ɔıʇıuɐɹ⅁", "material.gtceu.graphene": "ǝuǝɥdɐɹ⅁", "material.gtceu.graphite": "ǝʇıɥdɐɹ⅁", @@ -5330,6 +5331,7 @@ "material.gtceu.hastelloy_c_276": "9ㄥᄅ-Ɔ ʎoןןǝʇsɐH", "material.gtceu.hastelloy_x": "X ʎoןןǝʇsɐH", "material.gtceu.heavy_fuel": "ןǝnℲ ʎʌɐǝH", + "material.gtceu.heavy_oil": "ןıO ʎʌɐǝH", "material.gtceu.helium": "ɯnıןǝH", "material.gtceu.helium_3": "Ɛ ɯnıןǝH", "material.gtceu.hematite": "ǝʇıʇɐɯǝH", @@ -5392,6 +5394,7 @@ "material.gtceu.light_blue_dye": "ǝʎᗡ ǝnןᗺ ʇɥbıꞀ", "material.gtceu.light_fuel": "ןǝnℲ ʇɥbıꞀ", "material.gtceu.light_gray_dye": "ǝʎᗡ ʎɐɹ⅁ ʇɥbıꞀ", + "material.gtceu.light_oil": "ןıO ʇɥbıꞀ", "material.gtceu.lightly_hydro_cracked_gas": "sɐ⅁ pǝʞɔɐɹƆ-oɹpʎH ʎןʇɥbıꞀ", "material.gtceu.lightly_hydro_cracked_heavy_fuel": "ןǝnℲ ʎʌɐǝH pǝʞɔɐɹƆ-oɹpʎH ʎןʇɥbıꞀ", "material.gtceu.lightly_hydro_cracked_light_fuel": "ןǝnℲ ʇɥbıꞀ pǝʞɔɐɹƆ-oɹpʎH ʎןʇɥbıꞀ", @@ -5486,9 +5489,6 @@ "material.gtceu.octane": "ǝuɐʇɔO", "material.gtceu.oganesson": "uossǝuɐbO", "material.gtceu.oil": "ןıO", - "material.gtceu.oil_heavy": "ןıO ʎʌɐǝH", - "material.gtceu.oil_light": "ןıO ʇɥbıꞀ", - "material.gtceu.oil_medium": "ןıO ʍɐᴚ", "material.gtceu.oilsands": "spuɐsןıO", "material.gtceu.olivine": "ǝuıʌıןO", "material.gtceu.opal": "ןɐdO", @@ -5516,7 +5516,7 @@ "material.gtceu.platinum_group_sludge": "ǝbpnןS dnoɹ⅁ ɯnuıʇɐןԀ", "material.gtceu.platinum_raw": "ʍɐᴚ ɯnuıʇɐןԀ", "material.gtceu.platinum_sludge_residue": "ǝnpısǝᴚ ǝbpnןS ɯnuıʇɐןԀ", - "material.gtceu.plutonium": "ɯnıuoʇnןԀ", + "material.gtceu.plutonium_239": "6Ɛᄅ ɯnıuoʇnןԀ", "material.gtceu.plutonium_241": "Ɩㄣᄅ ɯnıuoʇnןԀ", "material.gtceu.pollucite": "ǝʇıɔnןןoԀ", "material.gtceu.polonium": "ɯnıuoןoԀ", @@ -5564,12 +5564,14 @@ "material.gtceu.raw_brine": "ǝuıɹᗺ ʍɐᴚ", "material.gtceu.raw_gasoline": "ǝuıןosɐ⅁ ʍɐᴚ", "material.gtceu.raw_growth_medium": "ɯnıpǝW ɥʇʍoɹ⅁ ʍɐᴚ", + "material.gtceu.raw_oil": "ןıO ʍɐᴚ", "material.gtceu.raw_rubber": "ɹǝqqnᴚ ʍɐᴚ", "material.gtceu.raw_styrene_butadiene_rubber": "ɹǝqqnᴚ ǝuǝıpɐʇnᗺ ǝuǝɹʎʇS ʍɐᴚ", "material.gtceu.realgar": "ɹɐbןɐǝᴚ", "material.gtceu.red_alloy": "ʎoןןⱯ pǝᴚ", "material.gtceu.red_dye": "ǝʎᗡ pǝᴚ", "material.gtceu.red_garnet": "ʇǝuɹɐ⅁ pǝᴚ", + "material.gtceu.red_granite": "ǝʇıuɐɹ⅁ pǝᴚ", "material.gtceu.red_steel": "ןǝǝʇS pǝᴚ", "material.gtceu.redrock": "ʞɔoɹpǝᴚ", "material.gtceu.redstone": "ǝuoʇspǝᴚ", @@ -5700,8 +5702,8 @@ "material.gtceu.tungstic_acid": "pıɔⱯ ɔıʇsbun⟘", "material.gtceu.ultimet": "ʇǝɯıʇן∩", "material.gtceu.uraninite": "ǝʇıuıuɐɹ∩", - "material.gtceu.uranium": "ɯnıuɐɹ∩", "material.gtceu.uranium_235": "ϛƐᄅ ɯnıuɐɹ∩", + "material.gtceu.uranium_238": "8Ɛᄅ ɯnıuɐɹ∩", "material.gtceu.uranium_hexafluoride": "ǝpıɹonןɟɐxǝH ɯnıuɐɹ∩", "material.gtceu.uranium_rhodium_dinaquadide": "ǝpıpɐnbɐuıᗡ ɯnıpoɥᴚ ɯnıuɐɹ∩", "material.gtceu.uranium_triplatinum": "ɯnuıʇɐןdıɹ⟘ ɯnıuɐɹ∩", diff --git a/src/generated/resources/assets/gtceu/lang/en_us.json b/src/generated/resources/assets/gtceu/lang/en_us.json index f723f9e2be..70286efb43 100644 --- a/src/generated/resources/assets/gtceu/lang/en_us.json +++ b/src/generated/resources/assets/gtceu/lang/en_us.json @@ -14,7 +14,7 @@ "behavior.portable_scanner.debug_lag_count": "Caused %s Lag Spike Warnings (anything taking longer than %sms) on the Server.", "behavior.portable_scanner.debug_machine": "Meta-ID: %s", "behavior.portable_scanner.debug_machine_invalid": " invalid!", - "behavior.portable_scanner.debug_machine_invalid_null=invalid! MetaTileEntity =": " null!", + "behavior.portable_scanner.debug_machine_invalid_null": "invalid! MetaTileEntity = null!", "behavior.portable_scanner.debug_machine_valid": " valid", "behavior.portable_scanner.divider": "=========================", "behavior.portable_scanner.energy_container_in": "Max IN: %s (%s) EU at %s A", @@ -2236,6 +2236,7 @@ "config.gtceu.option.dev": "dev", "config.gtceu.option.disableManualCompression": "disableManualCompression", "config.gtceu.option.doBedrockOres": "doBedrockOres", + "config.gtceu.option.doDatafixers": "doDatafixers", "config.gtceu.option.doProcessingArray": "doProcessingArray", "config.gtceu.option.doTerrainExplosion": "doTerrainExplosion", "config.gtceu.option.doesExplosionDamagesTerrain": "doesExplosionDamagesTerrain", @@ -4075,6 +4076,7 @@ "item.gtceu.advanced_item_voiding_cover": "Advanced Item Voiding Cover", "item.gtceu.advanced_item_voiding_cover.tooltip.0": "§7Voids §fItems§7 with amount control as §fCover§7.", "item.gtceu.advanced_item_voiding_cover.tooltip.1": "Activate with §fSoft Mallet§7 after placement.", + "item.gtceu.advanced_nanomuscle_chestplate": "Advanced NanoMuscle™ Suite Chestplate", "item.gtceu.advanced_power_thruster": "Advanced Power Thruster", "item.gtceu.advanced_quarktech_chestplate": "Advanced QuarkTech™ Suite Chestplate", "item.gtceu.advanced_smd_capacitor": "Advanced SMD Capacitor", @@ -4097,7 +4099,6 @@ "item.gtceu.anvil_casting_mold": "Casting Mold (Anvil)", "item.gtceu.anvil_casting_mold.tooltip": "§7Mold for shaping Anvils", "item.gtceu.ash_dust": "Ashes", - "item.gtceu.avanced_nanomuscle_chestplate": "Advanced NanoMuscle™ Suite Chestplate", "item.gtceu.axe_extruder_mold.tooltip": "§7Extruder Shape for making Axes", "item.gtceu.ball_casting_mold": "Casting Mold (Ball)", "item.gtceu.ball_casting_mold.tooltip": "§7Mold for making Balls", @@ -5256,6 +5257,7 @@ "material.gtceu.einsteinium": "Einsteinium", "material.gtceu.electrotine": "Electrotine", "material.gtceu.electrum": "Electrum", + "material.gtceu.elementium": "Elementium", "material.gtceu.emerald": "Emerald", "material.gtceu.ender_air": "Ender Air", "material.gtceu.ender_eye": "Ender Eye", @@ -5314,7 +5316,6 @@ "material.gtceu.goethite": "Goethite", "material.gtceu.gold": "Gold", "material.gtceu.granite": "Granite", - "material.gtceu.granite_red": "Granite Red", "material.gtceu.granitic_mineral_sand": "Granitic Mineral Sand", "material.gtceu.graphene": "Graphene", "material.gtceu.graphite": "Graphite", @@ -5330,6 +5331,7 @@ "material.gtceu.hastelloy_c_276": "Hastelloy C-276", "material.gtceu.hastelloy_x": "Hastelloy X", "material.gtceu.heavy_fuel": "Heavy Fuel", + "material.gtceu.heavy_oil": "Heavy Oil", "material.gtceu.helium": "Helium", "material.gtceu.helium_3": "Helium 3", "material.gtceu.hematite": "Hematite", @@ -5392,6 +5394,7 @@ "material.gtceu.light_blue_dye": "Light Blue Dye", "material.gtceu.light_fuel": "Light Fuel", "material.gtceu.light_gray_dye": "Light Gray Dye", + "material.gtceu.light_oil": "Light Oil", "material.gtceu.lightly_hydro_cracked_gas": "Lightly Hydro-Cracked Gas", "material.gtceu.lightly_hydro_cracked_heavy_fuel": "Lightly Hydro-Cracked Heavy Fuel", "material.gtceu.lightly_hydro_cracked_light_fuel": "Lightly Hydro-Cracked Light Fuel", @@ -5486,9 +5489,6 @@ "material.gtceu.octane": "Octane", "material.gtceu.oganesson": "Oganesson", "material.gtceu.oil": "Oil", - "material.gtceu.oil_heavy": "Heavy Oil", - "material.gtceu.oil_light": "Light Oil", - "material.gtceu.oil_medium": "Raw Oil", "material.gtceu.oilsands": "Oilsands", "material.gtceu.olivine": "Olivine", "material.gtceu.opal": "Opal", @@ -5516,7 +5516,7 @@ "material.gtceu.platinum_group_sludge": "Platinum Group Sludge", "material.gtceu.platinum_raw": "Platinum Raw", "material.gtceu.platinum_sludge_residue": "Platinum Sludge Residue", - "material.gtceu.plutonium": "Plutonium", + "material.gtceu.plutonium_239": "Plutonium 239", "material.gtceu.plutonium_241": "Plutonium 241", "material.gtceu.pollucite": "Pollucite", "material.gtceu.polonium": "Polonium", @@ -5564,12 +5564,14 @@ "material.gtceu.raw_brine": "Raw Brine", "material.gtceu.raw_gasoline": "Raw Gasoline", "material.gtceu.raw_growth_medium": "Raw Growth Medium", + "material.gtceu.raw_oil": "Raw Oil", "material.gtceu.raw_rubber": "Raw Rubber", "material.gtceu.raw_styrene_butadiene_rubber": "Raw Styrene Butadiene Rubber", "material.gtceu.realgar": "Realgar", "material.gtceu.red_alloy": "Red Alloy", "material.gtceu.red_dye": "Red Dye", "material.gtceu.red_garnet": "Red Garnet", + "material.gtceu.red_granite": "Red Granite", "material.gtceu.red_steel": "Red Steel", "material.gtceu.redrock": "Redrock", "material.gtceu.redstone": "Redstone", @@ -5700,8 +5702,8 @@ "material.gtceu.tungstic_acid": "Tungstic Acid", "material.gtceu.ultimet": "Ultimet", "material.gtceu.uraninite": "Uraninite", - "material.gtceu.uranium": "Uranium", "material.gtceu.uranium_235": "Uranium 235", + "material.gtceu.uranium_238": "Uranium 238", "material.gtceu.uranium_hexafluoride": "Uranium Hexafluoride", "material.gtceu.uranium_rhodium_dinaquadide": "Uranium Rhodium Dinaquadide", "material.gtceu.uranium_triplatinum": "Uranium Triplatinum", diff --git a/src/generated/resources/assets/gtceu/models/block/heavy_oil.json b/src/generated/resources/assets/gtceu/models/block/heavy_oil.json new file mode 100644 index 0000000000..b74b02b070 --- /dev/null +++ b/src/generated/resources/assets/gtceu/models/block/heavy_oil.json @@ -0,0 +1,5 @@ +{ + "textures": { + "particle": "gtceu:block/fluids/fluid.heavy_oil" + } +} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/models/block/light_oil.json b/src/generated/resources/assets/gtceu/models/block/light_oil.json new file mode 100644 index 0000000000..a6ff95ff32 --- /dev/null +++ b/src/generated/resources/assets/gtceu/models/block/light_oil.json @@ -0,0 +1,5 @@ +{ + "textures": { + "particle": "gtceu:block/fluids/fluid.light_oil" + } +} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/models/block/oil_heavy.json b/src/generated/resources/assets/gtceu/models/block/oil_heavy.json deleted file mode 100644 index 2e6953bb4a..0000000000 --- a/src/generated/resources/assets/gtceu/models/block/oil_heavy.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "textures": { - "particle": "gtceu:block/fluids/fluid.oil_heavy" - } -} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/models/block/oil_light.json b/src/generated/resources/assets/gtceu/models/block/oil_light.json deleted file mode 100644 index 0cbd722a2b..0000000000 --- a/src/generated/resources/assets/gtceu/models/block/oil_light.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "textures": { - "particle": "gtceu:block/fluids/fluid.oil_light" - } -} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/models/block/oil_medium.json b/src/generated/resources/assets/gtceu/models/block/oil_medium.json deleted file mode 100644 index 8f7f4602f7..0000000000 --- a/src/generated/resources/assets/gtceu/models/block/oil_medium.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "textures": { - "particle": "gtceu:block/fluids/fluid.oil_medium" - } -} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/models/block/raw_oil.json b/src/generated/resources/assets/gtceu/models/block/raw_oil.json new file mode 100644 index 0000000000..7e11b4e6d6 --- /dev/null +++ b/src/generated/resources/assets/gtceu/models/block/raw_oil.json @@ -0,0 +1,5 @@ +{ + "textures": { + "particle": "gtceu:block/fluids/fluid.raw_oil" + } +} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/models/item/avanced_nanomuscle_chestplate.json b/src/generated/resources/assets/gtceu/models/item/advanced_nanomuscle_chestplate.json similarity index 52% rename from src/generated/resources/assets/gtceu/models/item/avanced_nanomuscle_chestplate.json rename to src/generated/resources/assets/gtceu/models/item/advanced_nanomuscle_chestplate.json index eb85c6d7e3..baa2533e81 100644 --- a/src/generated/resources/assets/gtceu/models/item/avanced_nanomuscle_chestplate.json +++ b/src/generated/resources/assets/gtceu/models/item/advanced_nanomuscle_chestplate.json @@ -1,6 +1,6 @@ { "parent": "minecraft:item/generated", "textures": { - "layer0": "gtceu:item/avanced_nanomuscle_chestplate" + "layer0": "gtceu:item/advanced_nanomuscle_chestplate" } } \ No newline at end of file diff --git a/src/generated/resources/data/ae2/tags/items/p2p_attunements/fluid_p2p_tunnel.json b/src/generated/resources/data/ae2/tags/items/p2p_attunements/fluid_p2p_tunnel.json index 81bdd899b1..89a6487172 100644 --- a/src/generated/resources/data/ae2/tags/items/p2p_attunements/fluid_p2p_tunnel.json +++ b/src/generated/resources/data/ae2/tags/items/p2p_attunements/fluid_p2p_tunnel.json @@ -52,7 +52,7 @@ "gtceu:oxygen_plasma_bucket", "gtceu:palladium_bucket", "gtceu:platinum_bucket", - "gtceu:plutonium_bucket", + "gtceu:plutonium_239_bucket", "gtceu:plutonium_241_bucket", "gtceu:potassium_bucket", "gtceu:radon_bucket", @@ -67,7 +67,7 @@ "gtceu:titanium_bucket", "gtceu:tritium_bucket", "gtceu:tungsten_bucket", - "gtceu:uranium_bucket", + "gtceu:uranium_238_bucket", "gtceu:uranium_235_bucket", "gtceu:vanadium_bucket", "gtceu:xenon_bucket", @@ -310,9 +310,9 @@ "gtceu:raw_growth_medium_bucket", "gtceu:sterilized_growth_medium_bucket", "gtceu:oil_bucket", - "gtceu:oil_heavy_bucket", - "gtceu:oil_medium_bucket", - "gtceu:oil_light_bucket", + "gtceu:heavy_oil_bucket", + "gtceu:raw_oil_bucket", + "gtceu:light_oil_bucket", "gtceu:natural_gas_bucket", "gtceu:bacteria_bucket", "gtceu:bacterial_sludge_bucket", diff --git a/src/generated/resources/data/forge/tags/items/armors/chestplates.json b/src/generated/resources/data/forge/tags/items/armors/chestplates.json index aad91e93fd..9435ea1359 100644 --- a/src/generated/resources/data/forge/tags/items/armors/chestplates.json +++ b/src/generated/resources/data/forge/tags/items/armors/chestplates.json @@ -7,7 +7,7 @@ "gtceu:liquid_fuel_jetpack", "gtceu:electric_jetpack", "gtceu:advanced_electric_jetpack", - "gtceu:avanced_nanomuscle_chestplate", + "gtceu:advanced_nanomuscle_chestplate", "gtceu:advanced_quarktech_chestplate" ] } \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/tags/items/ppe_armor.json b/src/generated/resources/data/gtceu/tags/items/ppe_armor.json index ec5f73fa99..bde19d498c 100644 --- a/src/generated/resources/data/gtceu/tags/items/ppe_armor.json +++ b/src/generated/resources/data/gtceu/tags/items/ppe_armor.json @@ -10,7 +10,7 @@ "gtceu:quarktech_leggings", "gtceu:quarktech_boots", "gtceu:quarktech_helmet", - "gtceu:avanced_nanomuscle_chestplate", + "gtceu:advanced_nanomuscle_chestplate", "gtceu:advanced_quarktech_chestplate" ] } \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/worldgen/configured_feature/raw_oil_sprout.json b/src/generated/resources/data/gtceu/worldgen/configured_feature/raw_oil_sprout.json index 9f7c63b09e..a274658f90 100644 --- a/src/generated/resources/data/gtceu/worldgen/configured_feature/raw_oil_sprout.json +++ b/src/generated/resources/data/gtceu/worldgen/configured_feature/raw_oil_sprout.json @@ -1,7 +1,7 @@ { "type": "gtceu:fluid_sprout", "config": { - "fluid": "gtceu:oil_medium", + "fluid": "gtceu:raw_oil", "size": { "type": "minecraft:uniform", "value": { diff --git a/src/generated/resources/data/minecraft/tags/blocks/replaceable.json b/src/generated/resources/data/minecraft/tags/blocks/replaceable.json index 51b1c7c9f3..be225f678b 100644 --- a/src/generated/resources/data/minecraft/tags/blocks/replaceable.json +++ b/src/generated/resources/data/minecraft/tags/blocks/replaceable.json @@ -1,9 +1,9 @@ { "values": [ "gtceu:oil", - "gtceu:oil_light", - "gtceu:oil_heavy", - "gtceu:oil_medium", + "gtceu:light_oil", + "gtceu:heavy_oil", + "gtceu:raw_oil", "gtceu:natural_gas" ] } \ No newline at end of file diff --git a/src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_heavy.png b/src/main/resources/assets/gtceu/textures/block/fluids/fluid.heavy_oil.png similarity index 100% rename from src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_heavy.png rename to src/main/resources/assets/gtceu/textures/block/fluids/fluid.heavy_oil.png diff --git a/src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_heavy.png.mcmeta b/src/main/resources/assets/gtceu/textures/block/fluids/fluid.heavy_oil.png.mcmeta similarity index 100% rename from src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_heavy.png.mcmeta rename to src/main/resources/assets/gtceu/textures/block/fluids/fluid.heavy_oil.png.mcmeta diff --git a/src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_light.png b/src/main/resources/assets/gtceu/textures/block/fluids/fluid.light_oil.png similarity index 100% rename from src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_light.png rename to src/main/resources/assets/gtceu/textures/block/fluids/fluid.light_oil.png diff --git a/src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_light.png.mcmeta b/src/main/resources/assets/gtceu/textures/block/fluids/fluid.light_oil.png.mcmeta similarity index 100% rename from src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_light.png.mcmeta rename to src/main/resources/assets/gtceu/textures/block/fluids/fluid.light_oil.png.mcmeta diff --git a/src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_medium.png b/src/main/resources/assets/gtceu/textures/block/fluids/fluid.raw_oil.png similarity index 100% rename from src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_medium.png rename to src/main/resources/assets/gtceu/textures/block/fluids/fluid.raw_oil.png diff --git a/src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_medium.png.mcmeta b/src/main/resources/assets/gtceu/textures/block/fluids/fluid.raw_oil.png.mcmeta similarity index 100% rename from src/main/resources/assets/gtceu/textures/block/fluids/fluid.oil_medium.png.mcmeta rename to src/main/resources/assets/gtceu/textures/block/fluids/fluid.raw_oil.png.mcmeta diff --git a/src/main/resources/assets/gtceu/textures/item/avanced_nanomuscle_chestplate.png b/src/main/resources/assets/gtceu/textures/item/advanced_nanomuscle_chestplate.png similarity index 100% rename from src/main/resources/assets/gtceu/textures/item/avanced_nanomuscle_chestplate.png rename to src/main/resources/assets/gtceu/textures/item/advanced_nanomuscle_chestplate.png From ee1b582bfe609e75791523d9bb39441d0fd8a00b Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Fri, 6 Sep 2024 09:16:30 +0300 Subject: [PATCH 35/70] y u no find blcok :wuh: --- .../renderer/pipe/util/ActivableCacheKey.java | 6 ++---- .../gtceu/forge/ForgeCommonEventListener.java | 13 +++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java index e7c0ad4a65..1d315b005c 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.client.renderer.pipe.util; +import lombok.Getter; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -8,6 +9,7 @@ @OnlyIn(Dist.CLIENT) public class ActivableCacheKey extends CacheKey { + @Getter private final boolean active; public ActivableCacheKey(float thickness, boolean active) { @@ -21,9 +23,5 @@ public static ActivableCacheKey of(@Nullable Float thickness, @Nullable Boolean return new ActivableCacheKey(thick, act); } - public boolean isActive() { - return active; - } - // activeness is merely a way to pass information onwards, it does not result in separate mappings. } diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index e0aa456ad1..6ee7b99ab1 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -27,6 +27,7 @@ import com.gregtechceu.gtceu.common.commands.MedicalConditionCommands; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTBlockEntities; +import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.common.data.GTMachines; import com.gregtechceu.gtceu.common.data.machines.GTAEMachines; @@ -473,6 +474,18 @@ public static void remapIds(MissingMappingsEvent event) { remapPipe(fluidPipe, mapping); }); } + event.getMappings(Registries.BLOCK, GTCEu.MOD_ID).forEach(mapping -> { + switch (mapping.getKey().getPath()) { + case "normal_laser_pipe" -> mapping.remap(GTBlocks.LASER_PIPE.get()); + case "normal_optical_pipe" -> mapping.remap(GTBlocks.OPTICAL_PIPE.get()); + } + }); + event.getMappings(Registries.ITEM, GTCEu.MOD_ID).forEach(mapping -> { + switch (mapping.getKey().getPath()) { + case "normal_laser_pipe" -> mapping.remap(GTBlocks.LASER_PIPE.get().asItem()); + case "normal_optical_pipe" -> mapping.remap(GTBlocks.OPTICAL_PIPE.get().asItem()); + } + }); event.getMappings(Registries.BLOCK_ENTITY_TYPE, GTCEu.MOD_ID).forEach(mapping -> { switch (mapping.getKey().getPath()) { case "cable", "fluid_pipe", "item_pipe" -> mapping.remap(GTBlockEntities.MATERIAL_PIPE.get()); From 1012107acf42017d0359641365bd84a8c145a011 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 7 Sep 2024 22:01:52 +0300 Subject: [PATCH 36/70] fix pipe renames + connections --- .../physical/tile/PipeBlockEntity.java | 18 +++- .../renderer/pipe/PipeModelRedirector.java | 12 ++- .../renderer/pipe/PipeModelRegistry.java | 8 +- .../common/data/datafixer/GTDataFixers.java | 49 ++++++----- .../datafixer/fixes/OilVariantsRenameFix.java | 6 ++ .../gtceu/core/mixins/BlockEntityMixin.java | 27 ++++++ .../gtceu/core/mixins/NbtUtilsMixin.java | 18 ++++ .../gtceu/forge/ForgeCommonEventListener.java | 84 ++++++++++++++++--- .../assets/gtceu/blockstates/cable.json | 7 ++ .../gtceu/blockstates/pipe_activable.json | 7 ++ .../gtceu/blockstates/pipe_material.json | 7 ++ src/main/resources/gtceu.mixins.json | 2 + 12 files changed, 205 insertions(+), 40 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java create mode 100644 src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java create mode 100644 src/main/resources/assets/gtceu/blockstates/cable.json create mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_activable.json create mode 100644 src/main/resources/assets/gtceu/blockstates/pipe_material.json diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index f0b72079c2..2356677044 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -33,9 +33,11 @@ import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.gui.editor.runtime.PersistedParser; import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; +import com.lowdragmc.lowdraglib.syncdata.ManagedFieldUtils; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; @@ -46,6 +48,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceKey; import net.minecraft.server.TickTask; @@ -81,10 +84,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.function.Consumer; public class PipeBlockEntity extends NeighborCacheBlockEntity @@ -351,6 +351,16 @@ public void clearRemoved() { } } + @Override + public void loadCustomPersistedData(CompoundTag tag) { + if (tag.contains("connections")) this.connectionMask = tag.getByte("connections"); + if (tag.contains("blockedConnections")) this.blockedMask = tag.getByte("blockedConnections"); + if (tag.contains("cover")) { + PersistedParser.deserializeNBT(tag.getCompound("cover"), new HashMap<>(), + PipeCoverHolder.class, this.coverHolder); + } + } + // activeness // @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java index 17708fc1c4..6482392c58 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.client.renderer.pipe.util.MaterialModelSupplier; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; @@ -67,7 +68,16 @@ public List getQuads(@Nullable BlockState state, @Nullable Direction @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType) { Material mat = data.get(AbstractPipeModel.MATERIAL_PROPERTY); - return supplier.getModel(mat).getQuads(state, side, rand, data, renderType); + if (mat == null && state != null && state.getBlock() instanceof MaterialPipeBlock block) { + mat = block.material; + } + AbstractPipeModel model = supplier.getModel(mat); + // this can happen when transferring old data, apparently. + //noinspection ConstantValue + if (model == null) { + return List.of(); + } + return model.getQuads(state, side, rand, data, renderType); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java index 68f1dd5e44..4e74ed09f3 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -55,7 +55,7 @@ public final class PipeModelRegistry { static { initPipes(); initCables(); - ResourceLocation loc = GTCEu.id("block/pipe_activable"); + ResourceLocation loc = GTCEu.id("pipe_activable"); OPTICAL = new ActivablePipeModel( new TextureInformation(GTCEu.id("block/pipe/pipe_optical_in"), -1), new TextureInformation(GTCEu.id("block/pipe/pipe_optical_side"), -1), @@ -71,7 +71,7 @@ public final class PipeModelRegistry { true); LASER_MODEL = new PipeModelRedirector(new ModelResourceLocation(loc, "laser"), m -> LASER, s -> null); DUCT = new DuctPipeModel(); - DUCT_MODEL = new PipeModelRedirector(new ModelResourceLocation(GTCEu.id("block/pipe_duct"), ""), m -> DUCT, + DUCT_MODEL = new PipeModelRedirector(new ModelResourceLocation(GTCEu.id("pipe_duct"), ""), m -> DUCT, s -> null); } @@ -195,7 +195,7 @@ private static void initPipes() { array[6] = new PipeModel(pipeNonuple, pipeSide, true); PIPE_RESTRICTIVE_OVERRIDES.addAndMoveToLast(new MaterialModelOverride.StandardOverride<>(array, m -> true)); - ResourceLocation loc = GTCEu.id("block/pipe_material"); + ResourceLocation loc = GTCEu.id("pipe_material"); for (int i = 0; i < PIPE_MODEL_COUNT; i++) { int finalI = i; PIPE_MODELS[i] = materialModel(loc, m -> getOrCachePipeModel(m, finalI), String.valueOf(i)); @@ -241,7 +241,7 @@ private static void initCables() { return new CableModel(material, CableModel.INSULATION[insulation - 1], CableModel.INSULATION_FULL); }, m -> true)); - ResourceLocation loc = GTCEu.id("block/cable"); + ResourceLocation loc = GTCEu.id("cable"); for (int i = 0; i < CABLE_MODEL_COUNT; i++) { int finalI = i; CABLE_MODELS[i] = materialModel(loc, m -> getOrCacheCableModel(m, finalI), String.valueOf(i)); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java index fc071633be..eb51b44f16 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java @@ -58,12 +58,18 @@ public static void addFixers(DataFixerBuilder builder) { builder.addFixer(ItemRenameFix.create(schemaV1, "advanced_nanomuscle_chestplate rename fix", createRenamer("gtceu:avanced_nanomuscle_chestplate", "gtceu:advanced_nanomuscle_chestplate"))); - builder.addFixer(ItemRenameFix.create(schemaV1, "U238 rename fix", - createRenamer(Pattern.compile("gtceu:uranium_"), "gtceu:uranium_238_"))); - builder.addFixer(ItemRenameFix.create(schemaV1, "Pu239 rename fix", - createRenamer(Pattern.compile("gtceu:plutonium_"), "gtceu:plutonium_239_"))); - builder.addFixer(ItemRenameFix.create(schemaV1, "Red granite rename fix", - createRenamer(Pattern.compile("gtceu:granite_red"), "gtceu:red_granite"))); + UnaryOperator renamer = createRenamer(Pattern.compile("gtceu:uranium_"), + "gtceu:uranium_238_"); + builder.addFixer(ItemRenameFix.create(schemaV1, "U238 item rename fix", renamer)); + builder.addFixer(BlockRenameFix.create(schemaV1, "U238 block rename fix", renamer)); + + renamer = createRenamer(Pattern.compile("gtceu:plutonium_"), "gtceu:plutonium_239_"); + builder.addFixer(BlockRenameFix.create(schemaV1, "Pu239 block rename fix", renamer)); + builder.addFixer(ItemRenameFix.create(schemaV1, "Pu239 item rename fix", renamer)); + + renamer = createRenamer(Pattern.compile("gtceu:granite_red"), "gtceu:red_granite"); + builder.addFixer(ItemRenameFix.create(schemaV1, "Red granite item rename fix", renamer)); + builder.addFixer(BlockRenameFix.create(schemaV1, "Red granite block rename fix", renamer)); builder.addFixer(ItemRenameFix.create(schemaV1, "Raw oil bucket rename fix", createRenamer(OilVariantsRenameFix.RENAMED_ITEM_IDS))); @@ -76,20 +82,25 @@ public static void addFixers(DataFixerBuilder builder) { builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:item_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:duct_pipe")); builder.addFixer(new PipeConnectionFix(schemaV2, false, "gtceu:laser_pipe")); - builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe block entities", References.BLOCK_ENTITY)); - builder.addFixer(ItemRenameFix.create(schemaV2, "Item pipe rename fix", - createRenamer(Pattern.compile("(.+?)_(.+?)_item_pipe"), "$2_$1_pipe"))); - builder.addFixer(ItemRenameFix.create(schemaV2, "Fluid pipe rename fix", - createRenamer(Pattern.compile("(.+?)_(.+?)_fluid_pipe"), "$2_$1_pipe"))); - builder.addFixer(BlockRenameFix.create(schemaV2, "Item pipe rename fix", - createRenamer(Pattern.compile("(.+?)_(.+?)_item_pipe"), "$2_$1_pipe"))); - builder.addFixer(BlockRenameFix.create(schemaV2, "Fluid pipe rename fix", - createRenamer(Pattern.compile("(.+?)_(.+?)_fluid_pipe"), "$2_$1_pipe"))); - builder.addFixer(BlockRenameFix.create(schemaV2, "Optical cable rename fix", - createRenamer("gtceu:normal_optical_pipe", "gtceu:optical_fiber_cable"))); - builder.addFixer(BlockRenameFix.create(schemaV2, "Laser cable rename fix", - createRenamer("gtceu:normal_laser_pipe", "gtceu:laser_pipe"))); builder.addFixer(new ActivablePipeConnectionFix(schemaV2, false, "gtceu:optical_pipe")); + builder.addFixer(new AddNewChoices(schemaV2, "Added generic pipe block entities", References.BLOCK_ENTITY)); + + renamer = createRenamer(Pattern.compile("([a-z]+_*[a-z]*)_([_\\w]+?)_item_pipe"), "$2_$1_pipe"); + builder.addFixer(ItemRenameFix.create(schemaV2, "Item pipe rename fix", renamer)); + builder.addFixer(BlockRenameFix.create(schemaV2, "Item pipe rename fix", renamer)); + + renamer = createRenamer(Pattern.compile("([a-z]+_*[a-z]*)_([_\\w]+?)_fluid_pipe"), "$2_$1_pipe"); + builder.addFixer(ItemRenameFix.create(schemaV2, "Fluid pipe rename fix", renamer)); + builder.addFixer(BlockRenameFix.create(schemaV2, "Fluid pipe rename fix", renamer)); + + renamer = createRenamer("gtceu:normal_optical_pipe", "gtceu:optical_fiber_cable"); + builder.addFixer(ItemRenameFix.create(schemaV2, "Optical cable rename fix", renamer)); + builder.addFixer(BlockRenameFix.create(schemaV2, "Optical cable rename fix", renamer)); + + renamer = createRenamer("gtceu:normal_laser_pipe", "gtceu:laser_pipe"); + builder.addFixer(ItemRenameFix.create(schemaV2, "Laser cable rename fix", renamer)); + builder.addFixer(BlockRenameFix.create(schemaV2, "Laser cable rename fix", renamer)); + builder.addFixer(BlockEntityRenameFix.create(schemaV2, "Pipe block entity rename fix", createRenamer(Map.of( "gtceu:cable", "gtceu:material_pipe", diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java index 88251ea955..de16a55653 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java @@ -13,6 +13,12 @@ public class OilVariantsRenameFix { .build(); public static final Map RENAMED_BLOCK_IDS = ImmutableMap.builder() + .put("gtceu:oil_heavy", "gtceu:heavy_oil") + .put("gtceu:oil_light", "gtceu:light_oil") + .put("gtceu:oil_medium", "gtceu:raw_oil") + .build(); + + public static final Map RENAMED_FLUID_IDS = ImmutableMap.builder() .put("gtceu:oil_heavy", "gtceu:heavy_oil") .put("gtceu:flowing_oil_heavy", "gtceu:flowing_heavy_oil") .put("gtceu:oil_light", "gtceu:light_oil") diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java new file mode 100644 index 0000000000..af54cf4df7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java @@ -0,0 +1,27 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.common.data.GTBlockEntities; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +// TODO figure out better solution??? forge doesn't want to remap BEs for w/e reason +@Mixin(BlockEntity.class) +public class BlockEntityMixin { + + @ModifyArg(method = "loadStatic", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/resources/ResourceLocation;tryParse(Ljava/lang/String;)Lnet/minecraft/resources/ResourceLocation;")) + private static String gtceu$remapBlockEntityLoadBecauseDataFixDoesntWantToWork(String s) { + switch (s) { + case "gtceu:cable", "gtceu:fluid_pipe", "gtceu:item_pipe" -> + s = GTBlockEntities.MATERIAL_PIPE.getId().toString(); + case "gtceu:laser_pipe", "gtceu:optical_pipe" -> + s = GTBlockEntities.ACTIVABLE_PIPE.getId().toString(); + case "gtceu:duct_pipe" -> + s = GTBlockEntities.PIPE.getId().toString(); + } + return s; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java new file mode 100644 index 0000000000..446172194e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java @@ -0,0 +1,18 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; +import com.llamalad7.mixinextras.injector.ModifyReturnValue; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(NbtUtils.class) +public class NbtUtilsMixin { + + @ModifyReturnValue(method = "addDataVersion", at = @At("RETURN")) + private static CompoundTag gtceu$addModDataVersion(CompoundTag tag) { + return DataFixesInternals.get().addModDataVersions(tag); + } + +} diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index 6ee7b99ab1..7020649e2f 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -31,6 +31,7 @@ import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.common.data.GTMachines; import com.gregtechceu.gtceu.common.data.machines.GTAEMachines; +import com.gregtechceu.gtceu.common.datafixer.fixes.OilVariantsRenameFix; import com.gregtechceu.gtceu.common.item.ToggleEnergyConsumerBehavior; import com.gregtechceu.gtceu.common.item.armor.IJetpack; import com.gregtechceu.gtceu.common.network.GTNetwork; @@ -80,11 +81,14 @@ import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.MissingMappingsEvent; +import net.minecraftforge.registries.RegistryManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -461,31 +465,49 @@ public static void remapIds(MissingMappingsEvent event) { }); // remap pipe blocks (uses the datafixer in 1.21) - final Pattern itemPipe = Pattern.compile("(.+?)_(.+?)_item_pipe"); - final Pattern fluidPipe = Pattern.compile("(.+?)_(.+?)_fluid_pipe"); for (MaterialRegistry registry : GTCEuAPI.materialManager.getRegistries()) { String namespace = registry.getModid(); event.getMappings(Registries.BLOCK, namespace).forEach(mapping -> { - remapPipe(itemPipe, mapping); - remapPipe(fluidPipe, mapping); + remapPipe(mapping); }); event.getMappings(Registries.ITEM, namespace).forEach(mapping -> { - remapPipe(itemPipe, mapping); - remapPipe(fluidPipe, mapping); + remapPipe(mapping); }); } event.getMappings(Registries.BLOCK, GTCEu.MOD_ID).forEach(mapping -> { switch (mapping.getKey().getPath()) { case "normal_laser_pipe" -> mapping.remap(GTBlocks.LASER_PIPE.get()); case "normal_optical_pipe" -> mapping.remap(GTBlocks.OPTICAL_PIPE.get()); + default -> { + remapMaterial(Pattern.compile("uranium"), "uranium_238", mapping); + remapMaterial(Pattern.compile("plutonium"), "plutonium_239", mapping); + remapMaterial(Pattern.compile("granite_red"), "red_granite", mapping); + remapMaterial(OilVariantsRenameFix.RENAMED_BLOCK_IDS, mapping); + } } }); event.getMappings(Registries.ITEM, GTCEu.MOD_ID).forEach(mapping -> { switch (mapping.getKey().getPath()) { - case "normal_laser_pipe" -> mapping.remap(GTBlocks.LASER_PIPE.get().asItem()); - case "normal_optical_pipe" -> mapping.remap(GTBlocks.OPTICAL_PIPE.get().asItem()); + case "normal_laser_pipe" -> mapping.remap(GTBlocks.LASER_PIPE.asItem()); + case "normal_optical_pipe" -> mapping.remap(GTBlocks.OPTICAL_PIPE.asItem()); + case "avanced_nanomuscle_chestplate" -> mapping.remap(GTItems.NANO_CHESTPLATE_ADVANCED.get()); + default -> { + remapMaterial(Pattern.compile("uranium"), "uranium_238", mapping); + remapMaterial(Pattern.compile("plutonium"), "plutonium_239", mapping); + remapMaterial(Pattern.compile("granite_red"), "red_granite", mapping); + remapMaterial(OilVariantsRenameFix.RENAMED_ITEM_IDS, mapping); + } } }); + event.getMappings(Registries.FLUID, GTCEu.MOD_ID).forEach(mapping -> { + remapMaterial(OilVariantsRenameFix.RENAMED_FLUID_IDS, mapping); + remapMaterial(Map.of( + "gtceu:uranium", "gtceu:uranium_238", + "gtceu:flowing_uranium", "gtceu:flowing_uranium_238", + "gtceu:plutonium", "gtceu:plutonium_238", + "gtceu:flowing_plutonium", "gtceu:flowing_plutonium_238" + ), mapping); + }); event.getMappings(Registries.BLOCK_ENTITY_TYPE, GTCEu.MOD_ID).forEach(mapping -> { switch (mapping.getKey().getPath()) { case "cable", "fluid_pipe", "item_pipe" -> mapping.remap(GTBlockEntities.MATERIAL_PIPE.get()); @@ -495,13 +517,51 @@ public static void remapIds(MissingMappingsEvent event) { }); } - private static void remapPipe(Pattern pattern, MissingMappingsEvent.Mapping mapping) { + private static void remapPipe(MissingMappingsEvent.Mapping mapping) { + String namespace = mapping.getKey().getNamespace(); + String path = mapping.getKey().getPath(); + if (path.contains("_pipe")) { + StringBuilder result; + boolean restrictive = path.contains("restrictive"); + boolean fluid = path.contains("fluid"); + String[] split = path.substring(0, path.length() - (fluid ? 11 : 10)).split("_"); + if (restrictive) { + result = new StringBuilder(split[split.length - 2] + "_" + split[split.length - 1]); + for (int i = 0; i < split.length - 2; ++i) { + result.append("_").append(split[i]); + } + } else { + result = new StringBuilder(split[split.length - 1]); + for (int i = 0; i < split.length - 1; ++i) { + result.append("_").append(split[i]); + } + } + result.append("_pipe"); + + ResourceLocation newBlock = new ResourceLocation(namespace, result.toString()); + IForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(mapping.getRegistry().getRegistryKey()); + mapping.remap(registry.getValue(newBlock)); + } + } + + private static void remapMaterial(Pattern pattern, String replacement, MissingMappingsEvent.Mapping mapping) { String namespace = mapping.getKey().getNamespace(); String path = mapping.getKey().getPath(); Matcher match = pattern.matcher(path); - if (match.matches()) { - ResourceLocation newBlock = new ResourceLocation(namespace, match.replaceAll("$2_$1_pipe")); - mapping.remap(mapping.getRegistry().getValue(newBlock)); + String replaced = match.replaceAll(replacement); + if (!path.equals(replaced)) { + ResourceLocation newBlock = new ResourceLocation(namespace, replaced); + IForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(mapping.getRegistry().getRegistryKey()); + mapping.remap(registry.getValue(newBlock)); + } + } + + private static void remapMaterial(Map renameMap, MissingMappingsEvent.Mapping mapping) { + String newName = renameMap.get(mapping.getKey().toString()); + if (newName != null) { + ResourceLocation newBlock = new ResourceLocation(newName); + IForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(mapping.getRegistry().getRegistryKey()); + mapping.remap(registry.getValue(newBlock)); } } } diff --git a/src/main/resources/assets/gtceu/blockstates/cable.json b/src/main/resources/assets/gtceu/blockstates/cable.json new file mode 100644 index 0000000000..9357c18147 --- /dev/null +++ b/src/main/resources/assets/gtceu/blockstates/cable.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "gtceu:block/cube/all" + } + } +} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_activable.json b/src/main/resources/assets/gtceu/blockstates/pipe_activable.json new file mode 100644 index 0000000000..9357c18147 --- /dev/null +++ b/src/main/resources/assets/gtceu/blockstates/pipe_activable.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "gtceu:block/cube/all" + } + } +} diff --git a/src/main/resources/assets/gtceu/blockstates/pipe_material.json b/src/main/resources/assets/gtceu/blockstates/pipe_material.json new file mode 100644 index 0000000000..9357c18147 --- /dev/null +++ b/src/main/resources/assets/gtceu/blockstates/pipe_material.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "gtceu:block/cube/all" + } + } +} diff --git a/src/main/resources/gtceu.mixins.json b/src/main/resources/gtceu.mixins.json index 0eef6cb1fd..1718b0fda8 100644 --- a/src/main/resources/gtceu.mixins.json +++ b/src/main/resources/gtceu.mixins.json @@ -22,6 +22,7 @@ "mixins": [ "AbstractRegistrateAccessor", "BlockBehaviourAccessor", + "BlockEntityMixin", "BlockMixin", "BlockPropertiesAccessor", "ChunkGeneratorMixin", @@ -41,6 +42,7 @@ "LivingEntityMixin", "LootDataManagerMixin", "LootPoolAccessor", + "NbtUtilsMixin", "OreConfigurationMixin", "OreVeinifierMixin", "PartialNBTIngredientAccessor", From f513a1de12d55b466b2a73e02cdd19aa7f63c0af Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sat, 7 Sep 2024 22:17:18 +0300 Subject: [PATCH 37/70] add methods to IGTAddon for loading client data, tags and loot tables dynamically --- .../gregtechceu/gtceu/api/addon/IGTAddon.java | 22 +++++++++++++++++++ .../gregtechceu/gtceu/core/MixinHelpers.java | 10 ++++++--- .../gtceu/core/mixins/ModelManagerMixin.java | 3 +++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java index 7aa4eb4571..e810f01d1e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java +++ b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java @@ -6,9 +6,15 @@ import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; import com.gregtechceu.gtceu.common.data.GTOres; +import net.minecraft.core.Registry; +import net.minecraft.data.loot.packs.VanillaBlockLoot; import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.level.storage.loot.LootTable; +import java.util.List; +import java.util.Map; import java.util.function.Consumer; @SuppressWarnings("unused") @@ -85,6 +91,22 @@ default void addRecipes(Consumer provider) {} default void removeRecipes(Consumer consumer) {} + /** + * Use this to load client data like models and block states dynamically. + */ + default void loadDynamicResources() {} + + /** + * Use this to load loot tables dynamically. + */ + default void loadDynamicLoot(Map lootTables, VanillaBlockLoot vanillaBlockLoot) {} + + /** + * Use this to load tags dynamically. + */ + default void loadDynamicTags(Map> tagMap, + Registry registry) {} + /** * Use {@link GTOres#create(ResourceLocation, Consumer)} to register the veins. */ diff --git a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java index be3aa8f63f..77a46eb0f8 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java @@ -2,6 +2,8 @@ import com.gregtechceu.gtceu.api.GTCEuAPI; import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.api.addon.AddonFinder; +import com.gregtechceu.gtceu.api.addon.IGTAddon; import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidProperty; @@ -57,8 +59,8 @@ public class MixinHelpers { - public static void generateGTDynamicTags(Map> tagMap, - Registry registry) { + public static void generateGTDynamicTags(final Map> tagMap, + final Registry registry) { if (registry == BuiltInRegistries.ITEM) { ChemicalHelper.UNIFICATION_ENTRY_ITEM.forEach((entry, itemLikes) -> { if (itemLikes.isEmpty()) return; @@ -146,6 +148,7 @@ public static void generateGTDynamicTags(Map addon.loadDynamicTags(tagMap, registry)); } public static void addMaterialBlockTags(Map> tagMap, @@ -186,7 +189,7 @@ public static void addMaterialBlockTags(Map lootTables) { + public static void generateGTDynamicLoot(final Map lootTables) { GTBlocks.MATERIAL_BLOCKS.rowMap().forEach((prefix, map) -> { if (TagPrefix.ORES.containsKey(prefix)) { final TagPrefix.OreType type = TagPrefix.ORES.get(prefix); @@ -262,6 +265,7 @@ public static void generateGTDynamicLoot(Map lootTa lootTables.put(lootTableId, BLOCK_LOOT.createSingleItemTable(block).setParamSet(LootContextParamSets.BLOCK).build()); }); + AddonFinder.getAddons().forEach(addon -> addon.loadDynamicLoot(lootTables, BLOCK_LOOT)); } public static void addMaterialBlockLootTables(Map lootTables, TagPrefix prefix, diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java index 465cd5fc3a..f2318872f9 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/ModelManagerMixin.java @@ -1,6 +1,8 @@ package com.gregtechceu.gtceu.core.mixins; import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.addon.AddonFinder; +import com.gregtechceu.gtceu.api.addon.IGTAddon; import com.gregtechceu.gtceu.client.renderer.block.MaterialBlockRenderer; import com.gregtechceu.gtceu.client.renderer.block.OreBlockRenderer; import com.gregtechceu.gtceu.client.renderer.block.SurfaceRockRenderer; @@ -41,6 +43,7 @@ public abstract class ModelManagerMixin { SurfaceRockRenderer.reinitModels(); GTModels.registerMaterialFluidModels(); GTModels.registerPipeModels(); + AddonFinder.getAddons().forEach(IGTAddon::loadDynamicResources); GTCEu.LOGGER.info("GregTech Model loading took {}ms", System.currentTimeMillis() - startTime); } } From 3c595db01d9496de607b55b20e71b05a38dea03a Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 8 Sep 2024 00:18:35 +0300 Subject: [PATCH 38/70] would you rather have infinite bloom but no cables or cables, infinite cables, but no cables? --- .../api/graphnet/logic/NetLogicRegistry.java | 8 +-- .../physical/block/MaterialPipeBlockItem.java | 14 +++++ .../physical/block/PipeMaterialBlock.java | 6 ++ .../renderer/pipe/cache/ActivableSQC.java | 9 ++- .../renderer/pipe/cache/BlockableSQC.java | 7 +-- .../renderer/pipe/cache/ColorQuadCache.java | 9 ++- .../renderer/pipe/cache/ExtraCappedSQC.java | 7 +-- .../renderer/pipe/cache/RestrictiveSQC.java | 7 +-- .../pipe/cache/StructureQuadCache.java | 13 ++--- .../pipe/cover/CoverRendererBuilder.java | 5 +- .../renderer/pipe/quad/PipeQuadHelper.java | 21 +++---- .../client/renderer/pipe/quad/QuadHelper.java | 2 +- .../pipe/quad/RecolorableBakedQuad.java | 56 ------------------- .../gtceu/client/util/StaticFaceBakery.java | 9 +-- .../gtceu/common/data/GTBlocks.java | 4 +- .../pipelike/block/cable/CableBlock.java | 11 ++++ .../block/pipe/MaterialPipeBlock.java | 27 +++++++++ 17 files changed, 101 insertions(+), 114 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index 18b6407467..37931b5a5e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -51,9 +51,7 @@ protected EmptyLogicEntry() { } @Override - public void deserializeNBT(Tag arg) { - throw new RuntimeException("Can't deserialize empty logic entry!"); - } + public void deserializeNBT(Tag arg) {} @Override public void encode(FriendlyByteBuf buf, boolean fullChange) { @@ -61,8 +59,6 @@ public void encode(FriendlyByteBuf buf, boolean fullChange) { } @Override - public void decode(FriendlyByteBuf buf, boolean fullChange) { - throw new RuntimeException("Can't deserialize empty logic entry!"); - } + public void decode(FriendlyByteBuf buf, boolean fullChange) {} } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index e1f5f40578..251d22610d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -2,10 +2,13 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; +import net.minecraft.client.color.item.ItemColor; import net.minecraft.network.chat.Component; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; public class MaterialPipeBlockItem extends PipeBlockItem { @@ -39,4 +42,15 @@ public String getDescriptionId() { return material == null ? "unnamed" : getBlock().getStructure().getPrefix().getUnlocalizedName(material); } + + @OnlyIn(Dist.CLIENT) + public static ItemColor tintColor() { + return (itemStack, index) -> { + if (itemStack.getItem() instanceof MaterialPipeBlockItem materialBlockItem) { + return materialBlockItem.getBlock().tinted(materialBlockItem.getBlock().defaultBlockState(), null, null, + index); + } + return -1; + }; + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index cafb404c07..3939ad2c27 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -13,6 +13,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; @@ -34,6 +35,11 @@ public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStru this.material = material; } + public int tinted(BlockState blockState, @Nullable BlockAndTintGetter blockAndTintGetter, + @Nullable BlockPos blockPos, int index) { + return index == 0 || index == 1 ? material.getMaterialRGB() : -1; + } + @Nullable public static PipeMaterialBlock getBlockFromItem(@NotNull ItemStack stack) { if (stack.getItem() instanceof MaterialPipeBlockItem block) return block.getBlock(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java index 22da82c754..819fd513e8 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ActivableSQC.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; @@ -46,14 +45,14 @@ protected ActivableSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteIn } @Override - protected List buildPrototypeInternal() { - List quads = super.buildPrototypeInternal(); + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); buildOverlay(quads); buildOverlayActive(quads); return quads; } - protected void buildOverlay(List list) { + protected void buildOverlay(List list) { helper.setTargetSprite(overlayTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); @@ -62,7 +61,7 @@ protected void buildOverlay(List list) { } } - protected void buildOverlayActive(List list) { + protected void buildOverlayActive(List list) { helper.setTargetSprite(overlayActiveTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java index 0455b4ddf9..ab42f805db 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; @@ -39,13 +38,13 @@ protected BlockableSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteIn } @Override - protected List buildPrototypeInternal() { - List quads = super.buildPrototypeInternal(); + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); buildBlocked(quads); return quads; } - protected void buildBlocked(List list) { + protected void buildBlocked(List list) { helper.setTargetSprite(blockedTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java index 3ee4058f31..541aed90fc 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.client.renderer.pipe.cache; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -15,11 +14,11 @@ @OnlyIn(Dist.CLIENT) public final class ColorQuadCache { - private final List prototypes; + private final List prototypes; private final Object2ObjectLinkedOpenHashMap> cache; - public ColorQuadCache(List prototypes) { + public ColorQuadCache(List prototypes) { this.prototypes = prototypes; this.cache = new Object2ObjectLinkedOpenHashMap<>(); } @@ -28,8 +27,8 @@ public List getQuads(ColorData data) { List existing = cache.get(data); if (existing == null) { existing = new ObjectArrayList<>(); - for (RecolorableBakedQuad quad : prototypes) { - existing.add(quad.withColor(data)); + for (BakedQuad quad : prototypes) { + existing.add(quad); } cache.put(data, existing); // if (cache.size() > 20) cache.removeLast(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java index 0bf4039158..1e4558cea0 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ExtraCappedSQC.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; @@ -42,13 +41,13 @@ protected ExtraCappedSQC(PipeQuadHelper helper, SpriteInformation endTex, Sprite } @Override - protected List buildPrototypeInternal() { - List quads = super.buildPrototypeInternal(); + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); buildExtraCapper(quads); return quads; } - protected void buildExtraCapper(List list) { + protected void buildExtraCapper(List list) { helper.setTargetSprite(extraEndTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java index 6ee8dd73ce..e07bd5a8af 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; @@ -43,13 +42,13 @@ protected RestrictiveSQC(PipeQuadHelper helper, SpriteInformation endTex, Sprite } @Override - protected List buildPrototypeInternal() { - List quads = super.buildPrototypeInternal(); + protected List buildPrototypeInternal() { + List quads = super.buildPrototypeInternal(); buildRestrictive(quads); return quads; } - protected void buildRestrictive(List list) { + protected void buildRestrictive(List list) { helper.setTargetSprite(restrictiveTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java index b1c89b646b..0933a5c060 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/StructureQuadCache.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.client.renderer.pipe.cache; import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; @@ -55,8 +54,8 @@ protected void buildPrototype() { this.cache = new ColorQuadCache(this.buildPrototypeInternal()); } - protected List buildPrototypeInternal() { - List quads = new ObjectArrayList<>(); + protected List buildPrototypeInternal() { + List quads = new ObjectArrayList<>(); buildTube(quads); buildCore(quads); buildCapper(quads); @@ -64,7 +63,7 @@ protected List buildPrototypeInternal() { return quads; } - protected void buildTube(List list) { + protected void buildTube(List list) { helper.setTargetSprite(sideTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); @@ -73,7 +72,7 @@ protected void buildTube(List list) { } } - protected void buildCore(List list) { + protected void buildCore(List list) { helper.setTargetSprite(sideTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); @@ -82,7 +81,7 @@ protected void buildCore(List list) { } } - protected void buildCapper(List list) { + protected void buildCapper(List list) { helper.setTargetSprite(endTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); @@ -91,7 +90,7 @@ protected void buildCapper(List list) { } } - protected void buildCapperClosed(List list) { + protected void buildCapperClosed(List list) { helper.setTargetSprite(sideTex); for (Direction facing : GTUtil.DIRECTIONS) { int start = list.size(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java index c68eef40ed..3b9bdc492e 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cover/CoverRendererBuilder.java @@ -5,7 +5,6 @@ import com.gregtechceu.gtceu.client.renderer.pipe.cache.ColorQuadCache; import com.gregtechceu.gtceu.client.renderer.pipe.cache.SubListAddress; import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; import com.gregtechceu.gtceu.client.renderer.pipe.quad.UVMapper; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; @@ -74,14 +73,14 @@ public class CoverRendererBuilder { } public static ColorQuadCache buildPlates(SpriteInformation sprite) { - List quads = new ObjectArrayList<>(); + List quads = new ObjectArrayList<>(); for (Direction facing : GTUtil.DIRECTIONS) { PLATE_COORDS.put(facing, buildPlates(quads, facing, sprite)); } return new ColorQuadCache(quads); } - protected static SubListAddress buildPlates(List quads, Direction facing, + protected static SubListAddress buildPlates(List quads, Direction facing, SpriteInformation sprite) { int start = quads.size(); Pair box = PLATE_BOXES.get(facing); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java index 565ba67612..d4aeabb9ca 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; +import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; import net.minecraftforge.api.distmarker.Dist; @@ -89,20 +90,20 @@ public void setTargetSprite(SpriteInformation sprite) { this.targetSprite = sprite; } - public @NotNull RecolorableBakedQuad visitCore(Direction facing) { + public @NotNull BakedQuad visitCore(Direction facing) { return visitCore(facing, 0); } - public @NotNull RecolorableBakedQuad visitCore(Direction facing, int overlayLayer) { + public @NotNull BakedQuad visitCore(Direction facing, int overlayLayer) { return visitQuad(facing, coreBoxList.get(overlayLayer), UVMapper.standard(0)); } - public @NotNull List visitTube(Direction facing) { + public @NotNull List visitTube(Direction facing) { return visitTube(facing, 0); } - public @NotNull List visitTube(Direction facing, int overlayLayer) { - List list = new ObjectArrayList<>(); + public @NotNull List visitTube(Direction facing, int overlayLayer) { + List list = new ObjectArrayList<>(); Pair box = sideBoxesList.get(overlayLayer).get(facing); switch (facing.getAxis()) { case X -> { @@ -127,22 +128,22 @@ public void setTargetSprite(SpriteInformation sprite) { return list; } - public @NotNull RecolorableBakedQuad visitCapper(Direction facing) { + public @NotNull BakedQuad visitCapper(Direction facing) { return visitCapper(facing, 0); } - public @NotNull RecolorableBakedQuad visitCapper(Direction facing, int overlayLayer) { + public @NotNull BakedQuad visitCapper(Direction facing, int overlayLayer) { return visitQuad(facing, sideBoxesList.get(overlayLayer).get(facing), UVMapper.standard(0)); } - public @NotNull RecolorableBakedQuad visitQuad(Direction normal, Pair box, UVMapper uv) { + public @NotNull BakedQuad visitQuad(Direction normal, Pair box, UVMapper uv) { return QuadHelper.buildQuad(normal, box, uv, targetSprite); } - public static @NotNull List createFrame(TextureAtlasSprite sprite) { + public static @NotNull List createFrame(TextureAtlasSprite sprite) { PipeQuadHelper helper = PipeQuadHelper.create(0.998f).initialize(); helper.setTargetSprite(new SpriteInformation(sprite, 0)); - List list = new ObjectArrayList<>(); + List list = new ObjectArrayList<>(); for (Direction facing : GTUtil.DIRECTIONS) { list.add(helper.visitCore(facing)); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java index 638a1b86cd..bc0759362c 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -25,7 +25,7 @@ public final class QuadHelper { private QuadHelper() {} - public static @NotNull RecolorableBakedQuad buildQuad(Direction normal, Pair box, + public static @NotNull BakedQuad buildQuad(Direction normal, Pair box, @NotNull UVMapper uv, @NotNull SpriteInformation targetSprite) { BlockElementFace face = new BlockElementFace(null, -1, targetSprite.sprite().contents().name().toString(), diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java deleted file mode 100644 index 3f7b5faf55..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/RecolorableBakedQuad.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.pipe.quad; - -import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; -import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; - -import java.util.Arrays; - -import static net.minecraftforge.client.model.IQuadTransformer.*; - -@MethodsReturnNonnullByDefault -@OnlyIn(Dist.CLIENT) -public class RecolorableBakedQuad extends BakedQuad { - - private final Int2ObjectOpenHashMap cache; - private final SpriteInformation spriteInformation; - - /** - * Create a new recolorable quad based off of a baked quad prototype. - * - * @param prototype the prototype. - * @param spriteInformation the sprite information of this baked quad. - */ - public RecolorableBakedQuad(BakedQuad prototype, SpriteInformation spriteInformation) { - this(prototype, prototype.getTintIndex(), spriteInformation, new Int2ObjectOpenHashMap<>()); - } - - protected RecolorableBakedQuad(BakedQuad prototype, int tintIndex, - SpriteInformation spriteInformation, - Int2ObjectOpenHashMap cache) { - super(Arrays.copyOf(prototype.getVertices(), prototype.getVertices().length), tintIndex, - prototype.getDirection(), spriteInformation.sprite(), - prototype.isShade(), prototype.hasAmbientOcclusion()); - this.spriteInformation = spriteInformation; - this.cache = cache; - } - - /** - * Get a recolorable quad based off of this quad but aligned with the given color data. - * - * @param data the color data. - * @return a quad colored based on the color data. - */ - public RecolorableBakedQuad withColor(ColorData data) { - if (!spriteInformation.colorable()) return this; - int argb = data.colorsARGB()[spriteInformation.colorID()]; - return cache.computeIfAbsent(argb, - (c) -> new RecolorableBakedQuad(this, c, this.spriteInformation, this.cache)); - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java index 4b5000f779..ed7d74a5e9 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java @@ -1,7 +1,5 @@ package com.gregtechceu.gtceu.client.util; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.RecolorableBakedQuad; -import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.lowdragmc.lowdraglib.client.bakedpipeline.FaceQuad; @@ -136,8 +134,7 @@ public static BakedQuad bakeQuad( return quad; } - public static RecolorableBakedQuad bakeRecolorableQuad( - Vector3f posFrom, + public static BakedQuad bakeRecolorableQuad(Vector3f posFrom, Vector3f posTo, BlockElementFace face, SpriteInformation sprite, @@ -171,9 +168,7 @@ public static RecolorableBakedQuad bakeRecolorableQuad( ForgeHooksClient.fillNormal(aint, direction); ForgeFaceData data = face.getFaceData(); - RecolorableBakedQuad quad = new RecolorableBakedQuad( - new BakedQuad(aint, face.tintIndex, direction, sprite.sprite(), shade, data.ambientOcclusion()), - sprite); + BakedQuad quad = new BakedQuad(aint, sprite.colorID(), direction, sprite.sprite(), shade, data.ambientOcclusion()); if (!ForgeFaceData.DEFAULT.equals(data)) { QuadTransformers.applyingLightmap(data.blockLight(), data.skyLight()).processInPlace(quad); QuadTransformers.applyingColor(data.color()).processInPlace(quad); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index d10b7fa049..7649154ce5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -379,10 +379,10 @@ private static void registerMaterialPipeBlock(Material material, MaterialPipeStr .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) - .color(() -> () -> (state, level, pos, color) -> color) + .color(() -> MaterialPipeBlock::tintedColor) .item(MaterialPipeBlockItem::new) .model(NonNullBiConsumer.noop()) - .color(() -> () -> (stack, color) -> color) + .color(() -> MaterialPipeBlockItem::tintColor) .build() .register(); MATERIAL_PIPE_BLOCKS_BUILDER.put(pipeType.prefix(), material, entry); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index ddb01beff8..b822181ef7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -6,6 +6,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; +import com.gregtechceu.gtceu.client.renderer.pipe.CableModel; import com.gregtechceu.gtceu.common.data.GTDamageTypes; import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowData; import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; @@ -19,11 +20,13 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.Nullable; import java.util.Map; @@ -40,6 +43,14 @@ public CableBlock(BlockBehaviour.Properties properties, CableStructure structure }); } + public int tinted(BlockState blockState, @Nullable BlockAndTintGetter blockAndTintGetter, + @Nullable BlockPos blockPos, int index) { + if (getStructure().isInsulated() && index == 0) { + return CableModel.DEFAULT_INSULATION_COLOR; + } + return index == 0 ? material.getMaterialRGB() : -1; + } + @Override public CableStructure getStructure() { return (CableStructure) super.getStructure(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java index 7ed02d226b..1a7fe29a9c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -5,7 +5,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import net.minecraft.client.color.block.BlockColor; import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, IFreezable { @@ -17,4 +21,27 @@ public MaterialPipeBlock(BlockBehaviour.Properties properties, MaterialPipeStruc public MaterialPipeStructure getStructure() { return (MaterialPipeStructure) super.getStructure(); } + + @OnlyIn(Dist.CLIENT) + public static BlockColor tintedColor() { + return (blockState, level, blockPos, index) -> { + if (blockState.getBlock() instanceof MaterialPipeBlock block) { + if (blockPos != null && level != null && + level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { + if (pipe.getFrameMaterial() != null) { + if (index == 3) { + return pipe.getFrameMaterial().getMaterialRGB(); + } else if (index == 4) { + return pipe.getFrameMaterial().getMaterialSecondaryRGB(); + } + } + if (index == 0 && pipe.isPainted()) { + return pipe.getPaintingColor(); + } + } + return block.tinted(blockState, level, blockPos, index); + } + return -1; + }; + } } From d3b5f919029452596bbb2d7ee3f336532560f460 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Mon, 9 Sep 2024 09:00:53 +0300 Subject: [PATCH 39/70] fix cable colors (it was simple), support all colors on frame boxes, fix bloom issue (slight regression, TODO figure out better solution) --- .../physical/block/MaterialPipeBlockItem.java | 2 +- .../physical/block/PipeMaterialBlock.java | 24 ++++++++++++++++ .../physical/tile/PipeBlockEntity.java | 1 - .../renderer/pipe/AbstractPipeModel.java | 13 +++++---- .../renderer/pipe/ActivablePipeModel.java | 12 +++++--- .../client/renderer/pipe/PipeItemModel.java | 2 +- .../renderer/pipe/PipeModelRedirector.java | 4 +-- .../renderer/pipe/PipeModelRegistry.java | 1 - .../renderer/pipe/quad/PipeQuadHelper.java | 25 +++++++++++------ .../client/renderer/pipe/quad/QuadHelper.java | 3 +- .../renderer/pipe/util/ActivableCacheKey.java | 2 +- .../gtceu/client/util/StaticFaceBakery.java | 19 +++++++------ .../gtceu/common/data/GTBlocks.java | 7 +++-- .../common/data/datafixer/GTDataFixers.java | 5 ++-- .../datafixer/fixes/PipeConnectionFix.java | 28 ++++++++++--------- .../gtceu/common/datafixer/schemas/V0.java | 3 +- .../block/pipe/MaterialPipeBlock.java | 26 ----------------- .../gregtechceu/gtceu/core/MixinHelpers.java | 1 - .../gtceu/core/mixins/BlockEntityMixin.java | 14 +++++----- .../gtceu/core/mixins/NbtUtilsMixin.java | 5 ++-- .../gtceu/forge/ForgeCommonEventListener.java | 8 +++--- 21 files changed, 109 insertions(+), 96 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java index 251d22610d..93c466e70b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/MaterialPipeBlockItem.java @@ -6,9 +6,9 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; public class MaterialPipeBlockItem extends PipeBlockItem { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index 3939ad2c27..e36155ecb6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -9,6 +9,7 @@ import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.config.ConfigHolder; +import net.minecraft.client.color.block.BlockColor; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; @@ -19,6 +20,8 @@ import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,6 +38,27 @@ public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStru this.material = material; } + @OnlyIn(Dist.CLIENT) + public static BlockColor tintedColor() { + return (blockState, level, blockPos, index) -> { + if (blockState.getBlock() instanceof PipeMaterialBlock block) { + if (blockPos != null && level != null && + level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { + if (pipe.getFrameMaterial() != null) { + if (index >= 3) { + return pipe.getFrameMaterial().getMaterialRGB(index - 3); + } + } + if (index == 0 && pipe.isPainted()) { + return pipe.getPaintingColor(); + } + } + return block.tinted(blockState, level, blockPos, index); + } + return -1; + }; + } + public int tinted(BlockState blockState, @Nullable BlockAndTintGetter blockAndTintGetter, @Nullable BlockPos blockPos, int index) { return index == 0 || index == 1 ? material.getMaterialRGB() : -1; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 2356677044..cb2c9b2a67 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -37,7 +37,6 @@ import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import com.lowdragmc.lowdraglib.syncdata.IEnhancedManaged; import com.lowdragmc.lowdraglib.syncdata.IManagedStorage; -import com.lowdragmc.lowdraglib.syncdata.ManagedFieldUtils; import com.lowdragmc.lowdraglib.syncdata.annotation.DescSynced; import com.lowdragmc.lowdraglib.syncdata.annotation.Persisted; import com.lowdragmc.lowdraglib.syncdata.blockentity.IAsyncAutoSyncBlockEntity; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index cc95730e0b..a255d5e040 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -17,11 +17,11 @@ import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; @@ -80,7 +80,8 @@ public AbstractPipeModel() { List quads = getQuads(toKey(modelData), safeByte(modelData.get(CONNECTED_MASK_PROPERTY)), safeByte(modelData.get(CLOSED_MASK_PROPERTY)), safeByte(modelData.get(BLOCKED_MASK_PROPERTY)), data, modelData.get(FRAME_MATERIAL_PROPERTY), - safeByte(modelData.get(FRAME_MASK_PROPERTY)), coverMask); + safeByte(modelData.get(FRAME_MASK_PROPERTY)), coverMask, + rand, modelData, renderType); if (rendererPackage != null) renderCovers(quads, rendererPackage, rand, modelData, renderType); return quads; } @@ -117,7 +118,8 @@ protected static int safeInt(@Nullable Integer integer) { public @NotNull List getQuads(K key, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, - @Nullable Material frameMaterial, byte frameMask, byte coverMask) { + @Nullable Material frameMaterial, byte frameMask, byte coverMask, + RandomSource randomSource, ModelData modelData, RenderType renderType) { List quads = new ObjectArrayList<>(); StructureQuadCache cache = pipeCache.computeIfAbsent(key, this::constructForKey); @@ -125,12 +127,13 @@ protected static int safeInt(@Nullable Integer integer) { blockedMask, data, coverMask); if (frameMaterial != null) { - ResourceLocation rl = MaterialIconType.frameGt.getBlockTexturePath(frameMaterial.getMaterialIconSet(), + ResourceLocation rl = MaterialIconType.frameGt.getBlockModelPath(frameMaterial.getMaterialIconSet(), true); ColorQuadCache frame = frameCache.get(rl); if (frame == null) { + BakedModel model = Minecraft.getInstance().getModelManager().getModel(rl); frame = new ColorQuadCache(PipeQuadHelper - .createFrame(Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(rl))); + .createFrame(model, randomSource, modelData, renderType)); frameCache.put(rl, frame); } List frameQuads = frame diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java index 1c92e2da02..96ebfa74fd 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -16,7 +16,9 @@ import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.util.RandomSource; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; @@ -59,11 +61,13 @@ public ActivablePipeModel(@NotNull TextureInformation inTex, } @Override - public @NotNull List getQuads(ActivableCacheKey key, byte connectionMask, byte closedMask, - byte blockedMask, ColorData data, @Nullable Material frameMaterial, - byte frameMask, byte coverMask) { + public @NotNull List getQuads(ActivableCacheKey key, + byte connectionMask, byte closedMask, byte blockedMask, + ColorData data, @Nullable Material frameMaterial, + byte frameMask, byte coverMask, + RandomSource randomSource, ModelData modelData, RenderType renderType) { List quads = super.getQuads(key, connectionMask, closedMask, blockedMask, data, frameMaterial, - frameMask, coverMask); + frameMask, coverMask, randomSource, modelData, renderType); if (key.isActive() && allowActive()) { if (emissiveActive) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java index bd35330498..c63e28ac66 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeItemModel.java @@ -68,7 +68,7 @@ public PipeItemModel(PipeModelRedirector redirector, AbstractPipeModel basis, @NotNull RandomSource rand, @NotNull ModelData modelData, @Nullable RenderType renderType) { byte z = 0; - return basis.getQuads(key, (byte) 0b1100, z, z, data, null, z, z); + return basis.getQuads(key, (byte) 0b1100, z, z, data, null, z, z, rand, modelData, renderType); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java index 6482392c58..44fa90088a 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java @@ -3,8 +3,8 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.client.renderer.pipe.util.MaterialModelSupplier; - import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeBlock; + import com.lowdragmc.lowdraglib.client.model.ModelFactory; import net.minecraft.client.multiplayer.ClientLevel; @@ -73,7 +73,7 @@ public List getQuads(@Nullable BlockState state, @Nullable Direction } AbstractPipeModel model = supplier.getModel(mat); // this can happen when transferring old data, apparently. - //noinspection ConstantValue + // noinspection ConstantValue if (model == null) { return List.of(); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java index 4e74ed09f3..b2b94fa443 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -23,7 +23,6 @@ import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; -import java.util.Objects; import java.util.function.BiConsumer; public final class PipeModelRegistry { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java index d4aeabb9ca..4cd2898983 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -1,13 +1,17 @@ package com.gregtechceu.gtceu.client.renderer.pipe.quad; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; -import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.client.bakedpipeline.Quad; + +import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.model.data.ModelData; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.apache.commons.lang3.tuple.Pair; @@ -140,13 +144,18 @@ public void setTargetSprite(SpriteInformation sprite) { return QuadHelper.buildQuad(normal, box, uv, targetSprite); } - public static @NotNull List createFrame(TextureAtlasSprite sprite) { - PipeQuadHelper helper = PipeQuadHelper.create(0.998f).initialize(); - helper.setTargetSprite(new SpriteInformation(sprite, 0)); + public static @NotNull List createFrame(BakedModel frameModel, RandomSource randomSource, + ModelData modelData, RenderType renderType) { List list = new ObjectArrayList<>(); - for (Direction facing : GTUtil.DIRECTIONS) { - list.add(helper.visitCore(facing)); - } + // should always work + list.addAll(frameModel.getQuads(null, null, randomSource, modelData, renderType) + .stream() + .map(quad -> { + BakedQuad q = Quad.from(quad, -0.002f).rebake(); + return new BakedQuad(q.getVertices(), q.getTintIndex() + 3, + q.getDirection(), q.getSprite(), q.isShade(), q.hasAmbientOcclusion()); + }) + .toList()); return list; } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java index bc0759362c..7c5cf6644e 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/QuadHelper.java @@ -26,8 +26,7 @@ public final class QuadHelper { private QuadHelper() {} public static @NotNull BakedQuad buildQuad(Direction normal, Pair box, - @NotNull UVMapper uv, - @NotNull SpriteInformation targetSprite) { + @NotNull UVMapper uv, @NotNull SpriteInformation targetSprite) { BlockElementFace face = new BlockElementFace(null, -1, targetSprite.sprite().contents().name().toString(), uv.map(normal, box), ForgeFaceData.DEFAULT); return StaticFaceBakery.bakeRecolorableQuad(box.getLeft(), box.getRight(), face, targetSprite, normal, diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java index 1d315b005c..6360f67c49 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/util/ActivableCacheKey.java @@ -1,9 +1,9 @@ package com.gregtechceu.gtceu.client.renderer.pipe.util; -import lombok.Getter; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import lombok.Getter; import org.jetbrains.annotations.Nullable; @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java index ed7d74a5e9..5e584cb484 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java +++ b/src/main/java/com/gregtechceu/gtceu/client/util/StaticFaceBakery.java @@ -135,14 +135,14 @@ public static BakedQuad bakeQuad( } public static BakedQuad bakeRecolorableQuad(Vector3f posFrom, - Vector3f posTo, - BlockElementFace face, - SpriteInformation sprite, - Direction facing, - ModelState transform, - @Nullable BlockElementRotation partRotation, - boolean shade, - int emissivity) { + Vector3f posTo, + BlockElementFace face, + SpriteInformation sprite, + Direction facing, + ModelState transform, + @Nullable BlockElementRotation partRotation, + boolean shade, + int emissivity) { BlockFaceUV blockfaceuv = face.uv; if (transform.isUvLocked()) { blockfaceuv = recomputeUVs(face.uv, facing, transform.getRotation()); @@ -168,7 +168,8 @@ public static BakedQuad bakeRecolorableQuad(Vector3f posFrom, ForgeHooksClient.fillNormal(aint, direction); ForgeFaceData data = face.getFaceData(); - BakedQuad quad = new BakedQuad(aint, sprite.colorID(), direction, sprite.sprite(), shade, data.ambientOcclusion()); + BakedQuad quad = new BakedQuad(aint, sprite.colorID(), direction, sprite.sprite(), shade, + data.ambientOcclusion()); if (!ForgeFaceData.DEFAULT.equals(data)) { QuadTransformers.applyingLightmap(data.blockLight(), data.skyLight()).processInPlace(quad); QuadTransformers.applyingColor(data.color()).processInPlace(quad); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 7649154ce5..1c9ee68332 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -16,6 +16,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.MaterialPipeBlockItem; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlockItem; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.item.*; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.machine.multiblock.IBatteryData; @@ -330,10 +331,10 @@ private static void registerCableBlock(Material material, CableStructure structu .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) - .color(() -> () -> (state, level, pos, color) -> color) + .color(() -> PipeMaterialBlock::tintedColor) .item(MaterialPipeBlockItem::new) .model(NonNullBiConsumer.noop()) - .color(() -> () -> (stack, color) -> color) + .color(() -> MaterialPipeBlockItem::tintColor) .onRegister(compassNodeExist(GTCompassSections.MATERIALS, "wire_and_cable")) .build() .register(); @@ -379,7 +380,7 @@ private static void registerMaterialPipeBlock(Material material, MaterialPipeStr .setData(ProviderType.LANG, NonNullBiConsumer.noop()) .setData(ProviderType.LOOT, NonNullBiConsumer.noop()) .addLayer(() -> RenderType::cutoutMipped) - .color(() -> MaterialPipeBlock::tintedColor) + .color(() -> PipeMaterialBlock::tintedColor) .item(MaterialPipeBlockItem::new) .model(NonNullBiConsumer.noop()) .color(() -> MaterialPipeBlockItem::tintColor) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java index eb51b44f16..cd7f05860b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/datafixer/GTDataFixers.java @@ -4,8 +4,8 @@ import com.gregtechceu.gtceu.api.GTCEuAPI; import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; import com.gregtechceu.gtceu.common.datafixer.fixes.ActivablePipeConnectionFix; -import com.gregtechceu.gtceu.common.datafixer.fixes.PipeConnectionFix; import com.gregtechceu.gtceu.common.datafixer.fixes.OilVariantsRenameFix; +import com.gregtechceu.gtceu.common.datafixer.fixes.PipeConnectionFix; import com.gregtechceu.gtceu.common.datafixer.schemas.V2; import com.gregtechceu.gtceu.config.ConfigHolder; @@ -108,8 +108,7 @@ public static void addFixers(DataFixerBuilder builder) { "gtceu:item_pipe", "gtceu:material_pipe", "gtceu:laser_pipe", "gtceu:activable_pipe", "gtceu:optical_pipe", "gtceu:activable_pipe", - "gtceu:duct_pipe", "gtceu:pipe" - )))); + "gtceu:duct_pipe", "gtceu:pipe")))); } private static UnaryOperator createRenamer(String pOldName, String pNewName) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java index 68d2d19550..f264fe7a1c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/PipeConnectionFix.java @@ -1,24 +1,26 @@ package com.gregtechceu.gtceu.common.datafixer.fixes; +import net.minecraft.util.datafix.fixes.NamedEntityFix; +import net.minecraft.util.datafix.fixes.References; + import com.mojang.datafixers.DSL; import com.mojang.datafixers.Typed; import com.mojang.datafixers.schemas.Schema; import com.mojang.serialization.Dynamic; -import net.minecraft.util.datafix.fixes.NamedEntityFix; -import net.minecraft.util.datafix.fixes.References; public class PipeConnectionFix extends NamedEntityFix { - public PipeConnectionFix(Schema outputSchema, boolean changesType, String type) { - super(outputSchema, changesType, "PipeConnectionFix", References.BLOCK_ENTITY, type); - } - public Dynamic fixTag(Dynamic tag) { - tag = tag.set("connectionMask", tag.get("connections").result().get()); - return tag.set("blockedMask", tag.get("blockedConnections").result().get()); - } + public PipeConnectionFix(Schema outputSchema, boolean changesType, String type) { + super(outputSchema, changesType, "PipeConnectionFix", References.BLOCK_ENTITY, type); + } + + public Dynamic fixTag(Dynamic tag) { + tag = tag.set("connectionMask", tag.get("connections").result().get()); + return tag.set("blockedMask", tag.get("blockedConnections").result().get()); + } - @Override - protected Typed fix(Typed typed) { - return typed.update(DSL.remainderFinder(), this::fixTag); - } + @Override + protected Typed fix(Typed typed) { + return typed.update(DSL.remainderFinder(), this::fixTag); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java index 4e6729a6ec..504192a3ad 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java @@ -227,8 +227,7 @@ public Map> registerBlockEntities(Schema schema) "blockedConnections", DSL.intType().template(), "cover", covers.get(), "paintingColor", DSL.intType().template(), - "frameMaterial", GTReferences.MATERIAL_NAME.in(schema) - )); + "frameMaterial", GTReferences.MATERIAL_NAME.in(schema))); schema.register(map, "gtceu:cable", () -> DSL.and( DSL.optionalFields("temperature", DSL.intType().template()), diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java index 1a7fe29a9c..dcdc925678 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -5,11 +5,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import net.minecraft.client.color.block.BlockColor; import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; public class MaterialPipeBlock extends PipeMaterialBlock implements IBurnable, IFreezable { @@ -22,26 +18,4 @@ public MaterialPipeStructure getStructure() { return (MaterialPipeStructure) super.getStructure(); } - @OnlyIn(Dist.CLIENT) - public static BlockColor tintedColor() { - return (blockState, level, blockPos, index) -> { - if (blockState.getBlock() instanceof MaterialPipeBlock block) { - if (blockPos != null && level != null && - level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { - if (pipe.getFrameMaterial() != null) { - if (index == 3) { - return pipe.getFrameMaterial().getMaterialRGB(); - } else if (index == 4) { - return pipe.getFrameMaterial().getMaterialSecondaryRGB(); - } - } - if (index == 0 && pipe.isPainted()) { - return pipe.getPaintingColor(); - } - } - return block.tinted(blockState, level, blockPos, index); - } - return -1; - }; - } } diff --git a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java index 77a46eb0f8..6cab005c87 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java +++ b/src/main/java/com/gregtechceu/gtceu/core/MixinHelpers.java @@ -3,7 +3,6 @@ import com.gregtechceu.gtceu.api.GTCEuAPI; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.addon.AddonFinder; -import com.gregtechceu.gtceu.api.addon.IGTAddon; import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.data.chemical.material.properties.FluidProperty; diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java index af54cf4df7..bc4e7c6336 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java @@ -1,7 +1,9 @@ package com.gregtechceu.gtceu.core.mixins; import com.gregtechceu.gtceu.common.data.GTBlockEntities; + import net.minecraft.world.level.block.entity.BlockEntity; + import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @@ -12,15 +14,13 @@ public class BlockEntityMixin { @ModifyArg(method = "loadStatic", at = @At(value = "INVOKE", - target = "Lnet/minecraft/resources/ResourceLocation;tryParse(Ljava/lang/String;)Lnet/minecraft/resources/ResourceLocation;")) + target = "Lnet/minecraft/resources/ResourceLocation;tryParse(Ljava/lang/String;)Lnet/minecraft/resources/ResourceLocation;")) private static String gtceu$remapBlockEntityLoadBecauseDataFixDoesntWantToWork(String s) { switch (s) { - case "gtceu:cable", "gtceu:fluid_pipe", "gtceu:item_pipe" -> - s = GTBlockEntities.MATERIAL_PIPE.getId().toString(); - case "gtceu:laser_pipe", "gtceu:optical_pipe" -> - s = GTBlockEntities.ACTIVABLE_PIPE.getId().toString(); - case "gtceu:duct_pipe" -> - s = GTBlockEntities.PIPE.getId().toString(); + case "gtceu:cable", "gtceu:fluid_pipe", "gtceu:item_pipe" -> s = GTBlockEntities.MATERIAL_PIPE.getId() + .toString(); + case "gtceu:laser_pipe", "gtceu:optical_pipe" -> s = GTBlockEntities.ACTIVABLE_PIPE.getId().toString(); + case "gtceu:duct_pipe" -> s = GTBlockEntities.PIPE.getId().toString(); } return s; } diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java index 446172194e..8cc25712f4 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/NbtUtilsMixin.java @@ -1,9 +1,11 @@ package com.gregtechceu.gtceu.core.mixins; import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; -import com.llamalad7.mixinextras.injector.ModifyReturnValue; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; + +import com.llamalad7.mixinextras.injector.ModifyReturnValue; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -14,5 +16,4 @@ public class NbtUtilsMixin { private static CompoundTag gtceu$addModDataVersion(CompoundTag tag) { return DataFixesInternals.get().addModDataVersions(tag); } - } diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index 7020649e2f..3071205c30 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -83,8 +83,8 @@ import net.minecraftforge.items.IItemHandler; import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.MissingMappingsEvent; - import net.minecraftforge.registries.RegistryManager; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -505,8 +505,7 @@ public static void remapIds(MissingMappingsEvent event) { "gtceu:uranium", "gtceu:uranium_238", "gtceu:flowing_uranium", "gtceu:flowing_uranium_238", "gtceu:plutonium", "gtceu:plutonium_238", - "gtceu:flowing_plutonium", "gtceu:flowing_plutonium_238" - ), mapping); + "gtceu:flowing_plutonium", "gtceu:flowing_plutonium_238"), mapping); }); event.getMappings(Registries.BLOCK_ENTITY_TYPE, GTCEu.MOD_ID).forEach(mapping -> { switch (mapping.getKey().getPath()) { @@ -544,7 +543,8 @@ private static void remapPipe(MissingMappingsEvent.Mapping mapping) { } } - private static void remapMaterial(Pattern pattern, String replacement, MissingMappingsEvent.Mapping mapping) { + private static void remapMaterial(Pattern pattern, String replacement, + MissingMappingsEvent.Mapping mapping) { String namespace = mapping.getKey().getNamespace(); String path = mapping.getKey().getPath(); Matcher match = pattern.matcher(path); From 56885e281c8b2d54e9b66f615a359d419321bd5c Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Mon, 9 Sep 2024 10:28:34 +0300 Subject: [PATCH 40/70] port latest changes --- .../api/capability/IDataAccessHatch.java | 46 ------------------- .../api/capability/data/IDataAccess.java | 18 ++++---- .../data/query/DataQueryObject.java | 19 ++++++++ .../api/graphnet/logic/NetLogicData.java | 2 +- .../api/graphnet/logic/NetLogicRegistry.java | 14 +++--- .../api/graphnet/pipenet/WorldPipeNet.java | 9 +++- .../physical/block/ActivablePipeBlock.java | 2 +- .../physical/tile/PipeBlockEntity.java | 32 ++++++++++++- .../trait/NotifiableComputationContainer.java | 6 +-- .../renderer/pipe/cache/BlockableSQC.java | 22 ++++++++- .../renderer/pipe/cache/RestrictiveSQC.java | 8 ++-- .../gtceu/common/cover/ShutterCover.java | 3 +- .../gtceu/common/data/GTBlockEntities.java | 4 +- .../data/machines/GTResearchMachines.java | 6 +-- ...hine.java => ComputationHatchMachine.java} | 4 +- .../part/DataAccessHatchMachine.java | 34 +++++++++++--- .../part/OpticalDataHatchMachine.java | 3 +- .../optical/IOpticalTransferController.java | 3 +- .../net/optical/DataCapabilityObject.java | 4 -- .../gtceu/core/mixins/BlockEntityMixin.java | 2 +- .../gtceu/forge/ForgeCommonEventListener.java | 2 +- .../gtceu/utils/reference/WeakHashSet.java | 2 +- 22 files changed, 143 insertions(+), 102 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/capability/IDataAccessHatch.java rename src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/{OpticalComputationHatchMachine.java => ComputationHatchMachine.java} (90%) diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IDataAccessHatch.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IDataAccessHatch.java deleted file mode 100644 index 094a9471c5..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IDataAccessHatch.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.gregtechceu.gtceu.api.capability; - -import com.gregtechceu.gtceu.api.recipe.GTRecipe; - -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.Collection; - -public interface IDataAccessHatch { - - /** - * If passed a {@code seen} context, you must use {@link #isRecipeAvailable(GTRecipe, Collection)} to prevent - * infinite recursion - * - * @param recipe the recipe to check - * @return if the recipe is available for use - */ - default boolean isRecipeAvailable(@NotNull GTRecipe recipe) { - Collection list = new ArrayList<>(); - list.add(this); - return isRecipeAvailable(recipe, list); - } - - /** - * @param recipe the recipe to check - * @param seen the hatches already checked - * @return if the recipe is available for use - */ - boolean isRecipeAvailable(@NotNull GTRecipe recipe, @NotNull Collection seen); - - // REMEMBER TO CALL THIS FOR YOUR CUSTOM DATA HATCH TO WORK. - default GTRecipe modifyRecipe(GTRecipe recipe) { - // creative hatches do not need to check, they always have the recipe - if (this.isCreative()) return recipe; - - // hatches need to have the recipe available - if (this.isRecipeAvailable(recipe)) return recipe; - return null; - } - - /** - * @return true if this Data Access Hatch is creative or not - */ - boolean isCreative(); -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java index 95bbe14772..ee749cb6d1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/IDataAccess.java @@ -9,10 +9,8 @@ public interface IDataAccess { /** * Queries this {@link IDataAccess} with the specified query. - * - * @param queryObject the object representing the query. Can be cached in a weak set created by - * {@link com.gregtechceu.gtceu.utils.GTUtil#createWeakHashSet()} in order to prevent endless - * recursion. + * + * @param queryObject the object representing the query. * @return if the query has been cancelled */ boolean accessData(@NotNull DataQueryObject queryObject); @@ -33,7 +31,7 @@ default boolean supportsQuery(@NotNull DataQueryObject queryObject) { /** * Provides standardized logic for querying a collection of {@link IDataAccess}es. - * + * * @param accesses the {@link IDataAccess}es to query. * @param query the object representing the query. * @return if the query has been cancelled @@ -43,10 +41,12 @@ static boolean accessData(@NotNull Iterable accesses, boolean walk = false; boolean cancelled = false; for (IDataAccess access : accesses) { - query.setShouldTriggerWalker(false); - cancelled = access.accessData(query); - if (!walk) walk = query.isShouldTriggerWalker(); - if (cancelled) break; + if (query.traverseTo(access)) { + query.setShouldTriggerWalker(false); + cancelled = access.accessData(query); + if (!walk) walk = query.isShouldTriggerWalker(); + if (cancelled) break; + } } query.setShouldTriggerWalker(walk); return cancelled; diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java index 2e7c9584b6..dc85db38b7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java @@ -1,8 +1,12 @@ package com.gregtechceu.gtceu.api.capability.data.query; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; +import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; import lombok.Getter; import lombok.Setter; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class DataQueryObject { @@ -14,10 +18,25 @@ public abstract class DataQueryObject { @Setter private boolean shouldTriggerWalker = false; + private final ReferenceOpenHashSet visited = new ReferenceOpenHashSet<>(); + public DataQueryObject() { this.id = ID++; } + /** + * Used to tell this query when it passes through a location during traversal, + * know if the location supports this query, + * and know if this query has already visited the location. + * + * @param location the location next on traversal + * @return whether the location is not null, supports this query, and has not yet been visited. + */ + @Contract("null -> false") + public final boolean traverseTo(@Nullable IDataAccess location) { + return location != null && location.supportsQuery(this) && this.visited.add(location); + } + @NotNull public abstract DataQueryFormat getFormat(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index 5e7e20c2ca..f9ea491914 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -184,7 +184,7 @@ public void deserializeNBT(ListTag nbt) { CompoundTag tag = nbt.getCompound(i); String key = tag.getString("Name"); NetLogicEntry entry = this.logicEntrySet.get(key); - if (entry == null) entry = NetLogicRegistry.getTypeNotNull(key).supplier().get(); + if (entry == null) entry = NetLogicRegistry.getTypeNotNull(key).getNew(); if (entry == null) continue; entry.deserializeNBTNaive(tag.get("Tag")); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index 37931b5a5e..b2dc4968a6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -1,6 +1,6 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import net.minecraft.nbt.Tag; +import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -36,7 +36,7 @@ public static void throwNonexistenceError() { "This suggests that the server and client have different GT versions or modifications."); } - private static class EmptyLogicEntry extends NetLogicEntry { + private static class EmptyLogicEntry extends NetLogicEntry { private static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Empty", EmptyLogicEntry::new); @@ -46,17 +46,15 @@ protected EmptyLogicEntry() { } @Override - public @Nullable Tag serializeNBT() { - throw new RuntimeException("Can't serialize empty logic entry!"); + public @Nullable CompoundTag serializeNBT() { + return new CompoundTag(); } @Override - public void deserializeNBT(Tag arg) {} + public void deserializeNBT(CompoundTag arg) {} @Override - public void encode(FriendlyByteBuf buf, boolean fullChange) { - throw new RuntimeException("Can't serialize empty logic entry!"); - } + public void encode(FriendlyByteBuf buf, boolean fullChange) {} @Override public void decode(FriendlyByteBuf buf, boolean fullChange) {} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index 1b23d405a6..d4c743c799 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -10,8 +10,10 @@ import com.gregtechceu.gtceu.api.graphnet.graph.INetGraph; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeCapabilityObject; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.BlockedPredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldPosNet; +import com.gregtechceu.gtceu.common.cover.ShutterCover; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.core.BlockPos; @@ -129,7 +131,12 @@ protected boolean predicateEdge(@NotNull NetEdge edge, @NotNull WorldPipeNetNode * @param a the cover on the source of the edge * @param b the cover on the sink of the edge */ - protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) {} + protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) { + if (a instanceof ShutterCover aS && aS.isWorkingEnabled() || + b instanceof ShutterCover bS && bS.isWorkingEnabled()) { + edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + } + } public abstract Capability[] getTargetCapabilities(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java index 9a49e7c259..65d7157346 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/ActivablePipeBlock.java @@ -24,7 +24,7 @@ public ActivablePipeBlock(BlockBehaviour.Properties properties, IPipeStructure s @Override public @Nullable BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new ActivablePipeBlockEntity(GTBlockEntities.ACTIVABLE_PIPE.get(), pos, state); + return new ActivablePipeBlockEntity(GTBlockEntities.ACTIVATABLE_PIPE.get(), pos, state); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index cb2c9b2a67..d4b67c7403 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -65,6 +65,8 @@ 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.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.Shapes; @@ -100,6 +102,10 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity private final Int2ObjectOpenHashMap netLogicDatas = new Int2ObjectOpenHashMap<>(); + // this tile was loaded from datafixed NBT and needs to initialize its connections + @Persisted + private boolean legacy; + // information that is only required for determining graph topology should be stored on the tile entity level, // while information interacted with during graph traversal should be stored on the NetLogicData level. @@ -352,9 +358,16 @@ public void clearRemoved() { @Override public void loadCustomPersistedData(CompoundTag tag) { - if (tag.contains("connections")) this.connectionMask = tag.getByte("connections"); - if (tag.contains("blockedConnections")) this.blockedMask = tag.getByte("blockedConnections"); + if (tag.contains("connections")) { + legacy = true; + this.connectionMask = tag.getByte("connections"); + } + if (tag.contains("blockedConnections")) { + legacy = true; + this.blockedMask = tag.getByte("blockedConnections"); + } if (tag.contains("cover")) { + legacy = true; PersistedParser.deserializeNBT(tag.getCompound("cover"), new HashMap<>(), PipeCoverHolder.class, this.coverHolder); } @@ -538,6 +551,21 @@ protected void initialize() { this.temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); } } + if (this.legacy) { + for (Direction facing : GTUtil.DIRECTIONS) { + if (this.isConnected(facing)) { + PipeBlock.connectTile(this, this.getPipeNeighbor(facing, false), facing); + BlockPos pos = this.getBlockPos().relative(facing); + ChunkAccess chunk = getLevel().getChunk(pos); + if (chunk instanceof LevelChunk levelChunk) { + BlockEntity candidate = levelChunk + .getBlockEntity(pos, LevelChunk.EntityCreationType.CHECK); + if (candidate instanceof PipeBlockEntity pipe) + PipeBlock.connectTile(this, pipe, facing); + } + } + } + } this.netLogicDatas.trim(); this.capabilities.trim(); this.netCapabilities.trim(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java index 5a7ed17d73..cf3f99a801 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java @@ -57,8 +57,6 @@ public NotifiableComputationContainer(MetaMachine machine, IO handlerIO, boolean @Override public boolean accessData(@NotNull DataQueryObject queryObject) { - if (!supportsQuery(queryObject) || !recentQueries.add(queryObject)) return false; - if (isTransmitter()) { MetaMachine machine = getMachine(); if (machine instanceof IWorkable workable && !workable.isActive()) return false; @@ -95,9 +93,9 @@ public boolean accessData(@NotNull DataQueryObject queryObject) { Direction front = machine.getFrontFacing(); IDataAccess access = GTCapabilityHelper.getDataAccess(machine.getLevel(), machine.getPos().relative(front), front.getOpposite()); - if (access == null) return false; - return access.accessData(queryObject); + if (queryObject.traverseTo(access)) return access.accessData(queryObject); } + return false; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java index ab42f805db..a20fc1241b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java @@ -9,7 +9,10 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; import java.util.EnumMap; import java.util.List; @@ -30,13 +33,28 @@ protected BlockableSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteIn public static @NotNull BlockableSQC create(PipeQuadHelper helper, SpriteInformation endTex, SpriteInformation sideTex, SpriteInformation blockedTex) { - helper.initialize((facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, - OVERLAY_DIST_1)); + helper.initialize((facing, x1, y1, z1, x2, y2, z2) -> minLengthTube(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_1, 4)); BlockableSQC cache = new BlockableSQC(helper, endTex, sideTex, blockedTex); cache.buildPrototype(); return cache; } + + public static ImmutablePair minLengthTube(@Nullable Direction facing, float x1, float y1, + float z1, float x2, + float y2, float z2, float g, float minLength) { + if (facing == null) return QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, g); + return switch (facing) { + case UP -> QuadHelper.tubeOverlay(facing, x1, Math.min(y1, y2 - minLength), z1, x2, y2, z2, g); + case DOWN -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, Math.max(y2, y1 + minLength), z2, g); + case EAST -> QuadHelper.tubeOverlay(facing, Math.min(x1, x2 - minLength), y1, z1, x2, y2, z2, g); + case WEST -> QuadHelper.tubeOverlay(facing, x1, y1, z1, Math.max(x2, x1 + minLength), y2, z2, g); + case SOUTH -> QuadHelper.tubeOverlay(facing, x1, y1, Math.min(z1, z2 - minLength), x2, y2, z2, g); + case NORTH -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, Math.max(z2, z1 + minLength), g); + }; + } + @Override protected List buildPrototypeInternal() { List quads = super.buildPrototypeInternal(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java index e07bd5a8af..d34c18fb1f 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java @@ -32,10 +32,10 @@ protected RestrictiveSQC(PipeQuadHelper helper, SpriteInformation endTex, Sprite SpriteInformation sideTex, SpriteInformation blockedTex, SpriteInformation restrictiveTex) { helper.initialize( - (facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, - OVERLAY_DIST_2), - (facing, x1, y1, z1, x2, y2, z2) -> QuadHelper.tubeOverlay(facing, x1, y1, z1, x2, y2, z2, - OVERLAY_DIST_1)); + (facing, x1, y1, z1, x2, y2, z2) -> minLengthTube(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_2, 4), + (facing, x1, y1, z1, x2, y2, z2) -> minLengthTube(facing, x1, y1, z1, x2, y2, z2, + OVERLAY_DIST_1, 2)); RestrictiveSQC sqc = new RestrictiveSQC(helper, endTex, sideTex, blockedTex, restrictiveTex); sqc.buildPrototype(); return sqc; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java index 269b034fa0..7b2408e11a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/ShutterCover.java @@ -54,7 +54,8 @@ public InteractionResult onScrewdriverClick(Player playerIn, InteractionHand han @Override public boolean canPipePassThrough() { - return !workingEnabled; + // isWorkingAllowed restriction is applied during edge predication + return true; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java index 65208ff9b8..a1ef2daabd 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlockEntities.java @@ -27,8 +27,8 @@ public class GTBlockEntities { .validBlocks(GTBlocks.DUCT_PIPE_BLOCKS.values().toArray(NonNullSupplier[]::new)) .register(); - public static final BlockEntityEntry ACTIVABLE_PIPE = REGISTRATE - .blockEntity("activable_pipe", ActivablePipeBlockEntity::new) + public static final BlockEntityEntry ACTIVATABLE_PIPE = REGISTRATE + .blockEntity("activatable_pipe", ActivablePipeBlockEntity::new) .validBlocks(Stream.of(GTBlocks.OPTICAL_PIPE, GTBlocks.LASER_PIPE).toArray(NonNullSupplier[]::new)) .register(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java index 58735fc4b9..abd1932f2e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java @@ -23,7 +23,7 @@ import com.gregtechceu.gtceu.common.machine.multiblock.electric.research.ResearchStationMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.DataAccessHatchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.ObjectHolderMachine; -import com.gregtechceu.gtceu.common.machine.multiblock.part.OpticalComputationHatchMachine; +import com.gregtechceu.gtceu.common.machine.multiblock.part.ComputationHatchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.OpticalDataHatchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.hpca.HPCABridgePartMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.hpca.HPCAComputationPartMachine; @@ -302,12 +302,12 @@ public class GTResearchMachines { public static final MachineDefinition COMPUTATION_HATCH_TRANSMITTER = registerDataHatch( "computation_transmitter_hatch", "Computation Data Transmission Hatch", - ZPM, (holder) -> new OpticalComputationHatchMachine(holder, true), + ZPM, (holder) -> new ComputationHatchMachine(holder, true), "computation_data_hatch", PartAbility.COMPUTATION_DATA_TRANSMISSION).register(); public static final MachineDefinition COMPUTATION_HATCH_RECEIVER = registerDataHatch( "computation_receiver_hatch", "Computation Data Reception Hatch", - ZPM, (holder) -> new OpticalComputationHatchMachine(holder, false), + ZPM, (holder) -> new ComputationHatchMachine(holder, false), "computation_data_hatch", PartAbility.COMPUTATION_DATA_RECEPTION).register(); public static final MachineDefinition DATA_HATCH_TRANSMITTER = registerDataHatch( diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalComputationHatchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/ComputationHatchMachine.java similarity index 90% rename from src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalComputationHatchMachine.java rename to src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/ComputationHatchMachine.java index ebd6f03658..0659c60b1e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalComputationHatchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/ComputationHatchMachine.java @@ -16,14 +16,14 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault -public class OpticalComputationHatchMachine extends MultiblockPartMachine { +public class ComputationHatchMachine extends MultiblockPartMachine { @Getter private final boolean transmitter; protected NotifiableComputationContainer computationContainer; - public OpticalComputationHatchMachine(IMachineBlockEntity holder, boolean transmitter) { + public ComputationHatchMachine(IMachineBlockEntity holder, boolean transmitter) { super(holder); this.transmitter = transmitter; this.computationContainer = createComputationContainer(transmitter); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/DataAccessHatchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/DataAccessHatchMachine.java index 1fea9651b7..4ee44d4ff2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/DataAccessHatchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/DataAccessHatchMachine.java @@ -1,7 +1,10 @@ package com.gregtechceu.gtceu.common.machine.multiblock.part; import com.gregtechceu.gtceu.api.GTValues; -import com.gregtechceu.gtceu.api.capability.IDataAccessHatch; +import com.gregtechceu.gtceu.api.capability.data.IDataAccess; +import com.gregtechceu.gtceu.api.capability.data.query.DataAccessFormat; +import com.gregtechceu.gtceu.api.capability.data.query.DataQueryObject; +import com.gregtechceu.gtceu.api.capability.data.query.RecipeDataQuery; import com.gregtechceu.gtceu.api.capability.recipe.IO; import com.gregtechceu.gtceu.api.capability.recipe.ItemRecipeCapability; import com.gregtechceu.gtceu.api.gui.GuiTextures; @@ -46,7 +49,7 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class DataAccessHatchMachine extends TieredPartMachine - implements IMachineLife, IDataAccessHatch, IDataInfoProvider { + implements IMachineLife, IDataAccess, IDataInfoProvider { protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder( DataAccessHatchMachine.class, MultiblockPartMachine.MANAGED_FIELD_HOLDER); @@ -137,9 +140,19 @@ private void rebuildData(boolean isDataBank) { } @Override - public boolean isRecipeAvailable(@NotNull GTRecipe recipe, @NotNull Collection seen) { - seen.add(this); - return recipe.conditions.stream().noneMatch(ResearchCondition.class::isInstance) || recipes.contains(recipe); + public boolean accessData(@NotNull DataQueryObject queryObject) { + if (queryObject instanceof RecipeDataQuery query) { + if (isCreative || recipes.contains(query.getRecipe())) { + query.setFound(); + return true; + } + } + return false; + } + + @Override + public @NotNull DataAccessFormat getFormat() { + return DataAccessFormat.STANDARD; } @NotNull @@ -180,7 +193,16 @@ public void addedToController(IMultiController controller) { @Override public GTRecipe modifyRecipe(GTRecipe recipe) { - return IDataAccessHatch.super.modifyRecipe(recipe); + // creative hatches do not need to check, they always have the recipe + if (this.isCreative()) return recipe; + if (recipe.conditions.stream().noneMatch(ResearchCondition.class::isInstance)) return recipe; + + // hatches need to have the recipe available + RecipeDataQuery query = new RecipeDataQuery(recipe); + if (query.traverseTo(this) && this.accessData(query)) { + return recipe; + } + return null; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java index 0d95852a68..982a320e8d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java @@ -46,7 +46,6 @@ public OpticalDataHatchMachine(IMachineBlockEntity holder, boolean isTransmitter @Override public boolean accessData(@NotNull DataQueryObject queryObject) { - if (!supportsQuery(queryObject) || !recentQueries.add(queryObject)) return false; if (!getControllers().isEmpty()) { if (isTransmitter()) { IMultiController controller = getControllers().get(0); @@ -78,7 +77,7 @@ public boolean accessData(@NotNull DataQueryObject queryObject) { if (tileEntity == null) return false; IDataAccess cap = tileEntity.getCapability(GTCapability.CAPABILITY_DATA_ACCESS, getFrontFacing().getOpposite()).resolve().orElse(null); - return cap != null && cap.accessData(queryObject); + if (queryObject.traverseTo(cap)) return cap.accessData(queryObject); } } return false; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java index e2959f7d83..156d587a30 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/IOpticalTransferController.java @@ -39,6 +39,7 @@ public boolean queryHandler(DataQueryObject query, IDataAccess handler) { * @return whether the request should be cancelled */ default boolean queryHandler(DataQueryObject query, IDataAccess handler) { - return handler.accessData(query); + if (query.traverseTo(handler)) return handler.accessData(query); + else return false; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java index fd23122db7..c5ef1c4037 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java @@ -34,8 +34,6 @@ public class DataCapabilityObject implements IPipeCapabilityObject, IDataAccess @Setter private @Nullable PipeBlockEntity tile; - private final Set recentQueries = GTUtil.createWeakHashSet(); - public DataCapabilityObject(@NotNull N net) { this.net = net; } @@ -47,8 +45,6 @@ private BasicWorldPipeNetPath.Provider getProvider() { @Override public boolean accessData(@NotNull DataQueryObject queryObject) { if (tile == null) return false; - // if the add call fails (because the object already exists in the set) then do not recurse - if (!recentQueries.add(queryObject)) return false; for (Iterator it = getPaths(); it.hasNext();) { BasicWorldPipeNetPath path = it.next(); diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java index bc4e7c6336..8a9558b3a9 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/BlockEntityMixin.java @@ -19,7 +19,7 @@ public class BlockEntityMixin { switch (s) { case "gtceu:cable", "gtceu:fluid_pipe", "gtceu:item_pipe" -> s = GTBlockEntities.MATERIAL_PIPE.getId() .toString(); - case "gtceu:laser_pipe", "gtceu:optical_pipe" -> s = GTBlockEntities.ACTIVABLE_PIPE.getId().toString(); + case "gtceu:laser_pipe", "gtceu:optical_pipe" -> s = GTBlockEntities.ACTIVATABLE_PIPE.getId().toString(); case "gtceu:duct_pipe" -> s = GTBlockEntities.PIPE.getId().toString(); } return s; diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index 3071205c30..442b22bd56 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -510,7 +510,7 @@ public static void remapIds(MissingMappingsEvent event) { event.getMappings(Registries.BLOCK_ENTITY_TYPE, GTCEu.MOD_ID).forEach(mapping -> { switch (mapping.getKey().getPath()) { case "cable", "fluid_pipe", "item_pipe" -> mapping.remap(GTBlockEntities.MATERIAL_PIPE.get()); - case "laser_pipe", "optical_pipe" -> mapping.remap(GTBlockEntities.ACTIVABLE_PIPE.get()); + case "laser_pipe", "optical_pipe" -> mapping.remap(GTBlockEntities.ACTIVATABLE_PIPE.get()); case "duct_pipe" -> mapping.remap(GTBlockEntities.PIPE.get()); } }); diff --git a/src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java b/src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java index 17524e2fba..b6c458e837 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/reference/WeakHashSet.java @@ -55,7 +55,7 @@ public boolean remove(Object o) { @Override public boolean add(E e) { - return m.put(e, null) == null; + return m.put(e, Boolean.TRUE) == null; } @Override From 7f7bd4bdaf684e6c5ff796aa7d515d87a04a4c17 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Mon, 9 Sep 2024 16:24:43 +0300 Subject: [PATCH 41/70] clean up unused fields, spotless --- .../gtceu/api/capability/data/query/DataQueryObject.java | 1 + .../graphnet/pipenet/physical/block/PipeMaterialBlock.java | 2 +- .../api/machine/trait/NotifiableComputationContainer.java | 3 --- .../gtceu/client/renderer/pipe/cache/BlockableSQC.java | 1 - .../gtceu/client/renderer/pipe/cache/RestrictiveSQC.java | 1 - .../machine/multiblock/part/OpticalDataHatchMachine.java | 4 ---- 6 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java index dc85db38b7..b0f881dd28 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/data/query/DataQueryObject.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.capability.data.query; import com.gregtechceu.gtceu.api.capability.data.IDataAccess; + import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index e36155ecb6..e1d1a58029 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -19,9 +19,9 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java index cf3f99a801..6e4f642ef7 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/trait/NotifiableComputationContainer.java @@ -20,7 +20,6 @@ import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiPart; import com.gregtechceu.gtceu.api.recipe.GTRecipe; import com.gregtechceu.gtceu.utils.GTUtil; -import com.gregtechceu.gtceu.utils.reference.WeakHashSet; import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; @@ -42,8 +41,6 @@ public class NotifiableComputationContainer extends NotifiableRecipeHandlerTrait @Getter protected boolean transmitter; - private final WeakHashSet recentQueries = new WeakHashSet<>(); - protected long lastTimeStamp; private long currentOutputCwu = 0, lastOutputCwu = 0; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java index a20fc1241b..645e1e971a 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/BlockableSQC.java @@ -40,7 +40,6 @@ protected BlockableSQC(PipeQuadHelper helper, SpriteInformation endTex, SpriteIn return cache; } - public static ImmutablePair minLengthTube(@Nullable Direction facing, float x1, float y1, float z1, float x2, float y2, float z2, float g, float minLength) { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java index d34c18fb1f..f5f0d76269 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/RestrictiveSQC.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.client.renderer.pipe.cache; import com.gregtechceu.gtceu.client.renderer.pipe.quad.PipeQuadHelper; -import com.gregtechceu.gtceu.client.renderer.pipe.quad.QuadHelper; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; import com.gregtechceu.gtceu.utils.GTUtil; diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java index 982a320e8d..84beee9771 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/part/OpticalDataHatchMachine.java @@ -12,7 +12,6 @@ import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.machine.multiblock.part.MultiblockPartMachine; import com.gregtechceu.gtceu.api.recipe.GTRecipe; -import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.world.InteractionHand; @@ -26,7 +25,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Set; import javax.annotation.ParametersAreNonnullByDefault; @@ -34,8 +32,6 @@ @ParametersAreNonnullByDefault public class OpticalDataHatchMachine extends MultiblockPartMachine implements IStandardDataAccess { - private final Set recentQueries = GTUtil.createWeakHashSet(); - @Getter private final boolean isTransmitter; From 699c7ae0d28f438b35836a7af400a89aa6a4daf8 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Mon, 9 Sep 2024 17:23:11 +0300 Subject: [PATCH 42/70] fix net logic types not loading early enough --- .../gregtechceu/gtceu/api/addon/IGTAddon.java | 7 +++++ .../logic/AbstractDoubleLogicData.java | 2 +- .../graphnet/logic/AbstractIntLogicData.java | 2 +- .../graphnet/logic/AbstractLongLogicData.java | 2 +- .../api/graphnet/logic/NetLogicData.java | 15 ++++++---- .../api/graphnet/logic/NetLogicEntryType.java | 6 ++-- .../api/graphnet/logic/NetLogicRegistry.java | 15 ++++++++-- .../pipenet/logic/NetLogicEntryTypes.java | 28 +++++++++++++++++++ .../properties/MaterialEnergyProperties.java | 4 +-- .../net/energy/EnergyTraverseData.java | 2 +- .../pipelike/net/energy/VoltageLossLogic.java | 4 +-- 11 files changed, 69 insertions(+), 18 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java diff --git a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java index e810f01d1e..69a348c89b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java +++ b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.addon.events.KJSRecipeKeyEvent; import com.gregtechceu.gtceu.api.addon.events.MaterialCasingCollectionEvent; import com.gregtechceu.gtceu.api.data.worldgen.bedrockfluid.BedrockFluidDefinition; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.NetLogicEntryTypes; import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; import com.gregtechceu.gtceu.common.data.GTOres; @@ -123,6 +124,12 @@ default void registerFluidVeins() {} */ default void registerBedrockOreVeins() {} + /** + * Initialize custom {@link com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType} instances here. + * @see NetLogicEntryTypes + */ + default void loadNetLogicTypes() {} + /** * Register Material -> Casing block mappings here */ diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java index 4fa56783bb..a321f74617 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java @@ -15,7 +15,7 @@ protected AbstractDoubleLogicData(@NotNull NetLogicEntryType type) { } public T getWith(double value) { - return getType().supplier().get().setValue(value); + return getType().getNew().setValue(value); } protected T setValue(double value) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java index 3aa7284dbd..c328849383 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java @@ -14,7 +14,7 @@ protected AbstractIntLogicData(@NotNull NetLogicEntryType type) { } public T getWith(int value) { - return getType().supplier().get().setValue(value); + return getType().getNew().setValue(value); } protected T setValue(int value) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java index e5a95732b1..58f6dd36cf 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java @@ -15,7 +15,7 @@ protected AbstractLongLogicData(@NotNull NetLogicEntryType type) { } public T getWith(long value) { - return getType().supplier().get().setValue(value); + return getType().getNew().setValue(value); } @Contract("_ -> this") diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index f9ea491914..8bf7001186 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -126,9 +126,9 @@ public boolean hasLogicEntry(@NotNull NetLogicEntry key) { public > T getLogicEntryDefaultable(@NotNull NetLogicEntryType key) { try { T returnable = (T) logicEntrySet.get(key); - return returnable == null ? key.supplier().get() : returnable; + return returnable == null ? key.getNew() : returnable; } catch (ClassCastException ignored) { - return key.supplier().get(); + return key.getNew(); } } @@ -184,8 +184,13 @@ public void deserializeNBT(ListTag nbt) { CompoundTag tag = nbt.getCompound(i); String key = tag.getString("Name"); NetLogicEntry entry = this.logicEntrySet.get(key); - if (entry == null) entry = NetLogicRegistry.getTypeNotNull(key).getNew(); - if (entry == null) continue; + if (entry == null) { + NetLogicEntryType type = NetLogicRegistry.getTypeNullable(key); + if (type == null) { + continue; + } + entry = type.getNew(); + } entry.deserializeNBTNaive(tag.get("Tag")); } } @@ -209,7 +214,7 @@ public void decode(FriendlyByteBuf buf) { String name = buf.readUtf(255); if (name.isEmpty()) continue; NetLogicEntryType type = NetLogicRegistry.getTypeErroring(name); - NetLogicEntry existing = type.supplier().get(); + NetLogicEntry existing = type.getNew(); existing.registerToNetLogicData(this); existing.decode(buf); this.logicEntrySet.put(type, existing); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java index 9b6ba0091c..ad62c1992e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java @@ -1,18 +1,20 @@ package com.gregtechceu.gtceu.api.graphnet.logic; import net.minecraft.util.StringRepresentable; +import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; -public record NetLogicEntryType>(String id, Supplier supplier) +public record NetLogicEntryType>(String id, Supplier<@NotNull T> supplier) implements StringRepresentable { - public NetLogicEntryType(String id, Supplier supplier) { + public NetLogicEntryType(String id, Supplier<@NotNull T> supplier) { this.id = id; this.supplier = supplier; NetLogicRegistry.register(this); } + @NotNull public T getNew() { return supplier.get(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index b2dc4968a6..8558867b98 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -1,6 +1,10 @@ package com.gregtechceu.gtceu.api.graphnet.logic; +import com.gregtechceu.gtceu.api.addon.AddonFinder; +import com.gregtechceu.gtceu.api.addon.IGTAddon; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.NetLogicEntryTypes; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -13,6 +17,11 @@ public final class NetLogicRegistry { private static final Map> REGISTRY = new Object2ObjectOpenHashMap<>(); + static { + NetLogicEntryTypes.init(); + AddonFinder.getAddons().forEach(IGTAddon::loadNetLogicTypes); + } + static void register(NetLogicEntryType entry) { REGISTRY.putIfAbsent(entry.getSerializedName(), entry); } @@ -36,7 +45,7 @@ public static void throwNonexistenceError() { "This suggests that the server and client have different GT versions or modifications."); } - private static class EmptyLogicEntry extends NetLogicEntry { + private static class EmptyLogicEntry extends NetLogicEntry { private static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Empty", EmptyLogicEntry::new); @@ -46,12 +55,12 @@ protected EmptyLogicEntry() { } @Override - public @Nullable CompoundTag serializeNBT() { + public @Nullable Tag serializeNBT() { return new CompoundTag(); } @Override - public void deserializeNBT(CompoundTag arg) {} + public void deserializeNBT(Tag arg) {} @Override public void encode(FriendlyByteBuf buf, boolean fullChange) {} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java new file mode 100644 index 0000000000..90b431114d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; + +import com.gregtechceu.gtceu.api.graphnet.logic.ChannelCountLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.MultiNetCountLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.SuperconductorLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.VoltageLimitLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.VoltageLossLogic; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidContainmentLogic; + +public final class NetLogicEntryTypes { + + public static void init() { + Object type = ChannelCountLogic.TYPE; + type = MultiNetCountLogic.TYPE; + type = ThroughputLogic.TYPE; + type = WeightFactorLogic.TYPE; + type = EdgeCoverReferenceLogic.TYPE; + type = TemperatureLogic.TYPE; + type = EnergyFlowLogic.TYPE; + type = SuperconductorLogic.TYPE; + type = VoltageLimitLogic.TYPE; + type = VoltageLossLogic.TYPE; + type = FluidContainmentLogic.TYPE; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java index 6203b9efda..649992d6b9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java @@ -172,7 +172,7 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { boolean insulated = cable.partialBurnStructure() != null; // insulated cables cool down half as fast float coolingFactor = (float) (Math.sqrt(cable.material()) / (insulated ? 8 : 4)); - data.setLogicEntry(VoltageLossLogic.INSTANCE.supplier().get().getWith(loss)) + data.setLogicEntry(VoltageLossLogic.TYPE.getNew().getWith(loss)) .setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(loss + 0.001 / amperage)) .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(amperage)) .setLogicEntry(VoltageLimitLogic.TYPE.getNew().getWith(voltageLimit)) @@ -188,7 +188,7 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { if (amperage == 0) return; // skip pipes that are too small long loss = getLoss(structure); float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); - data.setLogicEntry(VoltageLossLogic.INSTANCE.supplier().get().getWith(loss)) + data.setLogicEntry(VoltageLossLogic.TYPE.getNew().getWith(loss)) .setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(loss + 0.001 / amperage)) .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(amperage)) .setLogicEntry(VoltageLimitLogic.TYPE.getNew().getWith(voltageLimit)) diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java index da375bdbb7..e9b8046823 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyTraverseData.java @@ -64,7 +64,7 @@ public ReversibleLossOperator traverseToNode(@NotNull WorldPipeNetNode node, lon if (!node.getData().getLogicEntryDefaultable(SuperconductorLogic.TYPE) .canSuperconduct(temperatureLogic == null ? TemperatureLogic.DEFAULT_TEMPERATURE : temperatureLogic.getTemperature(getQueryTick()))) { - pathVoltage -= node.getData().getLogicEntryDefaultable(VoltageLossLogic.INSTANCE).getValue(); + pathVoltage -= node.getData().getLogicEntryDefaultable(VoltageLossLogic.TYPE).getValue(); } NodeLossCache.Key key = NodeLossCache.key(node, this); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java index 47f533974f..2aa47791b4 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java @@ -6,11 +6,11 @@ public final class VoltageLossLogic extends AbstractLongLogicData { - public static final NetLogicEntryType INSTANCE = new NetLogicEntryType<>("VoltageLoss", + public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("VoltageLoss", () -> new VoltageLossLogic().setValue(0)); private VoltageLossLogic() { - super(INSTANCE); + super(TYPE); } @Override From 9fc77e8de4f02338e92a7c0341eba7ab5f8158b2 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Mon, 9 Sep 2024 17:23:50 +0300 Subject: [PATCH 43/70] fix some tint color and frame box issues --- .../graphnet/pipenet/physical/block/PipeBlock.java | 6 ------ .../pipenet/physical/block/PipeMaterialBlock.java | 5 ++++- .../pipenet/physical/tile/PipeBlockEntity.java | 1 + .../client/renderer/pipe/quad/PipeQuadHelper.java | 11 +++++++++++ .../gtceu/common/pipelike/block/cable/CableBlock.java | 2 +- 5 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 4844b3aaf3..65a1b9145c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -429,12 +429,6 @@ public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, Co return shape; } - @Override - public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor level, - BlockPos pos, BlockPos neighborPos) { - return super.updateShape(state, direction, neighborState, level, pos, neighborPos); - } - public boolean hasPipeCollisionChangingItem(BlockGetter world, BlockPos pos, Player player) { return hasPipeCollisionChangingItem(world, pos, player.getMainHandItem()) || hasPipeCollisionChangingItem(world, pos, player.getOffhandItem()) || diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index e1d1a58029..8eb0c0c173 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -61,7 +61,10 @@ public static BlockColor tintedColor() { public int tinted(BlockState blockState, @Nullable BlockAndTintGetter blockAndTintGetter, @Nullable BlockPos blockPos, int index) { - return index == 0 || index == 1 ? material.getMaterialRGB() : -1; + if (index == 0) { + return material.getMaterialRGB(); + } + return index == 1 ? material.getMaterialSecondaryRGB() : -1; } @Nullable diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index d4b67c7403..fdee499dc5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -126,6 +126,7 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity private int paintingColor = -1; @Getter + @Persisted @DescSynced private @Nullable Material frameMaterial; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java index 4cd2898983..68467b65ed 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.client.bakedpipeline.Quad; import net.minecraft.client.renderer.RenderType; @@ -156,6 +157,16 @@ public void setTargetSprite(SpriteInformation sprite) { q.getDirection(), q.getSprite(), q.isShade(), q.hasAmbientOcclusion()); }) .toList()); + for (Direction facing : GTUtil.DIRECTIONS) { + list.addAll(frameModel.getQuads(null, facing, randomSource, modelData, renderType) + .stream() + .map(quad -> { + BakedQuad q = Quad.from(quad, -0.002f).rebake(); + return new BakedQuad(q.getVertices(), q.getTintIndex() + 3, + q.getDirection(), q.getSprite(), q.isShade(), q.hasAmbientOcclusion()); + }) + .toList()); + } return list; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index b822181ef7..9798795301 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -45,7 +45,7 @@ public CableBlock(BlockBehaviour.Properties properties, CableStructure structure public int tinted(BlockState blockState, @Nullable BlockAndTintGetter blockAndTintGetter, @Nullable BlockPos blockPos, int index) { - if (getStructure().isInsulated() && index == 0) { + if (getStructure().isInsulated() && index == 1) { return CableModel.DEFAULT_INSULATION_COLOR; } return index == 0 ? material.getMaterialRGB() : -1; From 89f286bf404d924a20546dc3c2a00dbdd5153a32 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Mon, 9 Sep 2024 17:23:58 +0300 Subject: [PATCH 44/70] spotless --- .../gtceu/common/data/machines/GTResearchMachines.java | 2 +- .../gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java | 1 - .../gtceu/common/pipelike/net/optical/DataCapabilityObject.java | 2 -- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java index abd1932f2e..1fa474bcd0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTResearchMachines.java @@ -21,9 +21,9 @@ import com.gregtechceu.gtceu.common.machine.multiblock.electric.research.HPCAMachine; import com.gregtechceu.gtceu.common.machine.multiblock.electric.research.NetworkSwitchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.electric.research.ResearchStationMachine; +import com.gregtechceu.gtceu.common.machine.multiblock.part.ComputationHatchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.DataAccessHatchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.ObjectHolderMachine; -import com.gregtechceu.gtceu.common.machine.multiblock.part.ComputationHatchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.OpticalDataHatchMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.hpca.HPCABridgePartMachine; import com.gregtechceu.gtceu.common.machine.multiblock.part.hpca.HPCAComputationPartMachine; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java index dcdc925678..7ed02d226b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeBlock.java @@ -17,5 +17,4 @@ public MaterialPipeBlock(BlockBehaviour.Properties properties, MaterialPipeStruc public MaterialPipeStructure getStructure() { return (MaterialPipeStructure) super.getStructure(); } - } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java index c5ef1c4037..0dc01795b0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/optical/DataCapabilityObject.java @@ -12,7 +12,6 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import com.gregtechceu.gtceu.common.pipelike.block.optical.IOpticalTransferController; import com.gregtechceu.gtceu.common.pipelike.net.SlowActiveWalker; -import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.Platform; @@ -25,7 +24,6 @@ import org.jetbrains.annotations.Nullable; import java.util.Iterator; -import java.util.Set; public class DataCapabilityObject implements IPipeCapabilityObject, IDataAccess { From 14e0258055a392dbe582c4528707f8bb2dc3a1d0 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Mon, 9 Sep 2024 18:02:31 +0300 Subject: [PATCH 45/70] fix more frame box issues --- .../physical/tile/PipeBlockEntity.java | 3 ++- .../renderer/pipe/AbstractPipeModel.java | 21 +++++++++---------- .../renderer/pipe/cache/ColorQuadCache.java | 21 +++++++++---------- 3 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index fdee499dc5..ab0d29a41d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -724,10 +724,11 @@ public void markAsDirty() { for (Direction facing : GTUtil.DIRECTIONS) { CoverBehavior cover = getCoverHolder().getCoverAtSide(facing); if (cover != null) { - frameMask |= (byte) (1 << facing.ordinal()); + frameMask |= 1 << facing.ordinal(); if (cover.forcePipeRenderConnection()) this.connectionMask |= (byte) (1 << facing.ordinal()); } } + frameMask = (byte) ~frameMask; return ModelData.builder() .with(AbstractPipeModel.THICKNESS_PROPERTY, this.getStructure().getRenderThickness()) .with(AbstractPipeModel.CONNECTED_MASK_PROPERTY, connectionMask) diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index a255d5e040..0217f66d7f 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.client.renderer.pipe; import com.gregtechceu.gtceu.api.data.chemical.material.Material; -import com.gregtechceu.gtceu.api.data.chemical.material.info.MaterialIconType; +import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.client.renderer.pipe.cache.ColorQuadCache; import com.gregtechceu.gtceu.client.renderer.pipe.cache.StructureQuadCache; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererPackage; @@ -9,6 +9,7 @@ import com.gregtechceu.gtceu.client.renderer.pipe.util.CacheKey; import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; +import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.utils.GTUtil; import com.gregtechceu.gtceu.utils.reference.WeakHashSet; @@ -19,7 +20,6 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; @@ -53,7 +53,7 @@ public abstract class AbstractPipeModel { public static ModelProperty COLOR_PROPERTY = new ModelProperty<>(); public static final ModelProperty MATERIAL_PROPERTY = new ModelProperty<>(); - protected final Object2ObjectOpenHashMap frameCache = new Object2ObjectOpenHashMap<>(); + protected final Object2ObjectOpenHashMap frameCache = new Object2ObjectOpenHashMap<>(); protected final Object2ObjectOpenHashMap pipeCache; protected static final WeakHashSet> PIPE_CACHES = new WeakHashSet<>(); @@ -127,20 +127,19 @@ protected static int safeInt(@Nullable Integer integer) { blockedMask, data, coverMask); if (frameMaterial != null) { - ResourceLocation rl = MaterialIconType.frameGt.getBlockModelPath(frameMaterial.getMaterialIconSet(), - true); - ColorQuadCache frame = frameCache.get(rl); + BlockState state = GTBlocks.MATERIAL_BLOCKS.get(TagPrefix.frameGt, frameMaterial).getDefaultState(); + ColorQuadCache frame = frameCache.get(state); if (frame == null) { - BakedModel model = Minecraft.getInstance().getModelManager().getModel(rl); + BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state); frame = new ColorQuadCache(PipeQuadHelper .createFrame(model, randomSource, modelData, renderType)); - frameCache.put(rl, frame); + frameCache.put(state, frame); } List frameQuads = frame .getQuads(new ColorData(GTUtil.convertRGBtoARGB(frameMaterial.getMaterialRGB()))); - for (int i = 0; i < 6; i++) { - if ((frameMask & (1 << i)) > 0) { - quads.add(frameQuads.get(i)); + for (Direction dir : GTUtil.DIRECTIONS) { + if ((frameMask & (1 << dir.ordinal())) > 0) { + quads.addAll(frameQuads.stream().filter(quad -> quad.getDirection() == dir).toList()); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java index 541aed90fc..293520f8cf 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java @@ -7,7 +7,6 @@ import net.minecraftforge.api.distmarker.OnlyIn; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.List; @@ -24,15 +23,15 @@ public ColorQuadCache(List prototypes) { } public List getQuads(ColorData data) { - List existing = cache.get(data); - if (existing == null) { - existing = new ObjectArrayList<>(); - for (BakedQuad quad : prototypes) { - existing.add(quad); - } - cache.put(data, existing); - // if (cache.size() > 20) cache.removeLast(); - } - return existing; + //List existing = cache.get(data); + //if (existing == null) { + // existing = new ObjectArrayList<>(); + // for (BakedQuad quad : prototypes) { + // existing.add(quad); + // } + // cache.put(data, existing); + // // if (cache.size() > 20) cache.removeLast(); + //} + return prototypes; } } From 7f2011fefd90bdb4c4e29811dee8f13849961a10 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 12 Sep 2024 18:16:10 +0300 Subject: [PATCH 46/70] port lots of changes --- .../resources/assets/gtceu/lang/en_ud.json | 2 +- .../resources/assets/gtceu/lang/en_us.json | 2 +- .../gregtechceu/gtceu/api/addon/IGTAddon.java | 3 +- .../api/capability/IPropertyFluidFilter.java | 30 +-- .../gtceu/api/graphnet/IGraphNet.java | 2 +- .../logic/AbstractDoubleLogicData.java | 29 ++- .../graphnet/logic/AbstractIntLogicData.java | 29 ++- .../graphnet/logic/AbstractLongLogicData.java | 29 ++- .../logic/AbstractTransientLogicData.java | 28 +++ .../api/graphnet/logic/ChannelCountLogic.java | 12 +- .../graphnet/logic/MultiNetCountLogic.java | 18 -- .../api/graphnet/logic/NetLogicData.java | 106 +++++----- .../api/graphnet/logic/NetLogicEntry.java | 9 +- .../api/graphnet/logic/NetLogicEntryType.java | 26 --- .../logic/NetLogicRegistrationEvent.java | 23 +++ .../api/graphnet/logic/NetLogicRegistry.java | 103 ++++++---- .../api/graphnet/logic/NetLogicType.java | 45 +++++ .../api/graphnet/logic/ThroughputLogic.java | 12 +- .../api/graphnet/logic/WeightFactorLogic.java | 14 +- .../api/graphnet/pipenet/WorldPipeNet.java | 2 +- .../logic/EdgeCoverReferenceLogic.java | 149 -------------- .../pipenet/logic/NetLogicEntryTypes.java | 3 - .../pipenet/logic/TemperatureLogic.java | 86 ++++---- .../PipeStructureRegistrationEvent.java | 26 +++ .../physical/PipeStructureRegistry.java | 20 +- .../pipenet/physical/block/PipeBlock.java | 14 +- .../physical/block/PipeMaterialBlock.java | 23 +-- .../physical/tile/PipeBlockEntity.java | 80 ++------ .../pipenet/predicate/BlockedPredicate.java | 14 +- .../pipenet/predicate/FilterPredicate.java | 10 +- .../api/graphnet/predicate/EdgePredicate.java | 17 +- .../predicate/EdgePredicateHandler.java | 36 ++-- .../NetPredicateRegistrationEvent.java | 22 +++ .../predicate/NetPredicateRegistry.java | 83 ++++++-- .../graphnet/predicate/NetPredicateType.java | 46 +++++ .../gregtechceu/gtceu/common/CommonProxy.java | 51 +++++ .../gtceu/common/data/GTBlocks.java | 22 ++- .../gtceu/common/data/GTItems.java | 4 + .../gtceu/common/data/GTMachines.java | 2 +- .../gtceu/common/data/GTMaterials.java | 1 - .../data/materials/ElementMaterials.java | 7 +- .../data/materials/FirstDegreeMaterials.java | 18 +- .../data/materials/SecondDegreeMaterials.java | 2 +- .../common/item/PortableScannerBehavior.java | 4 +- .../pipelike/block/cable/CableStructure.java | 18 +- .../pipelike/block/duct/DuctStructure.java | 12 +- .../pipelike/block/laser/LaserPipeBlock.java | 5 +- .../pipelike/block/laser/LaserStructure.java | 10 +- .../block/optical/OpticalPipeBlock.java | 3 +- .../block/optical/OpticalStructure.java | 9 +- .../block/pipe/MaterialPipeStructure.java | 22 ++- .../properties/MaterialEnergyProperties.java | 27 +-- .../properties/MaterialFluidProperties.java | 20 +- .../properties/MaterialItemProperties.java | 10 +- .../pipelike/net/energy/EnergyFlowLogic.java | 50 ++--- .../net/energy/SuperconductorLogic.java | 13 +- .../net/energy/VoltageLimitLogic.java | 13 +- .../pipelike/net/energy/VoltageLossLogic.java | 13 +- .../net/fluid/FluidCapabilityObject.java | 2 + .../net/fluid/FluidContainmentLogic.java | 43 ++-- .../pipelike/net/fluid/FluidFlowLogic.java | 60 ++++++ .../pipelike/net/fluid/FluidTraverseData.java | 29 ++- .../pipelike/net/fluid/WorldFluidNet.java | 12 +- .../pipelike/net/item/ItemFlowLogic.java | 60 ++++++ .../pipelike/net/item/ItemTraverseData.java | 21 ++ .../pipelike/net/item/WorldItemNet.java | 12 +- .../gtceu/data/lang/IntegrationLang.java | 14 +- .../gtceu/data/lang/LangHandler.java | 6 +- .../data/recipe/misc/ComputerRecipes.java | 24 ++- .../jade/element/FluidStackElement.java | 50 +++++ .../jade/provider/PipeTileInfoProvider.java | 187 ++++++++++++++++++ .../integration/top/TheOneProbePlugin.java | 1 + .../top/provider/PipeTileInfoProvider.java | 130 ++++++++++++ .../resources/assets/gtceu/lang/ja_jp.json | 2 +- .../resources/assets/gtceu/lang/ru_ru.json | 2 +- .../resources/assets/gtceu/lang/zh_cn.json | 2 +- .../resources/assets/gtceu/lang/zh_tw.json | 2 +- 77 files changed, 1456 insertions(+), 692 deletions(-) create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java create mode 100644 src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java create mode 100644 src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java create mode 100644 src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java create mode 100644 src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java diff --git a/src/generated/resources/assets/gtceu/lang/en_ud.json b/src/generated/resources/assets/gtceu/lang/en_ud.json index 6fb896036a..f1b5d22534 100644 --- a/src/generated/resources/assets/gtceu/lang/en_ud.json +++ b/src/generated/resources/assets/gtceu/lang/en_ud.json @@ -2841,7 +2841,7 @@ "gtceu.item_filter.empty_item": ")ɯǝʇI oN( ʎʇdɯƎ", "gtceu.item_filter.footer": "ǝpıɹɹǝʌo oʇ ɯǝʇı ɥʇıʍ ʞɔıןƆǝ§", "gtceu.item_list.item_stored": "%d :pǝɹoʇSㄥ§", - "gtceu.item_pipe.priority": "%dɟ§ :ʎʇıɹoıɹԀ6§", + "gtceu.pipe.priority": "%dɟ§ :ʎʇıɹoıɹԀ6§", "gtceu.jade.cleaned_this_second": "s/%s :pɹɐzɐɥ pǝuɐǝןƆ", "gtceu.jade.energy_stored": "∩Ǝ %d / %d", "gtceu.jade.progress_computation": "∩MƆ %s / %s", diff --git a/src/generated/resources/assets/gtceu/lang/en_us.json b/src/generated/resources/assets/gtceu/lang/en_us.json index 70286efb43..aac137a6c6 100644 --- a/src/generated/resources/assets/gtceu/lang/en_us.json +++ b/src/generated/resources/assets/gtceu/lang/en_us.json @@ -2841,7 +2841,7 @@ "gtceu.item_filter.empty_item": "Empty (No Item)", "gtceu.item_filter.footer": "§eClick with item to override", "gtceu.item_list.item_stored": "§7Stored: %d", - "gtceu.item_pipe.priority": "§9Priority: §f%d", + "gtceu.pipe.priority": "§9Priority: §f%d", "gtceu.jade.cleaned_this_second": "Cleaned hazard: %s/s", "gtceu.jade.energy_stored": "%d / %d EU", "gtceu.jade.progress_computation": "%s / %s CWU", diff --git a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java index 69a348c89b..cdad437542 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java +++ b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.addon.events.KJSRecipeKeyEvent; import com.gregtechceu.gtceu.api.addon.events.MaterialCasingCollectionEvent; import com.gregtechceu.gtceu.api.data.worldgen.bedrockfluid.BedrockFluidDefinition; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.NetLogicEntryTypes; import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; import com.gregtechceu.gtceu.common.data.GTOres; @@ -125,7 +126,7 @@ default void registerFluidVeins() {} default void registerBedrockOreVeins() {} /** - * Initialize custom {@link com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType} instances here. + * Initialize custom {@link NetLogicType} instances here. * @see NetLogicEntryTypes */ default void loadNetLogicTypes() {} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java index 1f337b47e3..ab36bfde6d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java @@ -77,29 +77,15 @@ default boolean test(@NotNull FluidStack stack) { /** * Append tooltips about containment info * - * @param tooltip the tooltip to append to - * @param showToolsInfo if the "hold shift" line should mention tool info - * @param showTemperatureInfo if the temperature information should be displayed + * @param tooltip the tooltip to append to */ - default void appendTooltips(@NotNull List tooltip, boolean showToolsInfo, boolean showTemperatureInfo) { - if (GTUtil.isShiftDown()) { - if (showTemperatureInfo) { - tooltip.add(Component.translatable("gtceu.fluid_pipe.max_temperature", - FormattingUtil.formatNumbers(getMaxFluidTemperature()))); - tooltip.add(Component.translatable("gtceu.fluid_pipe.min_temperature", - FormattingUtil.formatNumbers(getMinFluidTemperature()))); - } - if (isGasProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.gas_proof")); - else tooltip.add(Component.translatable("gtceu.fluid_pipe.not_gas_proof")); - if (isPlasmaProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.plasma_proof")); - getContainedAttributes().forEach(a -> a.appendContainerTooltips(tooltip::add)); - } else if (isGasProof() || isPlasmaProof() || !getContainedAttributes().isEmpty()) { - if (showToolsInfo) { - tooltip.add(Component.translatable("gtceu.tooltip.tool_fluid_hold_shift")); - } else { - tooltip.add(Component.translatable("gtceu.tooltip.fluid_pipe_hold_shift")); - } - } + default void appendTooltips(@NotNull List tooltip) { + tooltip.add(Component.translatable("gtceu.fluid_pipe.max_temperature", getMaxFluidTemperature())); + tooltip.add(Component.translatable("gtceu.fluid_pipe.min_temperature", getMinFluidTemperature())); + if (isGasProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.gas_proof")); + else tooltip.add(Component.translatable("gtceu.fluid_pipe.not_gas_proof")); + if (isPlasmaProof()) tooltip.add(Component.translatable("gtceu.fluid_pipe.plasma_proof")); + getContainedAttributes().forEach(a -> a.appendContainerTooltips(tooltip::add)); } /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java index af099245d0..41a0aac219 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java @@ -125,7 +125,7 @@ default AbstractGroupData getBlankGroupData() { */ @NotNull default NetLogicData getDefaultNodeData() { - return new NetLogicData().setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(1)); + return new NetLogicData().setLogicEntry(WeightFactorLogic.TYPE.getWith(1)); } /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java index a321f74617..821d50eb18 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java @@ -3,15 +3,20 @@ import net.minecraft.nbt.DoubleTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.NotNull; +import java.util.function.Supplier; + public abstract class AbstractDoubleLogicData> extends NetLogicEntry { private double value; - protected AbstractDoubleLogicData(@NotNull NetLogicEntryType type) { - super(type); + protected AbstractDoubleLogicData() {} + + protected AbstractDoubleLogicData(double init) { + this.value = init; } public T getWith(double value) { @@ -46,4 +51,24 @@ public void encode(FriendlyByteBuf buf, boolean fullChange) { public void decode(FriendlyByteBuf buf, boolean fullChange) { this.value = buf.readDouble(); } + + @Override + public abstract @NotNull DoubleLogicType getType(); + + public static class DoubleLogicType> extends NetLogicType { + + public DoubleLogicType(@NotNull ResourceLocation name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + super(name, supplier, defaultable); + } + + public DoubleLogicType(@NotNull String namespace, @NotNull String name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + super(namespace, name, supplier, defaultable); + } + + public T getWith(double value) { + return getNew().setValue(value); + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java index c328849383..970e5f97ca 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java @@ -3,14 +3,19 @@ import net.minecraft.nbt.IntTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.NotNull; +import java.util.function.Supplier; + public abstract class AbstractIntLogicData> extends NetLogicEntry { private int value; - protected AbstractIntLogicData(@NotNull NetLogicEntryType type) { - super(type); + protected AbstractIntLogicData() {} + + protected AbstractIntLogicData(int init) { + this.value = init; } public T getWith(int value) { @@ -45,4 +50,24 @@ public void encode(FriendlyByteBuf buf, boolean fullChange) { public void decode(FriendlyByteBuf buf, boolean fullChange) { this.value = buf.readVarInt(); } + + @Override + public abstract @NotNull IntLogicType getType(); + + public static class IntLogicType> extends NetLogicType { + + public IntLogicType(@NotNull ResourceLocation name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + super(name, supplier, defaultable); + } + + public IntLogicType(@NotNull String namespace, @NotNull String name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + super(namespace, name, supplier, defaultable); + } + + public T getWith(int value) { + return getNew().setValue(value); + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java index 58f6dd36cf..92fc75efd4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java @@ -3,15 +3,20 @@ import net.minecraft.nbt.LongTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import java.util.function.Supplier; + public abstract class AbstractLongLogicData> extends NetLogicEntry { private long value; - protected AbstractLongLogicData(@NotNull NetLogicEntryType type) { - super(type); + protected AbstractLongLogicData() {} + + protected AbstractLongLogicData(long init) { + this.value = init; } public T getWith(long value) { @@ -47,4 +52,24 @@ public void encode(FriendlyByteBuf buf, boolean fullChange) { public void decode(FriendlyByteBuf buf, boolean fullChange) { this.value = buf.readVarLong(); } + + @Override + public abstract @NotNull LongLogicType getType(); + + public static class LongLogicType> extends NetLogicType { + + public LongLogicType(@NotNull ResourceLocation name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + super(name, supplier, defaultable); + } + + public LongLogicType(@NotNull String namespace, @NotNull String name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + super(namespace, name, supplier, defaultable); + } + + public T getWith(long value) { + return getNew().setValue(value); + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java new file mode 100644 index 0000000000..968f9e8963 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; +import org.jetbrains.annotations.Nullable; + +public abstract class AbstractTransientLogicData> + extends NetLogicEntry { + + @Override + public final void deserializeNBT(Tag nbt) {} + + @Override + public final @Nullable Tag serializeNBT() { + return null; + } + + @Override + public boolean shouldEncode() { + return false; + } + + @Override + public void encode(FriendlyByteBuf buf, boolean fullChange) {} + + @Override + public void decode(FriendlyByteBuf buf, boolean fullChange) {} +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java index a27f9c780c..b445a1144b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java @@ -1,12 +1,16 @@ package com.gregtechceu.gtceu.api.graphnet.logic; +import com.gregtechceu.gtceu.GTCEu; +import org.jetbrains.annotations.NotNull; + public final class ChannelCountLogic extends AbstractIntLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("ChannelCount", - () -> new ChannelCountLogic().setValue(1)); + public static final IntLogicType TYPE = new IntLogicType<>(GTCEu.MOD_ID, "ChannelCount", + ChannelCountLogic::new, new ChannelCountLogic().setValue(1)); - public ChannelCountLogic() { - super(TYPE); + @Override + public @NotNull IntLogicType getType() { + return TYPE; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java deleted file mode 100644 index e9d72ac92c..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/MultiNetCountLogic.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.gregtechceu.gtceu.api.graphnet.logic; - -public final class MultiNetCountLogic extends AbstractIntLogicData { - - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("MultiNetCount", - () -> new MultiNetCountLogic().setValue(1)); - - public MultiNetCountLogic() { - super(TYPE); - } - - @Override - public MultiNetCountLogic union(NetLogicEntry other) { - if (other instanceof MultiNetCountLogic l) { - return this.getValue() < l.getValue() ? this : l; - } else return this; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index 8bf7001186..f4805b6713 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -30,8 +30,7 @@ public final class NetLogicData implements ITagSerializable, IContentCh @Setter private Runnable onContentsChanged = () -> {}; - // TODO caching logic on simple logics to reduce amount of reduntant creation? - private final Object2ObjectOpenHashMap, NetLogicEntry> logicEntrySet; + private final Object2ObjectOpenHashMap, NetLogicEntry> logicEntrySet; private final WeakHashSet listeners = new WeakHashSet<>(); @@ -39,7 +38,7 @@ public NetLogicData() { logicEntrySet = new Object2ObjectOpenHashMap<>(4); } - private NetLogicData(Object2ObjectOpenHashMap, NetLogicEntry> logicEntrySet) { + private NetLogicData(Object2ObjectOpenHashMap, NetLogicEntry> logicEntrySet) { this.logicEntrySet = logicEntrySet; } @@ -84,7 +83,7 @@ public NetLogicData removeLogicEntry(@NotNull NetLogicEntry key) { return removeLogicEntry(key.getType()); } - public NetLogicData removeLogicEntry(@NotNull NetLogicEntryType key) { + public NetLogicData removeLogicEntry(@NotNull NetLogicType key) { NetLogicEntry entry = logicEntrySet.remove(key); if (entry != null) { entry.deregisterFromNetLogicData(this); @@ -105,31 +104,21 @@ public void markLogicEntryAsUpdated(NetLogicEntry entry, boolean fullChang } } - public boolean hasLogicEntry(@NotNull String key) { - return logicEntrySet.containsKey(key); + public boolean hasLogicEntry(@NotNull NetLogicType type) { + return logicEntrySet.containsKey(type); } public boolean hasLogicEntry(@NotNull NetLogicEntry key) { return logicEntrySet.containsKey(key.getType()); } - @Nullable - public > T getLogicEntryNullable(@NotNull NetLogicEntryType key) { - try { - return (T) logicEntrySet.get(key); - } catch (ClassCastException ignored) { - return null; - } + public > T getLogicEntryNullable(@NotNull NetLogicType type) { + return type.cast(logicEntrySet.get(type)); } @NotNull - public > T getLogicEntryDefaultable(@NotNull NetLogicEntryType key) { - try { - T returnable = (T) logicEntrySet.get(key); - return returnable == null ? key.getNew() : returnable; - } catch (ClassCastException ignored) { - return key.getNew(); - } + public > T getLogicEntryDefaultable(@NotNull NetLogicType type) { + return type.cast(logicEntrySet.getOrDefault(type, type.getDefault())); } @Contract("null, null -> null; !null, _ -> new; _, !null -> new") @@ -141,10 +130,10 @@ public boolean hasLogicEntry(@NotNull NetLogicEntry key) { @Contract("_, _ -> new") public static @NotNull NetLogicData union(@NotNull NetLogicData sourceData, @Nullable NetLogicData targetData) { - Object2ObjectOpenHashMap, NetLogicEntry> newLogic = new Object2ObjectOpenHashMap<>( + Object2ObjectOpenHashMap, NetLogicEntry> newLogic = new Object2ObjectOpenHashMap<>( sourceData.logicEntrySet); if (targetData != null) { - for (NetLogicEntryType key : newLogic.keySet()) { + for (NetLogicType key : newLogic.keySet()) { newLogic.computeIfPresent(key, (k, v) -> v.union(targetData.logicEntrySet.get(k))); } targetData.logicEntrySet.forEach((key, value) -> newLogic.computeIfAbsent(key, k -> value.union(null))); @@ -154,10 +143,10 @@ public boolean hasLogicEntry(@NotNull NetLogicEntry key) { @Contract("_, _ -> new") public static @NotNull NetLogicData union(@NotNull NetLogicData first, @NotNull NetLogicData... others) { - Object2ObjectOpenHashMap, NetLogicEntry> newLogic = new Object2ObjectOpenHashMap<>( + Object2ObjectOpenHashMap, NetLogicEntry> newLogic = new Object2ObjectOpenHashMap<>( first.logicEntrySet); for (NetLogicData other : others) { - for (NetLogicEntryType key : newLogic.keySet()) { + for (NetLogicType key : newLogic.keySet()) { newLogic.computeIfPresent(key, (k, v) -> v.union(other.logicEntrySet.get(k))); } other.logicEntrySet.forEach((key, value) -> newLogic.computeIfAbsent(key, k -> value.union(null))); @@ -170,7 +159,7 @@ public ListTag serializeNBT() { ListTag list = new ListTag(); for (NetLogicEntry entry : getEntries()) { CompoundTag tag = new CompoundTag(); - tag.putString("Name", entry.getType().getSerializedName()); + tag.putString("Type", entry.getType().getSerializedName()); Tag nbt = entry.serializeNBT(); if (nbt != null) tag.put("Tag", nbt); list.add(tag); @@ -182,28 +171,23 @@ public ListTag serializeNBT() { public void deserializeNBT(ListTag nbt) { for (int i = 0; i < nbt.size(); i++) { CompoundTag tag = nbt.getCompound(i); - String key = tag.getString("Name"); - NetLogicEntry entry = this.logicEntrySet.get(key); - if (entry == null) { - NetLogicEntryType type = NetLogicRegistry.getTypeNullable(key); - if (type == null) { - continue; - } - entry = type.getNew(); - } + NetLogicType type = NetLogicRegistry.getTypeNullable(tag.getString("Type")); + if (type == null) continue; + NetLogicEntry entry = this.logicEntrySet.get(type); + if (entry == null) entry = type.getNew(); entry.deserializeNBTNaive(tag.get("Tag")); + this.logicEntrySet.put(type, entry); } } public void encode(FriendlyByteBuf buf) { - buf.writeVarInt(getEntries().size()); + int count = 0; for (NetLogicEntry entry : getEntries()) { - if (entry.shouldEncode()) { - buf.writeUtf(entry.getType().getSerializedName()); - entry.encode(buf, true); - } else { - buf.writeUtf(""); - } + if (entry.shouldEncode()) count++; + } + buf.writeVarInt(count); + for (NetLogicEntry entry : getEntries()) { + if (entry.shouldEncode()) writeEntry(buf, entry, true); } } @@ -211,17 +195,43 @@ public void decode(FriendlyByteBuf buf) { this.logicEntrySet.clear(); int entryCount = buf.readVarInt(); for (int i = 0; i < entryCount; i++) { - String name = buf.readUtf(255); - if (name.isEmpty()) continue; - NetLogicEntryType type = NetLogicRegistry.getTypeErroring(name); - NetLogicEntry existing = type.getNew(); - existing.registerToNetLogicData(this); - existing.decode(buf); - this.logicEntrySet.put(type, existing); + readEntry(buf); } this.logicEntrySet.trim(); } + public static void writeEntry(@NotNull FriendlyByteBuf buf, @NotNull NetLogicEntry entry, boolean fullChange) { + buf.writeVarInt(NetLogicRegistry.getNetworkID(entry)); + buf.writeBoolean(fullChange); + entry.encode(buf, fullChange); + } + + /** + * @return the net logic entry decoded to. + */ + @Nullable + public NetLogicEntry readEntry(@NotNull FriendlyByteBuf buf) { + int id = buf.readVarInt(); + boolean fullChange = buf.readBoolean(); + NetLogicType type = NetLogicRegistry.getType(id); + NetLogicEntry existing = this.getLogicEntryNullable(type); + boolean add = false; + if (existing == null) { + // never partially decode into a new entry + if (!fullChange) return null; + existing = type.getNew(); + add = true; + } + try { + existing.decode(buf, fullChange); + } catch (Exception ignored) { + NetLogicRegistry.throwDecodingError(); + } + // make sure to add after decoding, so we don't notify listeners with an empty logic entry + if (add) this.setLogicEntry(existing); + return existing; + } + /** * Adds a listener to a weak set which is then notified for as long as it is not collected by the garbage collector. * diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java index d2019d2047..3827931561 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java @@ -21,12 +21,7 @@ public abstract class NetLogicEntry, N extends Tag> implements INBTSerializable, IPacket { - @Getter - private final @NotNull NetLogicEntryType type; - - protected NetLogicEntry(@NotNull NetLogicEntryType type) { - this.type = type; - } + public abstract @NotNull NetLogicType getType(); public void deserializeNBTNaive(@Nullable Tag nbt) { if (nbt != null) deserializeNBT((N) nbt); @@ -93,8 +88,6 @@ public T cast(NetLogicEntry entry) { /** * Controls whether this {@link NetLogicEntry} will be synced to the client or not. - * - * @return */ public boolean shouldEncode() { return true; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java deleted file mode 100644 index ad62c1992e..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntryType.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.gregtechceu.gtceu.api.graphnet.logic; - -import net.minecraft.util.StringRepresentable; -import org.jetbrains.annotations.NotNull; - -import java.util.function.Supplier; - -public record NetLogicEntryType>(String id, Supplier<@NotNull T> supplier) - implements StringRepresentable { - - public NetLogicEntryType(String id, Supplier<@NotNull T> supplier) { - this.id = id; - this.supplier = supplier; - NetLogicRegistry.register(this); - } - - @NotNull - public T getNew() { - return supplier.get(); - } - - @Override - public String getSerializedName() { - return id; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java new file mode 100644 index 0000000000..1b57bf28f6 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java @@ -0,0 +1,23 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; +import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; + +import java.util.Comparator; + +public final class NetLogicRegistrationEvent extends Event implements IModBusEvent { + + private final ObjectRBTreeSet> gather = new ObjectRBTreeSet<>( + Comparator.comparing(NetLogicType::getSerializedName)); + + public void accept(NetLogicType type) { + if (!gather.add(type)) + throw new IllegalStateException("Detected a name collision during Net Logic registration!"); + } + + ObjectRBTreeSet> getGather() { + return gather; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index 8558867b98..91ba4e7834 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -1,71 +1,90 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import com.gregtechceu.gtceu.api.addon.AddonFinder; -import com.gregtechceu.gtceu.api.addon.IGTAddon; -import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.NetLogicEntryTypes; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; - -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.lowdragmc.lowdraglib.LDLib; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import net.minecraft.client.Minecraft; + +import net.minecraft.network.chat.Component; +import net.minecraftforge.common.MinecraftForge; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; +import java.util.Set; public final class NetLogicRegistry { - private static final Map> REGISTRY = new Object2ObjectOpenHashMap<>(); + private static final Int2ObjectArrayMap> REGISTRY; + + private static final BiMap NAMES_TO_NETWORK_IDS; static { - NetLogicEntryTypes.init(); - AddonFinder.getAddons().forEach(IGTAddon::loadNetLogicTypes); + NetLogicRegistrationEvent event = new NetLogicRegistrationEvent(); + MinecraftForge.EVENT_BUS.post(event); + Set> gather = event.getGather(); + NAMES_TO_NETWORK_IDS = HashBiMap.create(gather.size()); + REGISTRY = new Int2ObjectArrayMap<>(gather.size()); + int id = 1; + for (NetLogicType type : gather) { + NAMES_TO_NETWORK_IDS.put(id, type.getSerializedName()); + REGISTRY.put(id, type); + id++; + } } - static void register(NetLogicEntryType entry) { - REGISTRY.putIfAbsent(entry.getSerializedName(), entry); + public static String getName(int networkID) { + return NAMES_TO_NETWORK_IDS.get(networkID); } - public static @Nullable NetLogicEntryType getTypeNullable(String name) { - return REGISTRY.get(name); + public static int getNetworkID(@NotNull String name) { + return NAMES_TO_NETWORK_IDS.inverse().get(name); } - public static @NotNull NetLogicEntryType getTypeNotNull(String name) { - return REGISTRY.getOrDefault(name, EmptyLogicEntry.TYPE); + public static int getNetworkID(@NotNull NetLogicType type) { + return getNetworkID(type.getSerializedName()); } - public static @NotNull NetLogicEntryType getTypeErroring(String name) { - NetLogicEntryType type = REGISTRY.get(name); - if (type == null) throwNonexistenceError(); - return type; + public static int getNetworkID(@NotNull NetLogicEntry entry) { + return getNetworkID(entry.getType()); } - public static void throwNonexistenceError() { - throw new RuntimeException("Could not find a matching supplier for an encoded NetLogicEntry. " + - "This suggests that the server and client have different GT versions or modifications."); + public static @Nullable NetLogicType getTypeNullable(int networkID) { + return REGISTRY.get(networkID); } - private static class EmptyLogicEntry extends NetLogicEntry { - - private static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Empty", - EmptyLogicEntry::new); + public static @Nullable NetLogicType getTypeNullable(@NotNull String name) { + return getTypeNullable(getNetworkID(name)); + } - protected EmptyLogicEntry() { - super(TYPE); - } + public static @NotNull NetLogicType getType(int networkID) { + NetLogicType type = REGISTRY.get(networkID); + if (type == null) throwNonexistenceError(); + assert type != null; + return type; + } - @Override - public @Nullable Tag serializeNBT() { - return new CompoundTag(); - } + public static @NotNull NetLogicType getType(@NotNull String name) { + return getType(getNetworkID(name)); + } - @Override - public void deserializeNBT(Tag arg) {} + public static void throwNonexistenceError() { + if (LDLib.isRemote()) disconnect(); + throw new RuntimeException("Could not find the type of an encoded NetLogicEntry. " + + "This suggests that the server and client have different GT versions or modifications."); + } - @Override - public void encode(FriendlyByteBuf buf, boolean fullChange) {} + public static void throwDecodingError() { + if (LDLib.isRemote()) disconnect(); + throw new RuntimeException("Failed to decode an encoded NetLogicEntry. " + + "This suggests that the server and client have different GT versions or modifications."); + } - @Override - public void decode(FriendlyByteBuf buf, boolean fullChange) {} + private static void disconnect() { + if (Minecraft.getInstance().getConnection() != null) + Minecraft.getInstance().getConnection() + .onDisconnect(Component.translatable("gtceu.universal.net_logic_disconnect")); } + + private NetLogicRegistry() {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java new file mode 100644 index 0000000000..ce6f4b48a5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java @@ -0,0 +1,45 @@ +package com.gregtechceu.gtceu.api.graphnet.logic; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.StringRepresentable; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +public class NetLogicType> implements StringRepresentable { + private final @NotNull String name; + private final @NotNull Supplier<@NotNull T> supplier; + private final @NotNull T defaultable; + + public NetLogicType(@NotNull ResourceLocation name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + this.name = name.toString(); + this.supplier = supplier; + this.defaultable = defaultable; + } + + public NetLogicType(@NotNull String namespace, @NotNull String name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + this.name = namespace + ":" + name; + this.supplier = supplier; + this.defaultable = defaultable; + } + + @SuppressWarnings("unchecked") + public T cast(NetLogicEntry entry) { + return (T) entry; + } + + public final @NotNull T getNew() { + return supplier.get(); + } + + public final @NotNull T getDefault() { + return defaultable; + } + + @Override + public final @NotNull String getSerializedName() { + return name; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java index b4d02f0a75..c85cea837e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java @@ -1,12 +1,16 @@ package com.gregtechceu.gtceu.api.graphnet.logic; +import com.gregtechceu.gtceu.GTCEu; +import org.jetbrains.annotations.NotNull; + public final class ThroughputLogic extends AbstractLongLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Throughput", - () -> new ThroughputLogic().setValue(0)); + public static final LongLogicType TYPE = new LongLogicType<>(GTCEu.MOD_ID, "Throughput", + ThroughputLogic::new, new ThroughputLogic()); - private ThroughputLogic() { - super(TYPE); + @Override + public @NotNull LongLogicType getType() { + return TYPE; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java index a5abf68d5b..af79cf7de6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java @@ -1,18 +1,22 @@ package com.gregtechceu.gtceu.api.graphnet.logic; +import com.gregtechceu.gtceu.GTCEu; +import org.jetbrains.annotations.NotNull; + public final class WeightFactorLogic extends AbstractDoubleLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("WeightFactor", - () -> new WeightFactorLogic().setValue(0.1d)); + public static final DoubleLogicType TYPE = new DoubleLogicType<>(GTCEu.MOD_ID, "WeightFactor", + WeightFactorLogic::new, new WeightFactorLogic().setValue(0.1)); - private WeightFactorLogic() { - super(TYPE); + @Override + public @NotNull DoubleLogicType getType() { + return TYPE; } @Override public WeightFactorLogic union(NetLogicEntry other) { if (other instanceof WeightFactorLogic l) { - return getWith(this.getValue() + l.getValue()); + return TYPE.getWith(this.getValue() + l.getValue()); } else return this; } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index d4c743c799..54dc566382 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -101,7 +101,7 @@ protected void updatePredicationInternal(@NotNull WorldPipeNetNode node, @NotNul protected boolean predicateEdge(@NotNull NetEdge edge, @NotNull WorldPipeNetNode source, @Nullable CoverBehavior coverSource, @NotNull WorldPipeNetNode target, @Nullable CoverBehavior coverTarget) { - Map> prevValue = new Object2ObjectOpenHashMap<>( + Map, EdgePredicate> prevValue = new Object2ObjectOpenHashMap<>( edge.getPredicateHandler().getPredicateSet()); edge.getPredicateHandler().clearPredicates(); coverPredication(edge, coverSource, coverTarget); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java deleted file mode 100644 index 3dc2f6d018..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/EdgeCoverReferenceLogic.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; - -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; -import com.gregtechceu.gtceu.utils.DimensionFacingPos; -import com.gregtechceu.gtceu.utils.GTUtil; - -import com.lowdragmc.lowdraglib.Platform; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; - -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.lang.ref.WeakReference; - -public final class EdgeCoverReferenceLogic extends NetLogicEntry { - - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EdgeCoverReference", - EdgeCoverReferenceLogic::new); - - @Nullable - private WeakReference coverSource; - private DimensionFacingPos coverSourcePos; - @Nullable - private WeakReference coverTarget; - private DimensionFacingPos coverTargetPos; - - public EdgeCoverReferenceLogic() { - super(TYPE); - } - - @Contract("_,_ -> this") - public EdgeCoverReferenceLogic coverSource(@NotNull DimensionFacingPos pos, @NotNull CoverBehavior cover) { - this.coverSource = new WeakReference<>(cover); - this.coverSourcePos = pos; - return this; - } - - @Contract("_,_ -> this") - public EdgeCoverReferenceLogic coverTarget(@NotNull DimensionFacingPos pos, @NotNull CoverBehavior cover) { - this.coverTarget = new WeakReference<>(cover); - this.coverTargetPos = pos; - return this; - } - - private @Nullable CoverBehavior getSource() { - if (coverSource == null) return null; - CoverBehavior ref = coverSource.get(); - if (ref == null) { - Level world = Platform.getMinecraftServer().getLevel(coverSourcePos.getDimension()); - if (world == null || !world.isLoaded(coverSourcePos.getPos())) return null; - - BlockEntity tile = world.getBlockEntity(coverSourcePos.getPos()); - if (tile instanceof PipeBlockEntity pipe) { - CoverBehavior cover = pipe.getCoverHolder().getCoverAtSide(coverSourcePos.getFacing()); - if (cover != null) { - this.coverSource = new WeakReference<>(cover); - return cover; - } else { - // the cover doesn't exist, which makes no sense since we have a reference to its location but - // whatever - this.coverSource = null; - return null; - } - } else { - // the pipe doesn't exist, which makes no sense since the edge holding us exists but whatever - this.coverSource = null; - return null; - } - } else { - return ref; - } - } - - private @Nullable CoverBehavior getTarget() { - if (coverTarget == null) return null; - CoverBehavior ref = coverTarget.get(); - if (ref == null) { - Level world = Platform.getMinecraftServer().getLevel(coverTargetPos.getDimension()); - if (world == null || !world.isLoaded(coverTargetPos.getPos())) return null; - - BlockEntity tile = world.getBlockEntity(coverTargetPos.getPos()); - if (tile instanceof PipeBlockEntity pipe) { - CoverBehavior cover = pipe.getCoverHolder().getCoverAtSide(coverTargetPos.getFacing()); - if (cover != null) { - this.coverTarget = new WeakReference<>(cover); - return cover; - } else { - // the cover doesn't exist, which makes no sense since we have a reference to its location but - // whatever - this.coverTarget = null; - return null; - } - } else { - // the pipe doesn't exist, which makes no sense since the edge holding us exists but whatever - this.coverTarget = null; - return null; - } - } else { - return ref; - } - } - - @Override - public CompoundTag serializeNBT() { - CompoundTag tag = new CompoundTag(); - tag.putLong("SourcePos", coverSourcePos.getPos().asLong()); - tag.putByte("SourceFacing", (byte) coverSourcePos.getFacing().ordinal()); - tag.putString("SourceDim", coverSourcePos.getDimension().location().toString()); - tag.putLong("TargetPos", coverTargetPos.getPos().asLong()); - tag.putByte("TargetFacing", (byte) coverTargetPos.getFacing().ordinal()); - tag.putString("TargetDim", coverTargetPos.getDimension().location().toString()); - return tag; - } - - @Override - public void deserializeNBT(CompoundTag nbt) { - this.coverSourcePos = new DimensionFacingPos(BlockPos.of(nbt.getLong("SourcePos")), - GTUtil.DIRECTIONS[nbt.getByte("SourceFacing")], - ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("SourceDim")))); - this.coverSource = new WeakReference<>(null); - this.coverTargetPos = new DimensionFacingPos(BlockPos.of(nbt.getLong("TargetPos")), - GTUtil.DIRECTIONS[nbt.getByte("TargetFacing")], - ResourceKey.create(Registries.DIMENSION, new ResourceLocation(nbt.getString("TargetDim")))); - this.coverTarget = coverSource; - } - - @Override - public boolean shouldEncode() { - return false; - } - - @Override - public void encode(FriendlyByteBuf buf, boolean fullChange) {} - - @Override - public void decode(FriendlyByteBuf buf, boolean fullChange) {} -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java index 90b431114d..345f2f735c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/NetLogicEntryTypes.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; import com.gregtechceu.gtceu.api.graphnet.logic.ChannelCountLogic; -import com.gregtechceu.gtceu.api.graphnet.logic.MultiNetCountLogic; import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; @@ -14,10 +13,8 @@ public final class NetLogicEntryTypes { public static void init() { Object type = ChannelCountLogic.TYPE; - type = MultiNetCountLogic.TYPE; type = ThroughputLogic.TYPE; type = WeightFactorLogic.TYPE; - type = EdgeCoverReferenceLogic.TYPE; type = TemperatureLogic.TYPE; type = EnergyFlowLogic.TYPE; type = SuperconductorLogic.TYPE; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index 585dc56265..9e47e677b0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -1,11 +1,12 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.logic; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.MultiNodeHelper; import com.gregtechceu.gtceu.api.graphnet.NetNode; import com.gregtechceu.gtceu.api.graphnet.logic.INetLogicEntryListener; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; import com.gregtechceu.gtceu.api.graphnet.pipenet.NodeLossResult; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; @@ -29,8 +30,7 @@ public final class TemperatureLogic extends NetLogicEntry { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Temperature", - TemperatureLogic::new); + public static final TemperatureLogicType TYPE = new TemperatureLogicType(); public static final int DEFAULT_TEMPERATURE = 298; @@ -47,42 +47,9 @@ public final class TemperatureLogic extends NetLogicEntry getType() { + return TYPE; } @Override @@ -322,4 +289,45 @@ public void decode(FriendlyByteBuf buf, boolean fullChange) { else this.partialBurnTemperature = null; } } + + public static class TemperatureLogicType extends NetLogicType { + + public TemperatureLogicType() { + super(GTCEu.MOD_ID, "Temperature", TemperatureLogic::new, new TemperatureLogic()); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum) { + return getWith(temperatureRestorationFunction, temperatureMaximum, 1); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum) { + return getWith(temperatureRestorationFunction, temperatureMaximum, temperatureMinimum, 1000); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum, int thermalMass) { + return getWith(temperatureRestorationFunction, temperatureMaximum, temperatureMinimum, thermalMass, 0); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum, int thermalMass, + @Nullable Integer partialBurnTemperature) { + return getWith(temperatureRestorationFunction, temperatureMaximum, temperatureMinimum, thermalMass, + partialBurnTemperature, 0); + } + + public TemperatureLogic getWith(@NotNull TemperatureLossFunction temperatureRestorationFunction, + int temperatureMaximum, int temperatureMinimum, int thermalMass, + @Nullable Integer partialBurnTemperature, int functionPriority) { + return getNew() + .setRestorationFunction(temperatureRestorationFunction) + .setTemperatureMaximum(temperatureMaximum) + .setTemperatureMinimum(temperatureMinimum) + .setThermalMass(thermalMass) + .setPartialBurnTemperature(partialBurnTemperature) + .setFunctionPriority(functionPriority); + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java new file mode 100644 index 0000000000..f8f1854642 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java @@ -0,0 +1,26 @@ +package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.Set; + +public final class PipeStructureRegistrationEvent extends Event implements IModBusEvent { + + private final Map, Set> registry = new Object2ObjectLinkedOpenHashMap<>(); + + public void register(@NotNull T structure) { + //noinspection unchecked + Set structures = (Set) registry.computeIfAbsent(structure.getClass(), + k -> new ObjectLinkedOpenHashSet<>()); + structures.add(structure); + } + + Map, Set> getRegistry() { + return registry; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java index 5da094110d..1fee935c71 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -4,7 +4,9 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import net.minecraftforge.common.MinecraftForge; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.UnmodifiableView; import java.util.Collections; import java.util.Map; @@ -13,19 +15,15 @@ @SuppressWarnings("unchecked") public final class PipeStructureRegistry { - private static final Map, Set> REGISTRY = new Object2ObjectLinkedOpenHashMap<>(); + private static final Map, Set> REGISTRY = fireEvent(); - public static void register(@NotNull T structure) { - Set structures = (Set) REGISTRY.computeIfAbsent(structure.getClass(), - k -> new ObjectLinkedOpenHashSet<>()); - structures.add(structure); + public static @NotNull @UnmodifiableView Set getStructures(Class structureClass) { + return (Set) REGISTRY.getOrDefault(structureClass, Collections.emptySet()); } - /** - * Do not modify the returned set. - */ - public static @NotNull Set getStructures(Class structureClass) { - GTUtil.forceInitialization(structureClass); - return (Set) REGISTRY.getOrDefault(structureClass, Collections.emptySet()); + private static Map, Set> fireEvent() { + PipeStructureRegistrationEvent event = new PipeStructureRegistrationEvent(); + MinecraftForge.EVENT_BUS.post(event); + return event.getRegistry(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 65a1b9145c..696c3413ef 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -299,20 +299,12 @@ public boolean allowsBlocking() { public static Collection getNodesForTile(PipeBlockEntity tile) { assert tile.getLevel() instanceof ServerLevel; - return tile.getBlockType().getHandler(tile.getLevel(), tile.getBlockPos()) + return tile.getBlockType().getHandler(tile) .getOrCreateFromNets((ServerLevel) tile.getLevel(), tile.getBlockPos(), tile.getStructure()); } - @Override - public void destroy(LevelAccessor level, BlockPos pos, BlockState state) { - super.destroy(level, pos, state); - if (level instanceof ServerLevel serverLevel) { - getHandler(level, pos).removeFromNets(serverLevel, pos, getStructure()); - } - } - @NotNull - protected abstract IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos); + public abstract IPipeNetNodeHandler getHandler(PipeBlockEntity tileContext); @NotNull protected abstract IPipeNetNodeHandler getHandler(@NotNull ItemStack stack); @@ -322,11 +314,11 @@ public void destroy(LevelAccessor level, BlockPos pos, BlockState state) { @Override public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag) { + getHandler(stack).addInformation(stack, level, tooltip, flag, getStructure()); if (getStructure() instanceof IPipeChanneledStructure channeledStructure) { if (channeledStructure.getChannelCount() > 1) tooltip.add(Component.translatable("gtceu.pipe.channels", channeledStructure.getChannelCount())); } - getHandler(stack).addInformation(stack, level, tooltip, flag, getStructure()); if (GTUtil.isShiftDown()) { tooltip.add(Component.translatable(getConnectLangKey())); tooltip.add(Component.translatable("gtceu.tool_action.screwdriver.access_covers")); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java index 8eb0c0c173..0b72328e29 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeMaterialBlock.java @@ -41,18 +41,18 @@ public PipeMaterialBlock(BlockBehaviour.Properties properties, IPipeMaterialStru @OnlyIn(Dist.CLIENT) public static BlockColor tintedColor() { return (blockState, level, blockPos, index) -> { - if (blockState.getBlock() instanceof PipeMaterialBlock block) { - if (blockPos != null && level != null && - level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { - if (pipe.getFrameMaterial() != null) { - if (index >= 3) { - return pipe.getFrameMaterial().getMaterialRGB(index - 3); - } - } - if (index == 0 && pipe.isPainted()) { - return pipe.getPaintingColor(); + if (blockPos != null && level != null && + level.getBlockEntity(blockPos) instanceof PipeBlockEntity pipe) { + if (pipe.getFrameMaterial() != null) { + if (index >= 3) { + return pipe.getFrameMaterial().getMaterialRGB(index - 3); } } + if (index == 0 && pipe.isPainted()) { + return pipe.getPaintingColor(); + } + } + if (blockState.getBlock() instanceof PipeMaterialBlock block) { return block.tinted(blockState, level, blockPos, index); } return -1; @@ -85,7 +85,8 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { } @Override - protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + @NotNull + public IPipeNetNodeHandler getHandler(PipeBlockEntity tile) { return material.getProperty(PropertyKey.PIPENET_PROPERTIES); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index ab0d29a41d..d7a321f99e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -12,7 +12,7 @@ import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicRegistry; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; @@ -100,6 +100,7 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity public static final int UPDATE_PIPE_LOGIC = 0; + @Getter private final Int2ObjectOpenHashMap netLogicDatas = new Int2ObjectOpenHashMap<>(); // this tile was loaded from datafixed NBT and needs to initialize its connections @@ -189,6 +190,8 @@ public boolean triggerEvent(int id, int type) { @Override public void setRemoved() { super.setRemoved(); + if (!level.isClientSide) getBlockType().getHandler(this) + .removeFromNets((ServerLevel) this.level, this.getBlockPos(), this.getStructure()); // TODO I hate this so much can someone please make it so that covers go through getDrops()? getCoverHolder().dropAllCovers(); } @@ -533,15 +536,7 @@ protected void initialize() { int networkID = node.getNet().getNetworkID(); netLogicDatas.put(networkID, node.getData()); node.getData().addListener( - (e, r, f) -> writeCustomData(UPDATE_PIPE_LOGIC, buf -> { - buf.writeVarInt(networkID); - buf.writeUtf(e.getType().id()); - buf.writeBoolean(r); - buf.writeBoolean(f); - if (!r) { - e.encode(buf, f); - } - })); + (e, r, f) -> writeLogicData(networkID, e, r, f)); // Manually resync the data, as it's loaded & the listeners are queried for the first time *before* // we call `addListener` on the line above. for (var entry : node.getData().getEntries()) { @@ -574,31 +569,14 @@ protected void initialize() { } } - /* - * @Override - * public void writeInitialSyncData(@NotNull FriendlyByteBuf buf) { - * buf.writeVarInt(netLogicDatas.size()); - * for (var entry : netLogicDatas.int2ObjectEntrySet()) { - * buf.writeVarInt(entry.getIntKey()); - * entry.getValue().encode(buf); - * } - * } - * - * @Override - * public void receiveInitialSyncData(@NotNull FriendlyByteBuf buf) { - * if (level.isClientSide) { - * netLogicDatas.clear(); - * int count = buf.readVarInt(); - * for (int i = 0; i < count; i++) { - * int networkID = buf.readVarInt(); - * NetLogicData data = new NetLogicData(); - * data.decode(buf); - * netLogicDatas.put(networkID, data); - * } - * } - * scheduleRenderUpdate(); - * } - */ + private void writeLogicData(int networkID, NetLogicEntry entry, boolean removed, boolean fullChange) { + writeCustomData(UPDATE_PIPE_LOGIC, buf -> { + buf.writeVarInt(networkID); + buf.writeBoolean(removed); + if (removed) buf.writeVarInt(NetLogicRegistry.getNetworkID(entry.getType())); + else NetLogicData.writeEntry(buf, entry, fullChange); + }); + } @Override public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { @@ -606,34 +584,16 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { // extra check just to make sure we don't affect actual net data with our writes if (level.isClientSide) { int networkID = buf.readVarInt(); - String identifier = buf.readUtf(255); boolean removed = buf.readBoolean(); - boolean fullChange = buf.readBoolean(); if (removed) { - NetLogicEntryType logic = NetLogicRegistry.getTypeErroring(identifier); - this.netLogicDatas.computeIfPresent(networkID, (k, v) -> v.removeLogicEntry(logic)); + NetLogicType type = NetLogicRegistry.getType(buf.readVarInt()); + NetLogicData data = this.netLogicDatas.get(networkID); + if (data != null) data.removeLogicEntry(type); } else { - if (fullChange) { - NetLogicEntry logic = NetLogicRegistry.getTypeErroring(identifier).getNew(); - logic.decode(buf, true); - this.netLogicDatas.compute(networkID, (k, v) -> { - if (v == null) v = new NetLogicData(); - v.setLogicEntry(logic); - return v; - }); - } else { - NetLogicData data = this.netLogicDatas.get(networkID); - if (data != null) { - NetLogicEntryType logic = NetLogicRegistry.getTypeErroring(identifier); - NetLogicEntry entry = data.getLogicEntryNullable(logic); - if (entry != null) entry.decode(buf, false); - data.markLogicEntryAsUpdated(entry, false); - } else return; - } - if (identifier.equals(TemperatureLogic.TYPE.getSerializedName())) { - TemperatureLogic tempLogic = this.netLogicDatas.get(networkID) - .getLogicEntryNullable(TemperatureLogic.TYPE); - if (tempLogic != null) updateTemperatureLogic(tempLogic); + NetLogicData data = this.netLogicDatas.computeIfAbsent(networkID, i -> new NetLogicData()); + NetLogicEntry read = data.readEntry(buf); + if (read instanceof TemperatureLogic tempLogic) { + updateTemperatureLogic(tempLogic); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java index 00884edb88..02f66751a5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/BlockedPredicate.java @@ -1,6 +1,8 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.predicate; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.NetPredicateType; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import net.minecraft.nbt.ByteTag; @@ -9,16 +11,14 @@ public final class BlockedPredicate extends EdgePredicate { - public static final BlockedPredicate INSTANCE = new BlockedPredicate(); + private static final BlockedPredicate INSTANCE = new BlockedPredicate(); - private BlockedPredicate() { - super("Blocked"); - } + public static final NetPredicateType TYPE = new NetPredicateType<>(GTCEu.MOD_ID, "Blocked", + () -> INSTANCE, INSTANCE); @Override - @Deprecated - public @NotNull BlockedPredicate getNew() { - return INSTANCE; + public @NotNull NetPredicateType getType() { + return TYPE; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java index ef71ea2888..42fbe50bab 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java @@ -1,7 +1,9 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.predicate; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.cover.filter.Filter; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.NetPredicateType; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import net.minecraft.nbt.CompoundTag; @@ -14,15 +16,17 @@ public final class FilterPredicate extends EdgePredicate { - public static final FilterPredicate INSTANCE = new FilterPredicate(); + public static final NetPredicateType TYPE = new NetPredicateType<>(GTCEu.MOD_ID, "Filter", + FilterPredicate::new, new FilterPredicate()); @Setter private @Nullable Filter sourceFilter; @Setter private @Nullable Filter targetFilter; - private FilterPredicate() { - super("FluidFilter"); + @Override + public @NotNull NetPredicateType getType() { + return TYPE; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java index 7787371c3a..a69cd6c2b2 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java @@ -14,19 +14,9 @@ * {@link #union(EdgePredicate)} behavior. */ public abstract class EdgePredicate, N extends Tag> - implements INBTSerializable, StringRepresentable { + implements INBTSerializable { - private final @NotNull String name; - - public EdgePredicate(@NotNull String name) { - this.name = name; - NetPredicateRegistry.register(this); - } - - @Override - public final @NotNull String getSerializedName() { - return name; - } + public abstract @NotNull NetPredicateType getType(); public void deserializeNBTNaive(Tag nbt) { deserializeNBT((N) nbt); @@ -41,9 +31,6 @@ public void deserializeNBTNaive(Tag nbt) { */ public abstract boolean andy(); - @NotNull - public abstract T getNew(); - public abstract boolean test(IPredicateTestObject object); /** diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java index d29adf3813..71c7637861 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java @@ -14,14 +14,9 @@ import java.util.Map; import java.util.function.Predicate; -/** - * Note - since the internal map representation encodes keys using {@link StringRepresentable#getSerializedName()} on - * predicates, - * making a predicate class return two different names is a valid way to register multiple instances. - */ public final class EdgePredicateHandler implements ITagSerializable, Predicate { - private final Map> predicateSet; + private final Map, EdgePredicate> predicateSet; public EdgePredicateHandler() { predicateSet = new Object2ObjectOpenHashMap<>(); @@ -32,7 +27,7 @@ public EdgePredicateHandler() { * nothing happens if a predicate is already present. */ public EdgePredicateHandler mergePredicate(@NotNull EdgePredicate predicate) { - EdgePredicate current = predicateSet.get(predicate.getSerializedName()); + EdgePredicate current = predicateSet.get(predicate.getType()); if (current == null) return setPredicate(predicate); if (predicate.getClass().isInstance(current)) { @@ -45,30 +40,30 @@ public EdgePredicateHandler mergePredicate(@NotNull EdgePredicate predicat /** * Do not modify the returned value */ - public Map> getPredicateSet() { + public Map, EdgePredicate> getPredicateSet() { return predicateSet; } public EdgePredicateHandler setPredicate(@NotNull EdgePredicate predicate) { - predicateSet.put(predicate.getSerializedName(), predicate); + predicateSet.put(predicate.getType(), predicate); return this; } public EdgePredicateHandler removePredicate(@NotNull EdgePredicate predicate) { - return removePredicate(predicate.getSerializedName()); + return removePredicate(predicate.getType()); } - public EdgePredicateHandler removePredicate(String key) { - predicateSet.remove(key); + public EdgePredicateHandler removePredicate(@NotNull NetPredicateType type) { + predicateSet.remove(type); return this; } public boolean hasPredicate(@NotNull EdgePredicate predicate) { - return predicateSet.containsKey(predicate.getSerializedName()); + return hasPredicate(predicate.getType()); } - public boolean hasPredicate(String key) { - return predicateSet.containsKey(key); + public boolean hasPredicate(@NotNull NetPredicateType type) { + return predicateSet.containsKey(type); } public void clearPredicates() { @@ -99,7 +94,7 @@ public ListTag serializeNBT() { for (EdgePredicate entry : predicateSet.values()) { CompoundTag tag = new CompoundTag(); tag.put("Tag", entry.serializeNBT()); - tag.putString("Name", entry.getSerializedName()); + tag.putString("Type", entry.getType().getSerializedName()); list.add(tag); } return list; @@ -109,10 +104,11 @@ public ListTag serializeNBT() { public void deserializeNBT(ListTag nbt) { for (int i = 0; i < nbt.size(); i++) { CompoundTag tag = nbt.getCompound(i); - String key = tag.getString("Name"); - EdgePredicate entry = this.predicateSet.get(key); - if (entry == null) entry = NetPredicateRegistry.getSupplierNotNull(key).get(); - if (entry == null) continue; + NetPredicateType type = NetPredicateRegistry.getType(tag.getString("Type")); + EdgePredicate entry = this.predicateSet.get(type); + if (entry == null) { + entry = type.getNew(); + } entry.deserializeNBTNaive(tag.get("Tag")); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java new file mode 100644 index 0000000000..7149683c6c --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java @@ -0,0 +1,22 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate; + +import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; + +import java.util.Comparator; + +public final class NetPredicateRegistrationEvent extends Event implements IModBusEvent { + + private final ObjectRBTreeSet> gather = new ObjectRBTreeSet<>( + Comparator.comparing(NetPredicateType::getSerializedName)); + + public void accept(NetPredicateType type) { + if (!gather.add(type)) + throw new IllegalStateException("Detected a name collision during Net Predicate registration!"); + } + + ObjectRBTreeSet> getGather() { + return gather; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java index ccf99b289a..03f0788976 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java @@ -1,36 +1,89 @@ package com.gregtechceu.gtceu.api.graphnet.predicate; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.lowdragmc.lowdraglib.LDLib; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; +import net.minecraftforge.common.MinecraftForge; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; -import java.util.function.Supplier; +import java.util.Set; public final class NetPredicateRegistry { - private static final Map>> REGISTRY = new Object2ObjectOpenHashMap<>(); + private static final Int2ObjectArrayMap> REGISTRY; - static void register(@NotNull EdgePredicate predicate) { - REGISTRY.putIfAbsent(predicate.getSerializedName(), predicate::getNew); + private static final BiMap NAMES_TO_NETWORK_IDS; + + static { + NetPredicateRegistrationEvent event = new NetPredicateRegistrationEvent(); + MinecraftForge.EVENT_BUS.post(event); + Set> gather = event.getGather(); + NAMES_TO_NETWORK_IDS = HashBiMap.create(gather.size()); + REGISTRY = new Int2ObjectArrayMap<>(gather.size()); + int id = 1; + for (NetPredicateType type : gather) { + NAMES_TO_NETWORK_IDS.put(id, type.getSerializedName()); + REGISTRY.put(id, type); + id++; + } + } + + public static String getName(int networkID) { + return NAMES_TO_NETWORK_IDS.get(networkID); + } + + public static int getNetworkID(@NotNull String name) { + return NAMES_TO_NETWORK_IDS.inverse().get(name); + } + + public static int getNetworkID(@NotNull NetPredicateType type) { + return getNetworkID(type.getSerializedName()); + } + + public static int getNetworkID(@NotNull EdgePredicate entry) { + return getNetworkID(entry.getType()); } - public static @Nullable Supplier<@NotNull EdgePredicate> getSupplierNullable(String name) { - return REGISTRY.get(name); + public static @Nullable NetPredicateType getTypeNullable(int networkID) { + return REGISTRY.get(networkID); } - public static @NotNull Supplier<@Nullable EdgePredicate> getSupplierNotNull(String name) { - return REGISTRY.getOrDefault(name, () -> null); + public static @Nullable NetPredicateType getTypeNullable(@NotNull String name) { + return getTypeNullable(getNetworkID(name)); } - public static @NotNull Supplier> getSupplierErroring(String name) { - Supplier> supplier = REGISTRY.get(name); - if (supplier == null) throwNonexistenceError(); - return supplier; + public static @NotNull NetPredicateType getType(int networkID) { + NetPredicateType type = REGISTRY.get(networkID); + if (type == null) throwNonexistenceError(); + assert type != null; + return type; + } + + public static @NotNull NetPredicateType getType(@NotNull String name) { + return getType(getNetworkID(name)); } public static void throwNonexistenceError() { - throw new RuntimeException("Could not find a matching supplier for an encoded EdgePredicate. " + + if (LDLib.isRemote()) disconnect(); + throw new RuntimeException("Could not find the type of an encoded EdgePredicate. " + + "This suggests that the server and client have different GT versions or modifications."); + } + + public static void throwDecodingError() { + if (LDLib.isRemote()) disconnect(); + throw new RuntimeException("Failed to decode an encoded EdgePredicate. " + "This suggests that the server and client have different GT versions or modifications."); } + + private static void disconnect() { + if (Minecraft.getInstance().getConnection() != null) + Minecraft.getInstance().getConnection() + .onDisconnect(Component.translatable("gtceu.universal.net_predicate_disconnect")); + } + + private NetPredicateRegistry() {} } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java new file mode 100644 index 0000000000..fa2517103e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java @@ -0,0 +1,46 @@ +package com.gregtechceu.gtceu.api.graphnet.predicate; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.StringRepresentable; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +public class NetPredicateType> implements StringRepresentable { + + private final String name; + private final @NotNull Supplier<@NotNull T> supplier; + private final @NotNull T defaultable; + + public NetPredicateType(@NotNull ResourceLocation name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + this.name = name.toString(); + this.supplier = supplier; + this.defaultable = defaultable; + } + + public NetPredicateType(@NotNull String namespace, @NotNull String name, @NotNull Supplier<@NotNull T> supplier, + @NotNull T defaultable) { + this.name = namespace + ":" + name; + this.supplier = supplier; + this.defaultable = defaultable; + } + + @SuppressWarnings("unchecked") + public T cast(EdgePredicate predicate) { + return (T) predicate; + } + + public final @NotNull T getNew() { + return supplier.get(); + } + + public final @NotNull T getDefault() { + return defaultable; + } + + @Override + public @NotNull String getSerializedName() { + return name; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java index f1b931e29a..232a7aa8ad 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java @@ -16,6 +16,15 @@ import com.gregtechceu.gtceu.api.data.worldgen.WorldGenLayers; import com.gregtechceu.gtceu.api.data.worldgen.generator.IndicatorGenerators; import com.gregtechceu.gtceu.api.data.worldgen.generator.VeinGenerators; +import com.gregtechceu.gtceu.api.graphnet.logic.ChannelCountLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicRegistrationEvent; +import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; +import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; +import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.BlockedPredicate; +import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.FilterPredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.NetPredicateRegistrationEvent; import com.gregtechceu.gtceu.api.gui.factory.CoverUIFactory; import com.gregtechceu.gtceu.api.gui.factory.GTUIEditorFactory; import com.gregtechceu.gtceu.api.gui.factory.MachineUIFactory; @@ -29,6 +38,18 @@ import com.gregtechceu.gtceu.common.data.materials.GTFoods; import com.gregtechceu.gtceu.common.item.tool.rotation.CustomBlockRotations; import com.gregtechceu.gtceu.common.network.GTNetwork; +import com.gregtechceu.gtceu.common.pipelike.block.cable.CableStructure; +import com.gregtechceu.gtceu.common.pipelike.block.duct.DuctStructure; +import com.gregtechceu.gtceu.common.pipelike.block.laser.LaserStructure; +import com.gregtechceu.gtceu.common.pipelike.block.optical.OpticalStructure; +import com.gregtechceu.gtceu.common.pipelike.block.pipe.MaterialPipeStructure; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.SuperconductorLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.VoltageLimitLogic; +import com.gregtechceu.gtceu.common.pipelike.net.energy.VoltageLossLogic; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidContainmentLogic; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.item.ItemFlowLogic; import com.gregtechceu.gtceu.common.registry.GTRegistration; import com.gregtechceu.gtceu.common.unification.material.MaterialRegistryManager; import com.gregtechceu.gtceu.config.ConfigHolder; @@ -225,6 +246,36 @@ public void modConstruct(FMLConstructModEvent event) { event.enqueueWork(CommonProxy::init); } + @SubscribeEvent + public static void registerPipeStructures(PipeStructureRegistrationEvent event) { + CableStructure.register(event); + MaterialPipeStructure.register(event); + LaserStructure.register(event); + OpticalStructure.register(event); + DuctStructure.register(event); + } + + @SubscribeEvent + public static void registerNetLogics(NetLogicRegistrationEvent event) { + event.accept(ChannelCountLogic.TYPE); + event.accept(EnergyFlowLogic.TYPE); + event.accept(FluidFlowLogic.TYPE); + event.accept(ItemFlowLogic.TYPE); + event.accept(FluidContainmentLogic.TYPE); + event.accept(SuperconductorLogic.TYPE); + event.accept(TemperatureLogic.TYPE); + event.accept(ThroughputLogic.TYPE); + event.accept(WeightFactorLogic.TYPE); + event.accept(VoltageLimitLogic.TYPE); + event.accept(VoltageLossLogic.TYPE); + } + + @SubscribeEvent + public static void registerNetPredicates(NetPredicateRegistrationEvent event) { + event.accept(BlockedPredicate.TYPE); + event.accept(FilterPredicate.TYPE); + } + @SubscribeEvent public void commonSetup(FMLCommonSetupEvent event) { event.enqueueWork(() -> { diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index 1c9ee68332..f6b9cf7bd3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -144,10 +144,24 @@ public class GTBlocks { .defaultLoot() .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) .addLayer(() -> RenderType::cutoutMipped) - .color(() -> () -> (state, level, pos, color) -> color) + .color(() -> PipeMaterialBlock::tintedColor) .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) - .color(() -> () -> (stack, color) -> color) + .color(() -> () -> (stack, color) -> -1) + .build() + .register(); + public static final BlockEntry LASER_REFLECTOR_PIPE = REGISTRATE + .block("laser_reflector_pipe", (p) -> new LaserPipeBlock(p, LaserStructure.MIRROR)) + .initialProperties(() -> Blocks.IRON_BLOCK) + .properties(p -> p.dynamicShape().noOcclusion().forceSolidOn()) + .blockstate(NonNullBiConsumer.noop()) + .defaultLoot() + .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) + .addLayer(() -> RenderType::cutoutMipped) + .color(() -> PipeMaterialBlock::tintedColor) + .item(PipeBlockItem::new) + .model(NonNullBiConsumer.noop()) + .color(() -> () -> (stack, color) -> -1) .build() .register(); public static final BlockEntry OPTICAL_PIPE = REGISTRATE @@ -157,11 +171,11 @@ public class GTBlocks { .blockstate(NonNullBiConsumer.noop()) .defaultLoot() .tag(GTToolType.WIRE_CUTTER.harvestTags.get(0)) - .color(() -> () -> (state, level, pos, color) -> color) + .color(() -> PipeMaterialBlock::tintedColor) .addLayer(() -> RenderType::cutoutMipped) .item(PipeBlockItem::new) .model(NonNullBiConsumer.noop()) - .color(() -> () -> (stack, color) -> color) + .color(() -> () -> (stack, color) -> -1) .build() .register(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java index 2f0604d2a7..23b63307f9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java @@ -2708,6 +2708,10 @@ public Component getItemName(ItemStack stack) { public static ItemEntry BLACKLIGHT = REGISTRATE.item("blacklight", Item::new) .onRegister(compassNode(GTCompassSections.MISC)).register(); + public static ItemEntry LASER_REFLECTOR = REGISTRATE + .item("dielectric_laser_mirror", Item::new) + .onRegister(compassNode(GTCompassSections.MISC)).register(); + public static ItemEntry RUBBER_BOAT = REGISTRATE .item("rubber_boat", p -> new GTBoatItem(false, GTBoat.BoatType.RUBBER, new Item.Properties())) .lang("Rubber Boat") diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java index d1fb98c2c9..4621237371 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java @@ -690,7 +690,7 @@ public static BiConsumer> createTankTooltips(String n if (material.hasProperty(PropertyKey.PIPENET_PROPERTIES)) { MaterialFluidProperties pipeprops = material.getProperty(PropertyKey.PIPENET_PROPERTIES) .getProperty(MaterialFluidProperties.KEY); - pipeprops.appendTooltips(list, true, true); + pipeprops.appendTooltips(list); } } }; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java index 15809e6006..7c5b1463f0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java @@ -219,7 +219,6 @@ public static void init() { plateDouble.setIgnored(BorosilicateGlass); plateDouble.setIgnored(Wood); plateDouble.setIgnored(TreatedWood); - plate.setIgnored(BorosilicateGlass); foil.setIgnored(BorosilicateGlass); dustSmall.setIgnored(Lapotron); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java index eb15074b3e..cbf29a178d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/ElementMaterials.java @@ -98,7 +98,7 @@ public static void register() { .liquid(new FluidBuilder().temperature(1560)) .ore() .color(0x73d73d).secondaryColor(0x184537).iconSet(METALLIC) - .appendFlags(STD_METAL) + .appendFlags(STD_METAL, GENERATE_FOIL) .hazard(HazardProperty.HazardTrigger.SKIN_CONTACT, GTMedicalConditions.BERYLLIOSIS, false) .element(GTElements.Be) .buildAndRegister(); @@ -840,7 +840,8 @@ public static void register() { Titanium = new Material.Builder(GTCEu.id("titanium")) // todo Ore? Look at EBF recipe here if we do Ti ores .ingot(3).fluid() .color(0xed8eea).secondaryColor(0xff64bc).iconSet(METALLIC) - .appendFlags(EXT2_METAL, GENERATE_ROTOR, GENERATE_SMALL_GEAR, GENERATE_GEAR, GENERATE_FRAME) + .appendFlags(EXT2_METAL, GENERATE_ROTOR, GENERATE_SMALL_GEAR, GENERATE_GEAR, GENERATE_FRAME, + GENERATE_FOIL) .element(GTElements.Ti) .toolStats(ToolProperty.Builder.of(8.0F, 6.0F, 1536, 3) .enchantability(14).build()) @@ -996,7 +997,7 @@ public static void register() { Trinium = new Material.Builder(GTCEu.id("trinium")) .ingot(7).fluid() .color(0x81808a).secondaryColor(0x351d4b).iconSet(SHINY) - .flags(GENERATE_FOIL, GENERATE_BOLT_SCREW, GENERATE_GEAR) + .flags(GENERATE_FOIL, GENERATE_BOLT_SCREW, GENERATE_GEAR, GENERATE_FRAME) .element(GTElements.Ke) .cableProperties(GTValues.V[7], 6, 4) .blastTemp(7200, GasTier.HIGH, GTValues.VA[GTValues.LuV], 1500) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java index 45aa6b96af..af44a8edc0 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java @@ -1299,7 +1299,7 @@ public static void register() { .color(0xE1B454).secondaryColor(0x223033).iconSet(METALLIC) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Manganese, 1, Phosphorus, 1) - .cableProperties(GTValues.V[GTValues.LV], 2, GTValues.V[GTValues.ULV], 500) + .cableProperties(GTValues.V[GTValues.LV], 2, GTValues.V[GTValues.ULV], Integer.MAX_VALUE) .blastTemp(1200, GasTier.LOW) .buildAndRegister(); @@ -1309,7 +1309,7 @@ public static void register() { .color(0x603c1a).secondaryColor(0x423e39).iconSet(METALLIC) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Magnesium, 1, Boron, 2) - .cableProperties(GTValues.V[GTValues.MV], 4, GTValues.V[GTValues.LV], 500) + .cableProperties(GTValues.V[GTValues.MV], 4, GTValues.V[GTValues.LV], Integer.MAX_VALUE) .blastTemp(2500, GasTier.LOW, GTValues.VA[HV], 1000) .buildAndRegister(); @@ -1319,7 +1319,7 @@ public static void register() { .color(0x928547).secondaryColor(0x3f2e2e).iconSet(SHINY) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Mercury, 1, Barium, 2, Calcium, 2, Copper, 3, Oxygen, 8) - .cableProperties(GTValues.V[GTValues.HV], 4, GTValues.V[GTValues.MV], 500) + .cableProperties(GTValues.V[GTValues.HV], 4, GTValues.V[GTValues.MV], Integer.MAX_VALUE) .blastTemp(3300, GasTier.LOW, GTValues.VA[HV], 1500) .buildAndRegister(); @@ -1329,7 +1329,7 @@ public static void register() { .color(0x457045).secondaryColor(0x66ff00).iconSet(RADIOACTIVE) .flags(DECOMPOSITION_BY_CENTRIFUGING) .components(Uranium238, 1, Platinum, 3) - .cableProperties(GTValues.V[GTValues.EV], 6, GTValues.V[GTValues.HV], 500) + .cableProperties(GTValues.V[GTValues.EV], 6, GTValues.V[GTValues.HV], Integer.MAX_VALUE) .blastTemp(4400, GasTier.MID, GTValues.VA[GTValues.EV], 1000) .buildAndRegister() .setFormula("UPt3", true); @@ -1340,7 +1340,7 @@ public static void register() { .color(0x850e85).secondaryColor(0x332f33).iconSet(SHINY) .flags(DECOMPOSITION_BY_CENTRIFUGING) .components(Samarium, 1, Iron, 1, Arsenic, 1, Oxygen, 1) - .cableProperties(GTValues.V[GTValues.IV], 6, GTValues.V[GTValues.EV], 500) + .cableProperties(GTValues.V[GTValues.IV], 6, GTValues.V[GTValues.EV], Integer.MAX_VALUE) .blastTemp(5200, GasTier.MID, GTValues.VA[GTValues.EV], 1500) .buildAndRegister(); @@ -1350,7 +1350,7 @@ public static void register() { .color(0x686760).secondaryColor(0x673300).iconSet(METALLIC) .flags(DECOMPOSITION_BY_ELECTROLYZING, GENERATE_FINE_WIRE) .components(Indium, 4, Tin, 2, Barium, 2, Titanium, 1, Copper, 7, Oxygen, 14) - .cableProperties(GTValues.V[GTValues.LuV], 8, GTValues.V[GTValues.IV], 500) + .cableProperties(GTValues.V[GTValues.LuV], 8, GTValues.V[GTValues.IV], Integer.MAX_VALUE) .blastTemp(6000, GasTier.HIGH, GTValues.VA[GTValues.IV], 1000) .buildAndRegister(); @@ -1360,7 +1360,7 @@ public static void register() { .color(0x232020).secondaryColor(0xff009c).iconSet(RADIOACTIVE) .flags(DECOMPOSITION_BY_CENTRIFUGING, GENERATE_FINE_WIRE) .components(Uranium238, 1, Rhodium, 1, Naquadah, 2) - .cableProperties(GTValues.V[GTValues.ZPM], 8, GTValues.V[LuV], 500) + .cableProperties(GTValues.V[GTValues.ZPM], 8, GTValues.V[LuV], Integer.MAX_VALUE) .blastTemp(9000, GasTier.HIGH, GTValues.VA[GTValues.IV], 1500) .buildAndRegister() .setFormula("URhNq2", true); @@ -1372,7 +1372,7 @@ public static void register() { .color(0xc6b083).secondaryColor(0x45063d).iconSet(METALLIC) .flags(DECOMPOSITION_BY_CENTRIFUGING, GENERATE_FINE_WIRE) .components(NaquadahEnriched, 4, Trinium, 3, Europium, 2, Duranium, 1) - .cableProperties(GTValues.V[GTValues.UV], 16, GTValues.V[GTValues.ZPM], 500) + .cableProperties(GTValues.V[GTValues.UV], 16, GTValues.V[GTValues.ZPM], Integer.MAX_VALUE) .blastTemp(9900, GasTier.HIGH, GTValues.VA[GTValues.LuV], 1000) .buildAndRegister(); @@ -1382,7 +1382,7 @@ public static void register() { .color(0x897b76).secondaryColor(0x00c0ff).iconSet(RADIOACTIVE) .flags(DECOMPOSITION_BY_ELECTROLYZING) .components(Ruthenium, 1, Trinium, 2, Americium, 1, Neutronium, 2, Oxygen, 8) - .cableProperties(GTValues.V[GTValues.UHV], 24, GTValues.V[GTValues.UV], 500) + .cableProperties(GTValues.V[GTValues.UHV], 24, GTValues.V[GTValues.UV], Integer.MAX_VALUE) .blastTemp(10800, GasTier.HIGHER) .buildAndRegister(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java index aebdcd0b7d..53bdcfe073 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/SecondDegreeMaterials.java @@ -321,7 +321,7 @@ public static void register() { .ingot(1) .liquid(new FluidBuilder().temperature(1921)) .color(0xFAFAFA).secondaryColor(0xfaf5c0).iconSet(SHINY) - .flags(GENERATE_FINE_WIRE, GENERATE_PLATE) + .flags(GENERATE_FINE_WIRE, GENERATE_PLATE, NO_SMASHING) .components(Boron, 1, SiliconDioxide, 7) .buildAndRegister(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index 634089829f..97b8148af3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -377,12 +377,12 @@ else if (machine instanceof IDataInfoProvider) int cumulativeCount = 0; long cumulativeVoltage = 0; long cumulativeAmperage = 0; - for (var memory : data.getLogicEntryDefaultable(EnergyFlowLogic.TYPE).getMemory().entrySet()) { + for (var memory : data.getLogicEntryDefaultable(EnergyFlowLogic.TYPE).getMemory().values()) { cumulativeCount++; int count = 0; double voltage = 0; long amperage = 0; - for (EnergyFlowData flow : memory.getValue()) { + for (EnergyFlowData flow : memory) { count++; long prev = amperage; amperage += flow.amperage(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index 57d76f90f5..48fecbca84 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IInsulatable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; @@ -42,10 +43,6 @@ public record CableStructure(String name, int material, int costFactor, TagPrefi public static final CableStructure CABLE_HEX = new CableStructure("hex_cable", 16, 1, TagPrefix.cableGtHex, WIRE_HEX, INSULATION_BURN_TEMP, 1f, PipeModelRegistry.getCableModel(5)); - public CableStructure { - PipeStructureRegistry.register(this); - } - @Override public @NotNull String getSerializedName() { return name; @@ -80,4 +77,17 @@ public boolean isInsulated() { public PipeModelRedirector getModel() { return model; } + + public static void register(@NotNull PipeStructureRegistrationEvent event) { + event.register(WIRE_SINGLE); + event.register(WIRE_DOUBLE); + event.register(WIRE_QUADRUPLE); + event.register(WIRE_OCTAL); + event.register(WIRE_HEX); + event.register(CABLE_SINGLE); + event.register(CABLE_DOUBLE); + event.register(CABLE_QUADRUPLE); + event.register(CABLE_OCTAL); + event.register(CABLE_HEX); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java index 6a2ae71189..ff28287351 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.block.duct; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; @@ -14,10 +15,6 @@ public record DuctStructure(String name, float renderThickness, float rateMultip public static final DuctStructure LARGE = new DuctStructure("large", 0.75f, 8f); public static final DuctStructure HUGE = new DuctStructure("huge", 0.75f, 16f); - public DuctStructure { - PipeStructureRegistry.register(this); - } - @Override public @NotNull String getSerializedName() { return name; @@ -37,4 +34,11 @@ public boolean isPaintable() { public PipeModelRedirector getModel() { return PipeModelRegistry.getDuctModel(); } + + public static void register(@NotNull PipeStructureRegistrationEvent event) { + event.register(SMALL); + event.register(NORMAL); + event.register(LARGE); + event.register(HUGE); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java index d4b075f68e..401b8ff2a9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java @@ -2,6 +2,8 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.ActivablePipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.LaserNetHandler; @@ -34,7 +36,8 @@ public boolean allowsBlocking() { } @Override - protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + @NotNull + public IPipeNetNodeHandler getHandler(PipeBlockEntity tileContext) { return LaserNetHandler.INSTANCE; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java index 20f4713507..ff0a874643 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.block.laser; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; @@ -21,10 +22,6 @@ public record LaserStructure(String name, float renderThickness, boolean mirror, public static final LaserStructure MIRROR = new LaserStructure("laser_pipe_mirror", 0.5f, true, PipeModelRegistry.getLaserModel()); - public LaserStructure { - PipeStructureRegistry.register(this); - } - @Override public ResourceTexture getPipeTexture(boolean isBlock) { return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; @@ -72,4 +69,9 @@ public boolean isPaintable() { public PipeModelRedirector getModel() { return model; } + + public static void register(@NotNull PipeStructureRegistrationEvent event) { + event.register(NORMAL); + event.register(MIRROR); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java index 5f80da6dc3..ef80607190 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.ActivablePipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.DuctNetHandler; @@ -34,7 +35,7 @@ public boolean allowsBlocking() { } @Override - protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + public IPipeNetNodeHandler getHandler(PipeBlockEntity tileContext) { return DuctNetHandler.INSTANCE; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java index dcc46d47b0..84b1db419f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.common.pipelike.block.optical; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; @@ -19,10 +20,6 @@ public record OpticalStructure(String name, float renderThickness, PipeModelRedi public static final OpticalStructure INSTANCE = new OpticalStructure("optical_pipe_normal", 0.375f, PipeModelRegistry.getOpticalModel()); - public OpticalStructure { - PipeStructureRegistry.register(this); - } - @Override public ResourceTexture getPipeTexture(boolean isBlock) { return isBlock ? GuiTextures.TOOL_WIRE_CONNECT : GuiTextures.TOOL_WIRE_BLOCK; @@ -60,4 +57,8 @@ public boolean isPaintable() { public PipeModelRedirector getModel() { return model; } + + public static void register(@NotNull PipeStructureRegistrationEvent event) { + event.register(INSTANCE); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java index d22e559607..be1c680824 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeChanneledStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; @@ -47,10 +48,6 @@ public record MaterialPipeStructure(String name, int material, int channelCount, "nonuple_restrictive", 18, 9, true, TagPrefix.pipeNonupleRestrictive, 0.95f, PipeModelRegistry.getPipeRestrictiveModel(6)); - public MaterialPipeStructure { - PipeStructureRegistry.register(this); - } - @Override public @NotNull String getSerializedName() { return name; @@ -80,4 +77,21 @@ public PipeModelRedirector getModel() { public boolean isPaintable() { return true; } + + public static void register(@NotNull PipeStructureRegistrationEvent event) { + event.register(TINY); + event.register(SMALL); + event.register(NORMAL); + event.register(LARGE); + event.register(HUGE); + event.register(QUADRUPLE); + event.register(NONUPLE); + event.register(TINY_RESTRICTIVE); + event.register(SMALL_RESTRICTIVE); + event.register(NORMAL_RESTRICTIVE); + event.register(LARGE_RESTRICTIVE); + event.register(HUGE_RESTRICTIVE); + event.register(QUADRUPLE_RESTRICTIVE); + event.register(NONUPLE_RESTRICTIVE); + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java index 649992d6b9..46601ecdee 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java @@ -111,9 +111,12 @@ public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNu tooltip.add(Component.translatable("gtceu.cable.superconductor", GTValues.VN[tier])); tooltip.add(Component.translatable("gtceu.cable.voltage", voltageLimit, GTValues.VNF[tier])); tooltip.add(Component.translatable("gtceu.cable.amperage", getAmperage(structure))); - tooltip.add(Component.translatable("gtceu.cable.loss_per_block", getLoss(structure))); - if (isSuperconductor()) + long loss = isSuperconductor() && superconductorCriticalTemperature == Integer.MAX_VALUE ? 0 : + getLoss(structure); + tooltip.add(Component.translatable("gtceu.cable.loss_per_block", loss)); + if (isSuperconductor() && superconductorCriticalTemperature != Integer.MAX_VALUE) { tooltip.add(Component.translatable("gtceu.cable.superconductor_loss", superconductorCriticalTemperature)); + } } @Override @@ -172,31 +175,31 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { boolean insulated = cable.partialBurnStructure() != null; // insulated cables cool down half as fast float coolingFactor = (float) (Math.sqrt(cable.material()) / (insulated ? 8 : 4)); - data.setLogicEntry(VoltageLossLogic.TYPE.getNew().getWith(loss)) - .setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(loss + 0.001 / amperage)) - .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(amperage)) - .setLogicEntry(VoltageLimitLogic.TYPE.getNew().getWith(voltageLimit)) + data.setLogicEntry(VoltageLossLogic.TYPE.getWith(loss)) + .setLogicEntry(WeightFactorLogic.TYPE.getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.TYPE.getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.TYPE.getWith(voltageLimit)) .setLogicEntry(TemperatureLogic.TYPE.getNew() .getWith(TemperatureLossFunction.getOrCreateCable(coolingFactor), materialMeltTemperature, 1, 100 * cable.material(), cable.partialBurnThreshold())); if (superconductorCriticalTemperature > 0) { - data.setLogicEntry(SuperconductorLogic.TYPE.getNew().getWith(superconductorCriticalTemperature)); + data.setLogicEntry(SuperconductorLogic.TYPE.getWith(superconductorCriticalTemperature)); } } else if (structure instanceof MaterialPipeStructure pipe) { long amperage = getAmperage(structure); if (amperage == 0) return; // skip pipes that are too small long loss = getLoss(structure); float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); - data.setLogicEntry(VoltageLossLogic.TYPE.getNew().getWith(loss)) - .setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(loss + 0.001 / amperage)) - .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(amperage)) - .setLogicEntry(VoltageLimitLogic.TYPE.getNew().getWith(voltageLimit)) + data.setLogicEntry(VoltageLossLogic.TYPE.getWith(loss)) + .setLogicEntry(WeightFactorLogic.TYPE.getWith(loss + 0.001 / amperage)) + .setLogicEntry(ThroughputLogic.TYPE.getWith(amperage)) + .setLogicEntry(VoltageLimitLogic.TYPE.getWith(voltageLimit)) .setLogicEntry(TemperatureLogic.TYPE.getNew() .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, 1, 50 * pipe.material(), null)); if (superconductorCriticalTemperature > 0) { - data.setLogicEntry(SuperconductorLogic.TYPE.getNew().getWith(superconductorCriticalTemperature)); + data.setLogicEntry(SuperconductorLogic.TYPE.getWith(superconductorCriticalTemperature)); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java index ad01defcf7..32616caaf7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialFluidProperties.java @@ -8,6 +8,7 @@ import com.gregtechceu.gtceu.api.fluids.FluidState; import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.logic.ChannelCountLogic; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; @@ -148,10 +149,9 @@ public MaterialPropertyKey getKey() { public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNull List tooltip, @NotNull TooltipFlag flagIn, IPipeMaterialStructure structure) { tooltip.add(Component.translatable("gtceu.universal.tooltip.fluid_transfer_rate", getThroughput(structure))); - tooltip.add(Component.translatable("gtceu.fluid_pipe.max_temperature", getMaxFluidTemperature())); - tooltip.add(Component.translatable("gtceu.fluid_pipe.min_temperature", getMinFluidTemperature())); - tooltip.add(Component.translatable("gtceu.fluid_pipe.priority", + tooltip.add(Component.translatable("gtceu.pipe.priority", FormattingUtil.formatNumbers(getFlowPriority(structure)))); + appendTooltips(tooltip); } @Override @@ -178,13 +178,15 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { if (structure instanceof MaterialPipeStructure pipe) { long throughput = getThroughput(structure); float coolingFactor = (float) Math.sqrt((double) pipe.material() / (4 + pipe.channelCount())); - data.setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(getFlowPriority(structure))) - .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(throughput)) - .setLogicEntry(FluidContainmentLogic.TYPE.getNew().getWith(containableStates, containedAttributes, + data.setLogicEntry(WeightFactorLogic.TYPE.getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.TYPE.getWith(throughput)) + .setLogicEntry(FluidContainmentLogic.TYPE.getWith(containableStates, containedAttributes, maxFluidTemperature)) - .setLogicEntry(TemperatureLogic.TYPE.getNew() - .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, - minFluidTemperature, 50 * pipe.material(), null)); + .setLogicEntry(TemperatureLogic.TYPE.getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), + materialMeltTemperature, minFluidTemperature, 50 * pipe.material(), null)); + if (pipe.channelCount() > 1) { + data.setLogicEntry(ChannelCountLogic.TYPE.getWith(pipe.channelCount())); + } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java index 0074acfbe3..bc2f89b51a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialItemProperties.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.properties.PipeNetProperties; import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.logic.ChannelCountLogic; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.ThroughputLogic; import com.gregtechceu.gtceu.api.graphnet.logic.WeightFactorLogic; @@ -57,7 +58,7 @@ public void addInformation(@NotNull ItemStack stack, BlockGetter worldIn, @NotNu tooltip.add(Component.translatable("gtceu.universal.tooltip.item_transfer_rate_stacks", baseItemsPer5Ticks / 16)); } - tooltip.add(Component.translatable("gtceu.item_pipe.priority", + tooltip.add(Component.translatable("gtceu.pipe.priority", FormattingUtil.formatNumbers(getFlowPriority(structure)))); } @@ -83,8 +84,11 @@ public WorldPipeNetNode getOrCreateFromNet(ServerLevel world, BlockPos pos, IPip public void mutateData(NetLogicData data, IPipeStructure structure) { if (structure instanceof MaterialPipeStructure pipe) { long throughput = baseItemsPer5Ticks * pipe.material(); - data.setLogicEntry(WeightFactorLogic.TYPE.getNew().getWith(getFlowPriority(structure))) - .setLogicEntry(ThroughputLogic.TYPE.getNew().getWith(throughput)); + data.setLogicEntry(WeightFactorLogic.TYPE.getWith(getFlowPriority(structure))) + .setLogicEntry(ThroughputLogic.TYPE.getWith(throughput)); + if (pipe.channelCount() > 1) { + data.setLogicEntry(ChannelCountLogic.TYPE.getWith(pipe.channelCount())); + } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java index 4b9367311d..e006647557 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java @@ -1,8 +1,11 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.logic.AbstractTransientLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; +import com.lowdragmc.lowdraglib.Platform; import net.minecraft.nbt.ByteTag; import net.minecraft.network.FriendlyByteBuf; @@ -15,25 +18,31 @@ import java.util.Collections; import java.util.List; -public class EnergyFlowLogic extends NetLogicEntry { +public class EnergyFlowLogic extends AbstractTransientLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("EnergyFlow", - EnergyFlowLogic::new); + public static final NetLogicType TYPE = new NetLogicType<>(GTCEu.MOD_ID, "EnergyFlow", + EnergyFlowLogic::new, new EnergyFlowLogic()); private final AveragingPerTickCounter averageVoltageCounter = new AveragingPerTickCounter(); private final AveragingPerTickCounter averageAmperageCounter = new AveragingPerTickCounter(); - private static final int MEMORY_TICKS = 10; + public static final int MEMORY_TICKS = 10; - @Getter @NotNull private final Long2ObjectOpenHashMap> memory = new Long2ObjectOpenHashMap<>(); - protected EnergyFlowLogic() { - super(TYPE); + @Override + public @NotNull NetLogicType getType() { + return TYPE; + } + + public @NotNull Long2ObjectOpenHashMap> getMemory() { + updateMemory(Platform.getMinecraftServer().getTickCount()); + return memory; } public @NotNull List getFlow(long tick) { + updateMemory(tick); return memory.getOrDefault(tick, Collections.emptyList()); } @@ -42,11 +51,7 @@ public void recordFlow(long tick, EnergyFlowData flow) { averageAmperageCounter.increment(tick, flow.amperage()); updateMemory(tick); - memory.compute(tick, (k, v) -> { - if (v == null) v = new ObjectArrayList<>(); - v.add(flow); - return v; - }); + memory.computeIfAbsent(tick, k -> new ObjectArrayList<>()).add(flow); } private void updateMemory(long tick) { @@ -66,23 +71,4 @@ public double getAverageAmperage(long currentTick) { public double getAverageVoltage(long currentTick) { return averageVoltageCounter.getAverage(currentTick); } - - @Override - public ByteTag serializeNBT() { - return ByteTag.valueOf((byte) 0); - } - - @Override - public void deserializeNBT(ByteTag nbt) {} - - @Override - public boolean shouldEncode() { - return false; - } - - @Override - public void encode(FriendlyByteBuf buf, boolean fullChange) {} - - @Override - public void decode(FriendlyByteBuf buf, boolean fullChange) {} } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java index af77671332..1ddc93821c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java @@ -1,15 +1,18 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractIntLogicData; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; +import org.jetbrains.annotations.NotNull; public final class SuperconductorLogic extends AbstractIntLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("Superconductor", - () -> new SuperconductorLogic().setValue(0)); + public static final IntLogicType TYPE = new IntLogicType<>(GTCEu.MOD_ID, "Superconductor", + SuperconductorLogic::new, new SuperconductorLogic()); - public SuperconductorLogic() { - super(TYPE); + @Override + public @NotNull IntLogicType getType() { + return TYPE; } public boolean canSuperconduct(int temp) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java index 7759ed7892..2cef05b9de 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java @@ -1,16 +1,19 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; +import org.jetbrains.annotations.NotNull; public final class VoltageLimitLogic extends AbstractLongLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("VoltageLimit", - () -> new VoltageLimitLogic().setValue(0)); + public static final LongLogicType TYPE = new LongLogicType<>(GTCEu.MOD_ID, "VoltageLimit", + VoltageLimitLogic::new, new VoltageLimitLogic()); - private VoltageLimitLogic() { - super(TYPE); + @Override + public @NotNull LongLogicType getType() { + return TYPE; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java index 2aa47791b4..29971c201d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java @@ -1,16 +1,19 @@ package com.gregtechceu.gtceu.common.pipelike.net.energy; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; +import org.jetbrains.annotations.NotNull; public final class VoltageLossLogic extends AbstractLongLogicData { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("VoltageLoss", - () -> new VoltageLossLogic().setValue(0)); + public static final LongLogicType TYPE = new LongLogicType<>(GTCEu.MOD_ID, "VoltageLoss", + VoltageLossLogic::new, new VoltageLossLogic()); - private VoltageLossLogic() { - super(TYPE); + @Override + public @NotNull LongLogicType getType() { + return TYPE; } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java index 14c27e162c..73132aca6e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java @@ -87,6 +87,8 @@ public Capability[] getCapabilities() { @Override public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { if (capability == ForgeCapabilities.FLUID_HANDLER) { + if (facing == null) return LazyOptional.empty(); // hard override to prevent TOP from displaying a tank. + //noinspection ConstantValue return ForgeCapabilities.FLUID_HANDLER.orEmpty(capability, facing == null ? LazyOptional.of(() -> FluidTransferHelperImpl.toFluidHandler(this)) : LazyOptional.of(() -> FluidTransferHelperImpl.toFluidHandler(wrappers.get(facing)))); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java index 23fe6a7cc5..112faeba9d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidContainmentLogic.java @@ -1,9 +1,10 @@ package com.gregtechceu.gtceu.common.pipelike.net.fluid; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.fluids.FluidState; import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntryType; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; import com.gregtechceu.gtceu.utils.GTUtil; import net.minecraft.nbt.CompoundTag; @@ -24,28 +25,16 @@ public final class FluidContainmentLogic extends NetLogicEntry { - public static final NetLogicEntryType TYPE = new NetLogicEntryType<>("FluidContainment", - () -> new FluidContainmentLogic().contain(FluidState.LIQUID)); + public static final FluidContainmentLogicType TYPE = new FluidContainmentLogicType(); private int maximumTemperature; private final Set containableAttributes = new ObjectOpenHashSet<>(); private @NotNull EnumSet containableStates = EnumSet.noneOf(FluidState.class); - public FluidContainmentLogic() { - super(TYPE); - } - - public @NotNull FluidContainmentLogic getWith(Collection states, - @NotNull Collection attributes, - int maximumTemperature) { - FluidContainmentLogic logic = new FluidContainmentLogic(); - logic.containableStates.addAll(states); - for (FluidAttribute attribute : attributes) { - logic.contain(attribute); - } - logic.maximumTemperature = maximumTemperature; - return logic; + @Override + public @NotNull FluidContainmentLogicType getType() { + return TYPE; } @Contract("_ -> this") @@ -144,4 +133,24 @@ public void decode(FriendlyByteBuf buf, boolean fullChange) { } containableStates = GTUtil.maskToSet(FluidState.class, BitSet.valueOf(buf.readByteArray(255))); } + + public static final class FluidContainmentLogicType extends NetLogicType { + + public FluidContainmentLogicType() { + super(GTCEu.MOD_ID, "FluidContainment", FluidContainmentLogic::new, + new FluidContainmentLogic().contain(FluidState.LIQUID)); + } + + public @NotNull FluidContainmentLogic getWith(Collection states, + @NotNull Collection attributes, + int maximumTemperature) { + FluidContainmentLogic logic = getNew(); + logic.containableStates.addAll(states); + for (FluidAttribute attribute : attributes) { + logic.contain(attribute); + } + logic.maximumTemperature = maximumTemperature; + return logic; + } + } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java new file mode 100644 index 0000000000..eaa464869a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java @@ -0,0 +1,60 @@ +package com.gregtechceu.gtceu.common.pipelike.net.fluid; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.logic.AbstractTransientLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; +import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.List; + +public class FluidFlowLogic extends AbstractTransientLogicData { + + public static final NetLogicType TYPE = new NetLogicType<>(GTCEu.MOD_ID, "FluidFlow", + FluidFlowLogic::new, new FluidFlowLogic()); + + public static final int MEMORY_TICKS = 10; + + private final Long2ObjectOpenHashMap> memory = new Long2ObjectOpenHashMap<>(); + private FluidStack last; + + @Override + public @NotNull NetLogicType getType() { + return TYPE; + } + + public @NotNull Long2ObjectOpenHashMap> getMemory() { + updateMemory(Platform.getMinecraftServer().getTickCount()); + return memory; + } + + public @NotNull List getFlow(long tick) { + updateMemory(tick); + return memory.getOrDefault(tick, Collections.emptyList()); + } + + public void recordFlow(long tick, FluidStack flow) { + updateMemory(tick); + memory.computeIfAbsent(tick, k -> new ObjectArrayList<>()).add(flow); + last = flow; + } + + public FluidStack getLast() { + return last; + } + + private void updateMemory(long tick) { + var iter = memory.long2ObjectEntrySet().fastIterator(); + while (iter.hasNext()) { + Long2ObjectMap.Entry> entry = iter.next(); + if (entry.getLongKey() + MEMORY_TICKS < tick) { + iter.remove(); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java index 281adc7a8a..a7527ecfeb 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.pipelike.net.fluid; +import com.google.common.primitives.Ints; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.fluids.FluidState; import com.gregtechceu.gtceu.api.fluids.GTFluid; @@ -167,14 +168,26 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl public void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNode, long consumption) { super.consumeFlowLimit(edge, targetNode, consumption); - TemperatureLogic temperatureLogic = targetNode.getData().getLogicEntryNullable(TemperatureLogic.TYPE); - if (temperatureLogic != null) { - FluidContainmentLogic containmentLogic = targetNode.getData() - .getLogicEntryDefaultable(FluidContainmentLogic.TYPE); - boolean overMax = fluidTemp > containmentLogic.getMaximumTemperature() && - !(state == FluidState.PLASMA && containmentLogic.contains(FluidState.PLASMA)); - temperatureLogic.moveTowardsTemperature(fluidTemp, - getQueryTick(), consumption * TEMPERATURE_EFFECT, !overMax); + if (consumption > 0 && !simulating()) { + recordFlow(targetNode, consumption); + TemperatureLogic temperatureLogic = targetNode.getData().getLogicEntryNullable(TemperatureLogic.TYPE); + if (temperatureLogic != null) { + FluidContainmentLogic containmentLogic = targetNode.getData() + .getLogicEntryDefaultable(FluidContainmentLogic.TYPE); + boolean overMax = fluidTemp > containmentLogic.getMaximumTemperature() && + !(state == FluidState.PLASMA && containmentLogic.contains(FluidState.PLASMA)); + temperatureLogic.moveTowardsTemperature(fluidTemp, + getQueryTick(), consumption * TEMPERATURE_EFFECT, !overMax); + } + } + } + + private void recordFlow(@NotNull NetNode node, long flow) { + FluidFlowLogic logic = node.getData().getLogicEntryNullable(FluidFlowLogic.TYPE); + if (logic == null) { + logic = FluidFlowLogic.TYPE.getNew(); + node.getData().setLogicEntry(logic); } + logic.recordFlow(getQueryTick(), getTestObject().recombine(Ints.saturatedCast(flow))); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java index babb727da8..a5520de7b5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/WorldFluidNet.java @@ -44,7 +44,7 @@ public static WorldFluidNet getWorldNet(ServerLevel serverLevel) { } public WorldFluidNet() { - super(false, DynamicWeightsShortestPathsAlgorithm::new); + super(true, DynamicWeightsShortestPathsAlgorithm::new); } @Override @@ -55,27 +55,27 @@ public boolean supportsPredication() { @Override protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) { super.coverPredication(edge, a, b); - if (edge.getPredicateHandler().hasPredicate(BlockedPredicate.INSTANCE)) return; + if (edge.getPredicateHandler().hasPredicate(BlockedPredicate.TYPE)) return; FilterPredicate predicate = null; if (a instanceof PumpCover filter) { if (filter.getManualIOMode() == ManualIOMode.DISABLED) { edge.getPredicateHandler().clearPredicates(); - edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + edge.getPredicateHandler().setPredicate(BlockedPredicate.TYPE.getNew()); return; } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && filter.getIo() != IO.IN) { - predicate = FilterPredicate.INSTANCE.getNew(); + predicate = FilterPredicate.TYPE.getNew(); predicate.setSourceFilter(filter.getFilterHandler().getFilter()); } } if (b instanceof PumpCover filter) { if (filter.getManualIOMode() == ManualIOMode.DISABLED) { edge.getPredicateHandler().clearPredicates(); - edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + edge.getPredicateHandler().setPredicate(BlockedPredicate.TYPE.getNew()); return; } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && filter.getIo() != IO.OUT) { - if (predicate == null) predicate = FilterPredicate.INSTANCE.getNew(); + if (predicate == null) predicate = FilterPredicate.TYPE.getNew(); predicate.setTargetFilter(filter.getFilterHandler().getFilter()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java new file mode 100644 index 0000000000..504d542e38 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java @@ -0,0 +1,60 @@ +package com.gregtechceu.gtceu.common.pipelike.net.item; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.logic.AbstractTransientLogicData; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; +import com.lowdragmc.lowdraglib.Platform; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.List; + +public class ItemFlowLogic extends AbstractTransientLogicData { + + public static final NetLogicType TYPE = new NetLogicType<>(GTCEu.MOD_ID, "ItemFlow", + ItemFlowLogic::new, new ItemFlowLogic()); + + public static final int MEMORY_TICKS = 10; + + private final Long2ObjectOpenHashMap> memory = new Long2ObjectOpenHashMap<>(); + private ItemStack last; + + @Override + public @NotNull NetLogicType getType() { + return TYPE; + } + + public @NotNull Long2ObjectOpenHashMap> getMemory() { + updateMemory(Platform.getMinecraftServer().getTickCount()); + return memory; + } + + public @NotNull List getFlow(long tick) { + updateMemory(tick); + return memory.getOrDefault(tick, Collections.emptyList()); + } + + public void recordFlow(long tick, ItemStack flow) { + updateMemory(tick); + memory.computeIfAbsent(tick, k -> new ObjectArrayList<>()).add(flow); + last = flow; + } + + public ItemStack getLast() { + return last; + } + + private void updateMemory(long tick) { + var iter = memory.long2ObjectEntrySet().fastIterator(); + while (iter.hasNext()) { + Long2ObjectMap.Entry> entry = iter.next(); + if (entry.getLongKey() + MEMORY_TICKS < tick) { + iter.remove(); + } + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java index 0a8b3251e8..88db6b2df9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java @@ -1,6 +1,9 @@ package com.gregtechceu.gtceu.common.pipelike.net.item; +import com.google.common.primitives.Ints; import com.gregtechceu.gtceu.api.graphnet.IGraphNet; +import com.gregtechceu.gtceu.api.graphnet.NetNode; +import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; import com.gregtechceu.gtceu.api.graphnet.edge.SimulatorKey; import com.gregtechceu.gtceu.api.graphnet.pipenet.FlowWorldPipeNetPath; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; @@ -65,4 +68,22 @@ public long finalizeAtDestination(@NotNull WorldPipeNetNode destination, long fl } return flowReachingDestination - availableFlow; } + + @Override + public void consumeFlowLimit(@NotNull AbstractNetFlowEdge edge, NetNode targetNode, long consumption) { + super.consumeFlowLimit(edge, targetNode, consumption); + if (consumption > 0 && !simulating()) { + recordFlow(targetNode, consumption); + } + } + + private void recordFlow(@NotNull NetNode node, long flow) { + ItemFlowLogic logic = node.getData().getLogicEntryNullable(ItemFlowLogic.TYPE); + if (logic == null) { + logic = ItemFlowLogic.TYPE.getNew(); + node.getData().setLogicEntry(logic); + } + logic.recordFlow(getQueryTick(), getTestObject().recombine(Ints.saturatedCast(flow))); + } + } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java index f77aa329f2..af08329023 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/WorldItemNet.java @@ -45,7 +45,7 @@ public static WorldItemNet getWorldNet(ServerLevel serverLevel) { } public WorldItemNet() { - super(false, DynamicWeightsShortestPathsAlgorithm::new); + super(true, DynamicWeightsShortestPathsAlgorithm::new); } @Override @@ -56,27 +56,27 @@ public boolean supportsPredication() { @Override protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) { super.coverPredication(edge, a, b); - if (edge.getPredicateHandler().hasPredicate(BlockedPredicate.INSTANCE)) return; + if (edge.getPredicateHandler().hasPredicate(BlockedPredicate.TYPE)) return; FilterPredicate predicate = null; if (a instanceof ConveyorCover filter) { if (filter.getManualIOMode() == ManualIOMode.DISABLED) { edge.getPredicateHandler().clearPredicates(); - edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + edge.getPredicateHandler().setPredicate(BlockedPredicate.TYPE.getNew()); return; } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && filter.getIo() != IO.IN) { - predicate = FilterPredicate.INSTANCE.getNew(); + predicate = FilterPredicate.TYPE.getNew(); predicate.setSourceFilter(filter.getFilterHandler().getFilter()); } } if (b instanceof ConveyorCover filter) { if (filter.getManualIOMode() == ManualIOMode.DISABLED) { edge.getPredicateHandler().clearPredicates(); - edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + edge.getPredicateHandler().setPredicate(BlockedPredicate.TYPE.getNew()); return; } else if (filter.getManualIOMode() == ManualIOMode.FILTERED && filter.getIo() != IO.OUT) { - if (predicate == null) predicate = FilterPredicate.INSTANCE.getNew(); + if (predicate == null) predicate = FilterPredicate.TYPE.getNew(); predicate.setTargetFilter(filter.getFilterHandler().getFilter()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java b/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java index ae24f06977..d710bcfecf 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java @@ -15,7 +15,9 @@ public static void init(RegistrateLangProvider provider) { initWailaLikeLang(provider); } - /** JEI, REI, EMI */ + /** + * JEI, REI, EMI + */ private static void initRecipeViewerLang(RegistrateLangProvider provider) { provider.add("gtceu.jei.multiblock_info", "Multiblock Info"); provider.add("gtceu.jei.ore_processing_diagram", "Ore Processing Diagram"); @@ -40,7 +42,9 @@ private static void initRecipeViewerLang(RegistrateLangProvider provider) { } } - /** Jade, TheOneProbe, WTHIT */ + /** + * Jade, TheOneProbe, WTHIT + */ private static void initWailaLikeLang(RegistrateLangProvider provider) { provider.add("gtceu.top.working_disabled", "Working Disabled"); provider.add("gtceu.top.energy_consumption", "Using"); @@ -96,5 +100,11 @@ private static void initWailaLikeLang(RegistrateLangProvider provider) { provider.add("gtceu.top.progress_computation", " / %s CWU"); provider.add("gtceu.top.progress_sec", " / %s s"); provider.add("gtceu.top.progress_tick", " / %s t"); + + + provider.add("gregtech.top.pipe.voltage", "Average Voltage / s:"); + provider.add("gregtech.top.pipe.amperage", "Average Amperage / s:"); + provider.add("gregtech.top.pipe.fluid_last", "Last Fluid:"); + provider.add("gregtech.top.pipe.item_last", "Last Item:"); } } diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java index 0d8b28ea3a..30f384d456 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java @@ -1052,15 +1052,17 @@ public static void init(RegistrateLangProvider provider) { provider.add("gtceu.cable.amperage", "Max Amperage: §e%d"); provider.add("gtceu.cable.loss_per_block", "Loss/Meter/Ampere: §c%d§7 EU-Volt"); provider.add("gtceu.cable.superconductor", "§d%s Superconductor"); + provider.add("gtceu.cable.superconductor_loss", "§cLoss is §f0§c under critical temperature §f%s§f K"); provider.add("gtceu.fluid_pipe.capacity", "§9Capacity: §f%d mB"); - provider.add("gtceu.fluid_pipe.max_temperature", "§cTemperature Limit: §f%d K"); + provider.add("gtceu.fluid_pipe.max_temperature", "§cMax Temperature: §f%s K"); + provider.add("gtceu.fluid_pipe.min_temperature", "§cMin Temperature: §f%s K"); provider.add("gtceu.fluid_pipe.channels", "§eChannels: §f%d"); provider.add("gtceu.fluid_pipe.gas_proof", "§6Can handle Gases"); provider.add("gtceu.fluid_pipe.acid_proof", "§6Can handle Acids"); provider.add("gtceu.fluid_pipe.cryo_proof", "§6Can handle Cryogenics"); provider.add("gtceu.fluid_pipe.plasma_proof", "§6Can handle all Plasmas"); provider.add("gtceu.fluid_pipe.not_gas_proof", "§4Gases may leak!"); - provider.add("gtceu.item_pipe.priority", "§9Priority: §f%d"); + provider.add("gtceu.pipe.priority", "§9Priority: §f%d"); provider.add("gtceu.duct_pipe.transfer_rate", "§bAir transfer rate: %s"); provider.add("gtceu.multiblock.work_paused", "Work Paused."); provider.add("gtceu.multiblock.running", "Running perfectly."); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java index 8c4f435a71..392fa7176c 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java @@ -3,7 +3,6 @@ import com.gregtechceu.gtceu.api.machine.multiblock.CleanroomType; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.data.recipe.CustomTags; - import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.world.item.ItemStack; @@ -290,5 +289,28 @@ public static void init(Consumer provider) { .outputItems(LASER_PIPE) .cleanroom(CleanroomType.CLEANROOM) .duration(100).EUt(VA[IV]).save(provider); + + FORMING_PRESS_RECIPES.recipeBuilder("laser_reflector") + .inputItems(plate, BorosilicateGlass) + .inputItems(foil, Titanium, 12) + .inputItems(foil, Silicon, 12) + .inputItems(foil, Tantalum, 12) + .inputItems(foil, Zinc, 12) + .inputItems(foil, Beryllium, 12) + .outputItems(LASER_REFLECTOR) + .cleanroom(CleanroomType.CLEANROOM) + .duration(200).EUt(VA[LuV]).save(provider); + + ASSEMBLY_LINE_RECIPES.recipeBuilder("laser_reflector_pipe") + .inputItems(frameGt, Trinium) + .inputItems(LASER_PIPE, 2) + .inputItems(LASER_REFLECTOR) + .inputItems(lens, NetherStar, 2) + .inputItems(foil, Osmiridium, 20) + .inputFluids(Polybenzimidazole.getFluid(L)) + .outputItems(LASER_REFLECTOR_PIPE) + .scannerResearch(b -> b.researchStack(LASER_PIPE.asStack()) + .EUt(VA[IV])) + .duration(200).EUt(VA[LuV]).save(provider); } } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java new file mode 100644 index 0000000000..dd22115d93 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java @@ -0,0 +1,50 @@ +package com.gregtechceu.gtceu.integration.jade.element; + +import com.lowdragmc.lowdraglib.gui.util.DrawerHelper; +import com.lowdragmc.lowdraglib.gui.util.TextFormattingUtil; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.world.phys.Vec2; +import snownee.jade.api.ui.Element; + +public class FluidStackElement extends Element { + + private final FluidStack fluidStack; + private float width, height; + + public FluidStackElement(FluidStack fluidStack, float width, float height) { + this.fluidStack = fluidStack; + this.width = width; + this.height = height; + } + + @Override + public Vec2 getSize() { + return new Vec2(width, height); + } + + @Override + public void render(GuiGraphics guiGraphics, float x, float y, float width, float height) { + RenderSystem.disableBlend(); + if (!fluidStack.isEmpty()) { + x += 2; + y += 2; + DrawerHelper.drawFluidForGui(guiGraphics, fluidStack, fluidStack.getAmount(), + (int) x, (int) y, (int) width, (int) height); + + guiGraphics.pose().pushPose(); + guiGraphics.pose().scale(0.5F, 0.5F, 1); + String s = TextFormattingUtil.formatLongToCompactStringBuckets(fluidStack.getAmount(), 3) + "B"; + Font fontRenderer = Minecraft.getInstance().font; + guiGraphics.drawString(fontRenderer, s, (x + (width / 3f)) * 2 - fontRenderer.width(s) + 21, + (y + (height / 3f) + 6) * 2, 0xFFFFFF, true); + guiGraphics.pose().popPose(); + } + RenderSystem.enableBlend(); + RenderSystem.setShaderColor(1, 1, 1, 1); + + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java new file mode 100644 index 0000000000..8cd976f81d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java @@ -0,0 +1,187 @@ +package com.gregtechceu.gtceu.integration.jade.provider; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowData; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.item.ItemFlowLogic; +import com.gregtechceu.gtceu.integration.jade.element.FluidStackElement; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidHelperImpl; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import mcjty.theoneprobe.api.CompoundText; +import mcjty.theoneprobe.api.ElementAlignment; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; +import snownee.jade.api.BlockAccessor; +import snownee.jade.api.IBlockComponentProvider; +import snownee.jade.api.IServerDataProvider; +import snownee.jade.api.ITooltip; +import snownee.jade.api.config.IPluginConfig; +import snownee.jade.api.ui.IElement; +import snownee.jade.api.ui.IElementHelper; + +public class PipeTileInfoProvider implements IBlockComponentProvider, IServerDataProvider { + + @Override + public ResourceLocation getUid() { + return GTCEu.id("pipe_tile_provider"); + } + + @Override + public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPluginConfig iPluginConfig) { + CompoundTag serverData = blockAccessor.getServerData(); + if (serverData.contains("Energy")) { + CompoundTag energy = serverData.getCompound("Energy"); + iTooltip.add(Component.translatable("gtceu.top.pipe.voltage") + .append(Component.literal(String.valueOf(energy.getLong("voltage"))))); + iTooltip.add(Component.translatable("gtceu.top.pipe.amperage") + .append(Component.literal(String.valueOf(energy.getLong("amperage"))))); + } + if (serverData.contains("Fluid")) { + CompoundTag fluid = serverData.getCompound("Fluid"); + + FluidStack stack = FluidStack.loadFromTag(fluid.getCompound("LastFluid")); + iTooltip.add(IElementHelper.get().text("gtceu.top.pipe.fluid_last").align(IElement.Align.LEFT)); + iTooltip.append(new FluidStackElement(stack, 14, 14)); + iTooltip.append(stack.getDisplayName()); + + ListTag list = fluid.getList("ExtraFluids", Tag.TAG_COMPOUND); + for (int i = 0; i < list.size(); i++) { + CompoundTag tag = list.getCompound(i); + stack = FluidStack.loadFromTag(tag.getCompound("Fluid")); + iTooltip.add(new FluidStackElement(stack, 14, 14)); + iTooltip.append(Component.literal(String.valueOf(tag.getLong("Amount"))) + .append(Component.literal(" mB/s ")) + .append(stack.getDisplayName())); + } + } + if (serverData.contains("Item")) { + CompoundTag item = serverData.getCompound("Item"); + + ItemStack stack = ItemStack.of(item.getCompound("LastItem")); + iTooltip.add(IElementHelper.get().text("gtceu.top.pipe.item_last").align(IElement.Align.LEFT)); + iTooltip.append(IElementHelper.get().item(stack)); + iTooltip.append(stack.getDisplayName()); + + ListTag list = item.getList("ExtraFluids", Tag.TAG_COMPOUND); + for (int i = 0; i < list.size(); i++) { + CompoundTag tag = list.getCompound(i); + stack = ItemStack.of(tag.getCompound("Item")); + iTooltip.add(IElementHelper.get().item(stack)); + iTooltip.append(Component.literal(String.valueOf(tag.getLong("Amount"))) + .append(Component.literal(" /s ")) + .append(stack.getDisplayName())); + } + } + } + + @Override + public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccessor) { + if (blockAccessor.getBlock() instanceof PipeBlock pipe) { + PipeBlockEntity tile = pipe.getBlockEntity(blockAccessor.getLevel(), blockAccessor.getPosition()); + if (tile != null) { + for (NetLogicData data : tile.getNetLogicDatas().values()) { + EnergyFlowLogic energy = data.getLogicEntryNullable(EnergyFlowLogic.TYPE); + if (energy != null) { + addEnergyFlowInformation(compoundTag, energy); + } + FluidFlowLogic fluid = data.getLogicEntryNullable(FluidFlowLogic.TYPE); + if (fluid != null) { + addFluidFlowInformation(compoundTag, fluid); + } + ItemFlowLogic item = data.getLogicEntryNullable(ItemFlowLogic.TYPE); + if (item != null) { + addItemFlowInformation(compoundTag, item); + } + } + } + } + } + + private void addEnergyFlowInformation(CompoundTag tag, EnergyFlowLogic logic) { + long cumulativeVoltage = 0; + long cumulativeAmperage = 0; + for (var memory : logic.getMemory().values()) { + int count = 0; + double voltage = 0; + long amperage = 0; + for (EnergyFlowData flow : memory) { + count++; + long prev = amperage; + amperage += flow.amperage(); + // weighted average + voltage = voltage * prev / amperage + (double) (flow.voltage() * flow.amperage()) / amperage; + } + if (count != 0) { + cumulativeVoltage += voltage / count; + cumulativeAmperage += amperage / count; + } + } + CompoundTag energy = new CompoundTag(); + energy.putLong("voltage", cumulativeVoltage / EnergyFlowLogic.MEMORY_TICKS); + energy.putLong("amperage", cumulativeAmperage / EnergyFlowLogic.MEMORY_TICKS); + tag.put("Energy", energy); + } + + private void addFluidFlowInformation(CompoundTag tag, FluidFlowLogic logic) { + CompoundTag fluid = new CompoundTag(); + + fluid.put("LastFluid", logic.getLast().saveToTag(new CompoundTag())); + + Object2LongOpenHashMap counts = new Object2LongOpenHashMap<>(); + for (var memory : logic.getMemory().values()) { + for (FluidStack stack : memory) { + counts.merge(new FluidTestObject(stack), stack.getAmount(), Long::sum); + } + } + + ListTag extraFluids = new ListTag(); + for (var entry : counts.object2LongEntrySet()) { + CompoundTag inner = new CompoundTag(); + FluidStack stack = entry.getKey().recombine(); + + inner.put("Fluid", stack.saveToTag(new CompoundTag())); + inner.putLong("Amount", entry.getLongValue() * 20 / FluidFlowLogic.MEMORY_TICKS); + extraFluids.add(inner); + } + fluid.put("ExtraFluids", extraFluids); + tag.put("Fluid", fluid); + } + + private void addItemFlowInformation(CompoundTag tag, ItemFlowLogic logic) { + CompoundTag item = new CompoundTag(); + item.put("LastItem", logic.getLast().save(new CompoundTag())); + + Object2IntOpenHashMap counts = new Object2IntOpenHashMap<>(); + for (var memory : logic.getMemory().values()) { + for (ItemStack stack : memory) { + counts.merge(new ItemTestObject(stack), stack.getCount(), Integer::sum); + } + } + + ListTag extraItems = new ListTag(); + for (var entry : counts.object2IntEntrySet()) { + CompoundTag inner = new CompoundTag(); + ItemStack stack = entry.getKey().recombine(); + + inner.put("Item", stack.save(new CompoundTag())); + inner.putInt("Amount", entry.getIntValue() * 20 / FluidFlowLogic.MEMORY_TICKS); + extraItems.add(inner); + } + item.put("ExtraItems", extraItems); + tag.put("Item", item); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/TheOneProbePlugin.java b/src/main/java/com/gregtechceu/gtceu/integration/top/TheOneProbePlugin.java index 29dfec35a6..6b9ea5a51d 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/TheOneProbePlugin.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/TheOneProbePlugin.java @@ -30,5 +30,6 @@ public static void init(ITheOneProbe oneProbe) { oneProbe.registerProvider(new CoverProvider()); oneProbe.registerProvider(new HazardCleanerInfoProvider()); oneProbe.registerProvider(new TransformerInfoProvider()); + oneProbe.registerProvider(new PipeTileInfoProvider()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java new file mode 100644 index 0000000000..f949e03a3f --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java @@ -0,0 +1,130 @@ +package com.gregtechceu.gtceu.integration.top.provider; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.FluidTestObject; +import com.gregtechceu.gtceu.api.graphnet.predicate.test.ItemTestObject; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowData; +import com.gregtechceu.gtceu.common.pipelike.net.energy.EnergyFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidFlowLogic; +import com.gregtechceu.gtceu.common.pipelike.net.item.ItemFlowLogic; +import com.gregtechceu.gtceu.integration.top.element.FluidStackElement; +import com.gregtechceu.gtceu.integration.top.element.FluidStyle; +import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; +import com.lowdragmc.lowdraglib.side.fluid.FluidStack; +import com.lowdragmc.lowdraglib.side.fluid.forge.FluidHelperImpl; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import mcjty.theoneprobe.api.*; +import mcjty.theoneprobe.apiimpl.styles.TextStyle; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; + +public class PipeTileInfoProvider implements IProbeInfoProvider { + + @Override + public ResourceLocation getID() { + return GTCEu.id("pipe_tile_provider"); + } + + @Override + public void addProbeInfo(ProbeMode mode, IProbeInfo info, Player player, Level level, + BlockState state, IProbeHitData hitData) { + if (state.getBlock() instanceof PipeBlock pipe) { + PipeBlockEntity tile = pipe.getBlockEntity(level, hitData.getPos()); + if (tile != null) { + for (NetLogicData data : tile.getNetLogicDatas().values()) { + EnergyFlowLogic energy = data.getLogicEntryNullable(EnergyFlowLogic.TYPE); + if (energy != null) { + addEnergyFlowInformation(mode, info, player, hitData, energy); + } + FluidFlowLogic fluid = data.getLogicEntryNullable(FluidFlowLogic.TYPE); + if (fluid != null) { + addFluidFlowInformation(mode, info, player, hitData, fluid); + } + ItemFlowLogic item = data.getLogicEntryNullable(ItemFlowLogic.TYPE); + if (item != null) { + addItemFlowInformation(mode, info, player, hitData, item); + } + } + } + } + } + + private void addEnergyFlowInformation(ProbeMode probeMode, IProbeInfo iProbeInfo, Player entityPlayer, + IProbeHitData iProbeHitData, EnergyFlowLogic logic) { + long cumulativeVoltage = 0; + long cumulativeAmperage = 0; + for (var memory : logic.getMemory().values()) { + int count = 0; + double voltage = 0; + long amperage = 0; + for (EnergyFlowData flow : memory) { + count++; + long prev = amperage; + amperage += flow.amperage(); + // weighted average + voltage = voltage * prev / amperage + (double) (flow.voltage() * flow.amperage()) / amperage; + } + if (count != 0) { + cumulativeVoltage += voltage / count; + cumulativeAmperage += amperage / count; + } + } + iProbeInfo.text(CompoundText.create().info(Component.translatable("gtceu.top.pipe.voltage")) + .important(Component.literal(String.valueOf(cumulativeVoltage / EnergyFlowLogic.MEMORY_TICKS)))); + iProbeInfo.text(CompoundText.create().info(Component.translatable("gtceu.top.pipe.amperage")) + .important(Component.literal(String.valueOf(cumulativeAmperage / EnergyFlowLogic.MEMORY_TICKS)))); + } + + private void addFluidFlowInformation(ProbeMode probeMode, IProbeInfo iProbeInfo, Player entityPlayer, + IProbeHitData iProbeHitData, FluidFlowLogic logic) { + iProbeInfo.horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)) + .text(CompoundText.create().info(Component.translatable("gtceu.top.pipe.fluid_last"))) + .element(new FluidStackElement(logic.getLast(), new FluidStyle())) + .text(logic.getLast().getDisplayName()); + + Object2LongOpenHashMap counts = new Object2LongOpenHashMap<>(); + for (var memory : logic.getMemory().values()) { + for (FluidStack stack : memory) { + counts.merge(new FluidTestObject(stack), stack.getAmount(), Long::sum); + } + } + + for (var entry : counts.object2LongEntrySet()) { + FluidStack stack = entry.getKey().recombine(); + iProbeInfo.horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)) + .element(new FluidStackElement(logic.getLast(), new FluidStyle().bounds(14, 14))) + .text(entry.getLongValue() * 20 / FluidFlowLogic.MEMORY_TICKS + " mB/S " + stack.getDisplayName().getString()); + } + } + + private void addItemFlowInformation(ProbeMode probeMode, IProbeInfo iProbeInfo, Player entityPlayer, + IProbeHitData iProbeHitData, ItemFlowLogic logic) { + iProbeInfo.horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)) + .text(CompoundText.create().info(Component.translatable("gtceu.top.pipe.item_last"))) + .item(logic.getLast()) + .text(logic.getLast().getDisplayName()); + + Object2IntOpenHashMap counts = new Object2IntOpenHashMap<>(); + for (var memory : logic.getMemory().values()) { + for (ItemStack stack : memory) { + counts.merge(new ItemTestObject(stack), stack.getCount(), Integer::sum); + } + } + + for (var entry : counts.object2IntEntrySet()) { + ItemStack stack = entry.getKey().recombine(); + iProbeInfo.horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)) + .item(stack) + .text(entry.getIntValue() * 20 / ItemFlowLogic.MEMORY_TICKS + " /s " + stack.getDisplayName()); + } + } +} diff --git a/src/main/resources/assets/gtceu/lang/ja_jp.json b/src/main/resources/assets/gtceu/lang/ja_jp.json index 56640ba343..1d371a2b8a 100644 --- a/src/main/resources/assets/gtceu/lang/ja_jp.json +++ b/src/main/resources/assets/gtceu/lang/ja_jp.json @@ -2786,7 +2786,7 @@ "gtceu.item_filter.empty_item": "指定なし", "gtceu.item_filter.footer": "§e 書き換える項目でクリックする。", "gtceu.item_list.item_stored": "§7格納: %d", - "gtceu.item_pipe.priority": "§9優先順位: §f%d", + "gtceu.pipe.priority": "§9優先順位: §f%d", "gtceu.jade.cleaned_this_second": "汚染の洗浄度: %s/s", "gtceu.jade.energy_stored": "%d / %d EU", "gtceu.jade.progress_computation": "%s / %s CWU", diff --git a/src/main/resources/assets/gtceu/lang/ru_ru.json b/src/main/resources/assets/gtceu/lang/ru_ru.json index cdbaa1028a..0332b45165 100644 --- a/src/main/resources/assets/gtceu/lang/ru_ru.json +++ b/src/main/resources/assets/gtceu/lang/ru_ru.json @@ -2252,7 +2252,7 @@ "gtceu.item_filter.empty_item": "Пусто (нет предмета)", "gtceu.item_filter.footer": "§eНажмите с предметом, чтобы переопределить", "gtceu.item_list.item_stored": "§7Хранится: %d", - "gtceu.item_pipe.priority": "§9Приоритет: §f%d", + "gtceu.pipe.priority": "§9Приоритет: §f%d", "gtceu.jei.bedrock_fluid.heavy_oil_deposit": "Залежь тяжелой нефти", "gtceu.jei.bedrock_fluid.lava_deposit": "Залежь лавы", "gtceu.jei.bedrock_fluid.light_oil_deposit": "Залежь легкой нефти", diff --git a/src/main/resources/assets/gtceu/lang/zh_cn.json b/src/main/resources/assets/gtceu/lang/zh_cn.json index a4bc7f0631..af85681272 100644 --- a/src/main/resources/assets/gtceu/lang/zh_cn.json +++ b/src/main/resources/assets/gtceu/lang/zh_cn.json @@ -2832,7 +2832,7 @@ "gtceu.item_filter.empty_item":"空(无物品)", "gtceu.item_filter.footer":"§e手持物品右键覆盖设置", "gtceu.item_list.item_stored":"§7储量:%d", - "gtceu.item_pipe.priority":"§9优先级:§f%d", + "gtceu.pipe.priority":"§9优先级:§f%d", "gtceu.jade.cleaned_this_second":"污染清理速率:%s/s", "gtceu.jade.energy_stored":"%d / %d EU", "gtceu.jade.progress_computation":"%s / %s CWU", diff --git a/src/main/resources/assets/gtceu/lang/zh_tw.json b/src/main/resources/assets/gtceu/lang/zh_tw.json index e8a364e677..89b3743ab1 100644 --- a/src/main/resources/assets/gtceu/lang/zh_tw.json +++ b/src/main/resources/assets/gtceu/lang/zh_tw.json @@ -2832,7 +2832,7 @@ "gtceu.item_filter.empty_item":"空(無物品)", "gtceu.item_filter.footer":"§e手持物品右鍵取代設定", "gtceu.item_list.item_stored":"§7儲量:%d", - "gtceu.item_pipe.priority":"§9優先順序:§f%d", + "gtceu.pipe.priority":"§9優先順序:§f%d", "gtceu.jade.cleaned_this_second":"污染清理速率:%s/s", "gtceu.jade.energy_stored":"%d / %d EU", "gtceu.jade.progress_computation":"計算進度:%s / %s", From 8fdf4aaf8847dd50e86cd824201810637afe5d32 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 12 Sep 2024 19:12:54 +0300 Subject: [PATCH 47/70] fix gradle + spotless + datagen --- build.gradle | 18 ++++++++- gradle/scripts/jars.gradle | 36 +++++++++++------- gradle/scripts/publishing.gradle | 2 +- .../gtceu/compass/nodes/materials/frame.json | 4 +- .../nodes/materials/screwdriver_tip.json | 2 +- .../nodes/materials/wire_cutter_head.json | 2 +- .../nodes/misc/dielectric_laser_mirror.json | 15 ++++++++ .../resources/assets/gtceu/lang/en_ud.json | 19 +++++---- .../resources/assets/gtceu/lang/en_us.json | 19 +++++---- .../models/item/dielectric_laser_mirror.json | 6 +++ .../tags/blocks/mineable/wire_cutter.json | 1 + .../forge/tags/blocks/mineable/wrench.json | 6 +-- .../loot_tables/blocks/large_duct_pipe.json | 21 ---------- ...ct_pipe.json => laser_reflector_pipe.json} | 4 +- .../loot_tables/blocks/normal_duct_pipe.json | 21 ---------- .../loot_tables/blocks/small_duct_pipe.json | 21 ---------- .../gregtechceu/gtceu/api/addon/IGTAddon.java | 1 + .../api/capability/IPropertyFluidFilter.java | 2 - .../logic/AbstractDoubleLogicData.java | 2 +- .../graphnet/logic/AbstractIntLogicData.java | 2 +- .../graphnet/logic/AbstractLongLogicData.java | 2 +- .../logic/AbstractTransientLogicData.java | 1 + .../api/graphnet/logic/ChannelCountLogic.java | 1 + .../api/graphnet/logic/NetLogicData.java | 3 +- .../api/graphnet/logic/NetLogicEntry.java | 1 - .../logic/NetLogicRegistrationEvent.java | 4 +- .../api/graphnet/logic/NetLogicRegistry.java | 9 +++-- .../api/graphnet/logic/NetLogicType.java | 2 + .../api/graphnet/logic/ThroughputLogic.java | 1 + .../api/graphnet/logic/WeightFactorLogic.java | 1 + .../api/graphnet/pipenet/WorldPipeNet.java | 3 +- .../PipeStructureRegistrationEvent.java | 7 ++-- .../physical/PipeStructureRegistry.java | 5 +-- .../physical/tile/PipeBlockEntity.java | 2 +- .../pipenet/predicate/FilterPredicate.java | 5 --- .../api/graphnet/predicate/EdgePredicate.java | 1 - .../predicate/EdgePredicateHandler.java | 1 - .../NetPredicateRegistrationEvent.java | 3 +- .../predicate/NetPredicateRegistry.java | 8 ++-- .../graphnet/predicate/NetPredicateType.java | 1 + .../renderer/pipe/cache/ColorQuadCache.java | 18 ++++----- .../renderer/pipe/quad/PipeQuadHelper.java | 2 +- .../pipelike/block/cable/CableStructure.java | 1 - .../pipelike/block/duct/DuctPipeBlock.java | 6 +-- .../pipelike/block/duct/DuctStructure.java | 1 - .../pipelike/block/laser/LaserPipeBlock.java | 3 -- .../pipelike/block/laser/LaserStructure.java | 1 - .../block/optical/OpticalPipeBlock.java | 2 - .../block/optical/OpticalStructure.java | 1 - .../block/pipe/MaterialPipeStructure.java | 1 - .../properties/MaterialEnergyProperties.java | 13 +++---- .../pipelike/net/energy/EnergyFlowLogic.java | 4 -- .../net/energy/SuperconductorLogic.java | 2 +- .../net/energy/VoltageLimitLogic.java | 2 +- .../pipelike/net/energy/VoltageLossLogic.java | 2 +- .../net/fluid/FluidCapabilityObject.java | 2 +- .../pipelike/net/fluid/FluidFlowLogic.java | 2 + .../pipelike/net/fluid/FluidTraverseData.java | 2 +- .../pipelike/net/item/ItemFlowLogic.java | 5 ++- .../pipelike/net/item/ItemTraverseData.java | 3 +- .../gtceu/data/lang/IntegrationLang.java | 1 - .../data/recipe/misc/ComputerRecipes.java | 1 + .../jade/element/FluidStackElement.java | 5 ++- .../jade/provider/PipeTileInfoProvider.java | 18 ++++----- .../top/provider/PipeTileInfoProvider.java | 16 ++++---- .../textures/item/dielectric_laser_mirror.png | Bin 0 -> 5232 bytes 66 files changed, 179 insertions(+), 200 deletions(-) create mode 100644 src/generated/resources/assets/gtceu/compass/nodes/misc/dielectric_laser_mirror.json create mode 100644 src/generated/resources/assets/gtceu/models/item/dielectric_laser_mirror.json delete mode 100644 src/generated/resources/data/gtceu/loot_tables/blocks/large_duct_pipe.json rename src/generated/resources/data/gtceu/loot_tables/blocks/{huge_duct_pipe.json => laser_reflector_pipe.json} (74%) delete mode 100644 src/generated/resources/data/gtceu/loot_tables/blocks/normal_duct_pipe.json delete mode 100644 src/generated/resources/data/gtceu/loot_tables/blocks/small_duct_pipe.json create mode 100644 src/main/resources/assets/gtceu/textures/item/dielectric_laser_mirror.png diff --git a/build.gradle b/build.gradle index fe33d4561d..8520ec1d85 100644 --- a/build.gradle +++ b/build.gradle @@ -1,3 +1,5 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + plugins { id 'java-library' id 'eclipse' @@ -5,7 +7,7 @@ plugins { id 'maven-publish' alias libs.plugins.modDevGradle alias libs.plugins.machete // automatic jar compressing on build - //alias libs.plugins.shadow + alias libs.plugins.shadow alias libs.plugins.spotless alias libs.plugins.lombok } @@ -18,6 +20,20 @@ java.toolchain.languageVersion = JavaLanguageVersion.of(17) boolean isSnapshot = System.getenv("SNAPSHOT") version = "${mod_version}" + (isSnapshot ? "-SNAPSHOT" : "") +tasks.register('slimJar', ShadowJar) { + from sourceSets.main.output +} + +afterEvaluate { + tasks.withType(ShadowJar).configureEach { + dependsOn shadowJar.configurations + minimize() + relocate("org.jgrapht", "${maven_group}.repack.org.jgrapht") + relocate("org.jheaps", "${maven_group}.repack.org.jheaps") + relocate("org.apfloat", "${maven_group}.repack.org.apfloat") + } +} + apply from: "$rootDir/gradle/scripts/moddevgradle.gradle" apply from: "$rootDir/gradle/scripts/repositories.gradle" apply from: "$rootDir/dependencies.gradle" diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 0602a7e19e..7aab1738ff 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -1,28 +1,36 @@ -tasks.register('slimJar', Jar) { - archiveClassifier = "dev-slim" - from sourceSets.main.output -} - shadowJar { - dependsOn shadowJar.configurations + from jar.outputs configurations = [project.configurations.shadow] - archiveClassifier = "dev-shadow" - minimize() - relocate("org.jgrapht", "${maven_group}.repack.org.jgrapht") - relocate("org.jheaps", "${maven_group}.repack.org.jheaps") - relocate("org.apfloat", "${maven_group}.repack.org.apfloat") + archiveClassifier = "dev" +} + +slimJar { + from sourceSets.main.output + archiveClassifier = "dev-slim" } obfuscation { reobfuscate(tasks.named('slimJar'), sourceSets.main) { archiveClassifier = "slim" } + reobfuscate(tasks.named('shadowJar'), sourceSets.main) { + archiveClassifier = "shadow" + } + reobfuscate(tasks.named('shadowJar'), sourceSets.main) { + archiveClassifier = null + archiveClassifier.convention(null) + } } jar { - exclude ".cache/*" + archiveClassifier = "dev-no-shadow" + archiveClassifier.convention("dev-no-shadow") + enabled = false +} - archiveClassifier = "dev" +reobfJar { + archiveClassifier = "no-shadow" + enabled = false } tasks.register('sourcesJar', Jar) { @@ -37,6 +45,8 @@ base { afterEvaluate { tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { + exclude ".cache/*" + manifest.attributes([ 'MixinConfigs': 'gtceu.mixins.json', 'Specification-Title': project.name, diff --git a/gradle/scripts/publishing.gradle b/gradle/scripts/publishing.gradle index 76e7650e0a..b2807e361e 100644 --- a/gradle/scripts/publishing.gradle +++ b/gradle/scripts/publishing.gradle @@ -1,5 +1,5 @@ artifacts { - archives tasks.reobfJar + archives tasks.reobfShadowJar archives tasks.reobfSlimJar archives tasks.sourcesJar } diff --git a/src/generated/resources/assets/gtceu/compass/nodes/materials/frame.json b/src/generated/resources/assets/gtceu/compass/nodes/materials/frame.json index 39cfd375c8..01d8df4995 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/materials/frame.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/materials/frame.json @@ -4,8 +4,8 @@ "res": "gtceu:aluminium_frame" }, "items": [ - "#minecraft:climbable", - "#forge:frames" + "#forge:frames", + "#minecraft:climbable" ], "page": "gtceu:materials/frame", "position": [ diff --git a/src/generated/resources/assets/gtceu/compass/nodes/materials/screwdriver_tip.json b/src/generated/resources/assets/gtceu/compass/nodes/materials/screwdriver_tip.json index 0e2be18919..482dbce4f6 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/materials/screwdriver_tip.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/materials/screwdriver_tip.json @@ -5,7 +5,7 @@ }, "page": "gtceu:materials/screwdriver_tip", "position": [ - -100, + -150, 100 ], "section": "gtceu:materials" diff --git a/src/generated/resources/assets/gtceu/compass/nodes/materials/wire_cutter_head.json b/src/generated/resources/assets/gtceu/compass/nodes/materials/wire_cutter_head.json index 35cda72eea..c2e1af6c79 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/materials/wire_cutter_head.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/materials/wire_cutter_head.json @@ -5,7 +5,7 @@ }, "page": "gtceu:materials/wire_cutter_head", "position": [ - -300, + -350, 200 ], "section": "gtceu:materials" diff --git a/src/generated/resources/assets/gtceu/compass/nodes/misc/dielectric_laser_mirror.json b/src/generated/resources/assets/gtceu/compass/nodes/misc/dielectric_laser_mirror.json new file mode 100644 index 0000000000..c1a4bb4648 --- /dev/null +++ b/src/generated/resources/assets/gtceu/compass/nodes/misc/dielectric_laser_mirror.json @@ -0,0 +1,15 @@ +{ + "button_texture": { + "type": "item", + "res": "gtceu:dielectric_laser_mirror" + }, + "items": [ + "gtceu:dielectric_laser_mirror" + ], + "page": "gtceu:misc/dielectric_laser_mirror", + "position": [ + -200, + 300 + ], + "section": "gtceu:misc" +} \ No newline at end of file diff --git a/src/generated/resources/assets/gtceu/lang/en_ud.json b/src/generated/resources/assets/gtceu/lang/en_ud.json index f1b5d22534..719d966319 100644 --- a/src/generated/resources/assets/gtceu/lang/en_ud.json +++ b/src/generated/resources/assets/gtceu/lang/en_ud.json @@ -333,7 +333,6 @@ "block.gtceu.hpca_empty_component": "ʇuǝuodɯoƆ ⱯƆԀH ʎʇdɯƎ", "block.gtceu.hpca_heat_sink_component": "ʇuǝuodɯoƆ ʞuıS ʇɐǝH ⱯƆԀH", "block.gtceu.hssg_coil_block": "ʞɔoןᗺ ןıoƆ ⅁-SSH", - "block.gtceu.huge_duct_pipe": "ǝdıԀ ʇɔnᗡ ǝbnH", "block.gtceu.hv_16a_energy_converter": "ɹǝʇɹǝʌuoƆ ʎbɹǝuƎ Ɐ9Ɩ ΛH", "block.gtceu.hv_1a_energy_converter": "ɹǝʇɹǝʌuoƆ ʎbɹǝuƎ ⱯƖ ΛH", "block.gtceu.hv_4a_energy_converter": "ɹǝʇɹǝʌuoƆ ʎbɹǝuƎ Ɐㄣ ΛH", @@ -527,7 +526,6 @@ "block.gtceu.large_combustion_engine": "ǝuıbuƎ uoıʇsnqɯoƆ ǝbɹɐꞀ", "block.gtceu.large_cutter": "ʍɐS buıʇʇnƆ ǝbɹɐꞀ", "block.gtceu.large_distillery": "ʎɹǝןןıʇsıᗡ buıʇɐuoıʇɔɐɹℲ ǝbɹɐꞀ", - "block.gtceu.large_duct_pipe": "ǝdıԀ ʇɔnᗡ ǝbɹɐꞀ", "block.gtceu.large_electrolyzer": "ɹǝqɯɐɥƆ sısʎןoɹʇɔǝןƎ ǝbɹɐꞀ", "block.gtceu.large_electromagnet": "ʇǝubɐɯoɹʇɔǝןƎ ǝbɹɐꞀ", "block.gtceu.large_engraving_laser": "ɹǝsɐꞀ buıʌɐɹbuƎ ǝbɹɐꞀ", @@ -543,6 +541,7 @@ "block.gtceu.large_wiremill": "ʎɹoʇɔɐℲ ǝɹıM ǝbɹɐꞀ", "block.gtceu.laser_hazard_sign_block": "ʞɔoןᗺ ubıS pɹɐzɐH ɹǝsɐꞀ", "block.gtceu.laser_pipe": "ǝdıԀ ɹǝsɐꞀ", + "block.gtceu.laser_reflector_pipe": "ǝdıԀ ɹoʇɔǝןɟǝᴚ ɹǝsɐꞀ", "block.gtceu.laser_safe_engraving_casing": "buısɐƆ buıʌɐɹbuƎ ǝɟɐS-ɹǝsɐꞀ", "block.gtceu.light_blue_borderless_lamp": "dɯɐꞀ ssǝןɹǝpɹoᗺ ǝnןᗺ ʇɥbıꞀ", "block.gtceu.light_blue_lamp": "dɯɐꞀ ǝnןᗺ ʇɥbıꞀ", @@ -914,7 +913,6 @@ "block.gtceu.nichrome_coil_block": "ʞɔoןᗺ ןıoƆ ǝɯoɹɥɔıN", "block.gtceu.noise_hazard_sign_block": "ʞɔoןᗺ ubıS pɹɐzɐH ǝsıoN", "block.gtceu.nonconducting_casing": "buısɐƆ buıʇɔnpuoɔuoN", - "block.gtceu.normal_duct_pipe": "ǝdıԀ ʇɔnᗡ ןɐɯɹoN", "block.gtceu.normal_laser_pipe.tooltip": "sǝuıן ʇɥbıɐɹʇs uı ㄥ§ssoן ouɟ§ ɥʇıʍ ɹǝʍod buıʇʇıɯsuɐɹ⟘ㄥ§", "block.gtceu.normal_optical_pipe.tooltip": "ㄥ§ɐʇɐᗡ ɥɔɹɐǝsǝᴚɟ§ ɹo ㄥ§uoıʇɐʇndɯoƆɟ§ buıʇʇıɯsuɐɹ⟘ㄥ§", "block.gtceu.object_holder": "ɹǝpןoH ʇɔǝظqO", @@ -1083,7 +1081,6 @@ "block.gtceu.shock_proof_cutting_casing": "buısɐƆ buıʇʇnƆ ɟooɹԀ ʞɔoɥS", "block.gtceu.slicing_blades": "sǝpɐןᗺ buıɔıןS", "block.gtceu.small_dark_concrete_bricks": "sʞɔıɹᗺ ǝʇǝɹɔuoƆ ʞɹɐᗡ ןןɐɯS", - "block.gtceu.small_duct_pipe": "ǝdıԀ ʇɔnᗡ ןןɐɯS", "block.gtceu.small_light_concrete_bricks": "sʞɔıɹᗺ ǝʇǝɹɔuoƆ ʇɥbıꞀ ןןɐɯS", "block.gtceu.small_marble_bricks": "sʞɔıɹᗺ ǝןqɹɐW ןןɐɯS", "block.gtceu.small_red_granite_bricks": "sʞɔıɹᗺ ǝʇıuɐɹ⅁ pǝᴚ ןןɐɯS", @@ -2009,7 +2006,6 @@ "compass.node.gtceu.materials/spring": "buıɹdS", "compass.node.gtceu.materials/tiny_dust": "ʇsnᗡ ʎuı⟘", "compass.node.gtceu.materials/tool_heads": "spɐǝH ןoo⟘", - "compass.node.gtceu.materials/wire_and_cable": "ǝןqɐƆ puⱯ ǝɹıM", "compass.node.gtceu.materials/wire_cutter_head": "pɐǝH ɹǝʇʇnƆ ǝɹıM", "compass.node.gtceu.misc/advanced_power_thruster": "ɹǝʇsnɹɥ⟘ ɹǝʍoԀ pǝɔuɐʌpⱯ", "compass.node.gtceu.misc/ancient_gold_coin": "uıoƆ pןo⅁ ʇuǝıɔuⱯ", @@ -2032,6 +2028,7 @@ "compass.node.gtceu.misc/crystal_cpu": "ndƆ ןɐʇsʎɹƆ", "compass.node.gtceu.misc/crystal_soc": "ɔoS ןɐʇsʎɹƆ", "compass.node.gtceu.misc/diamond_grinding_head": "pɐǝH buıpuıɹ⅁ puoɯɐıᗡ", + "compass.node.gtceu.misc/dielectric_laser_mirror": "ɹoɹɹıW ɹǝsɐꞀ ɔıɹʇɔǝןǝıᗡ", "compass.node.gtceu.misc/doge_coin": "uıoƆ ǝboᗡ", "compass.node.gtceu.misc/duct_tape": "ǝdɐ⟘ ʇɔnᗡ", "compass.node.gtceu.misc/electric_motor": "ɹoʇoW ɔıɹʇɔǝןƎ", @@ -2605,6 +2602,10 @@ "fluid.tile.lava": "ɐʌɐꞀ", "fluid.tile.water": "ɹǝʇɐM", "fluid_cell.empty": "ʎʇdɯƎ", + "gregtech.top.pipe.amperage": ":s / ǝbɐɹǝdɯⱯ ǝbɐɹǝʌⱯ", + "gregtech.top.pipe.fluid_last": ":pınןℲ ʇsɐꞀ", + "gregtech.top.pipe.item_last": ":ɯǝʇI ʇsɐꞀ", + "gregtech.top.pipe.voltage": ":s / ǝbɐʇןoΛ ǝbɐɹǝʌⱯ", "gtceu.air_scrubber": "ɹǝqqnɹɔS ɹıⱯ", "gtceu.alloy_blast_smelter": "ɹǝʇןǝɯS ʇsɐןᗺ ʎoןןⱯ", "gtceu.alloy_smelter": "ɹǝʇןǝɯS ʎoןןⱯ", @@ -2622,6 +2623,7 @@ "gtceu.cable.amperage": "%dǝ§ :ǝbɐɹǝdɯⱯ xɐW", "gtceu.cable.loss_per_block": "ʇןoΛ-∩Ǝ ㄥ§%dɔ§ :ǝɹǝdɯⱯ/ɹǝʇǝW/ssoꞀ", "gtceu.cable.superconductor": "ɹoʇɔnpuoɔɹǝdnS %sp§", + "gtceu.cable.superconductor_loss": "ʞ ɟ§%sɟ§ ǝɹnʇɐɹǝdɯǝʇ ןɐɔıʇıɹɔ ɹǝpun ɔ§0ɟ§ sı ssoꞀɔ§", "gtceu.cable.voltage": ")ɐ§%s(ɐ§ %dɐ§ :ǝbɐʇןoΛ xɐW", "gtceu.canner": "ɹǝuuɐƆ", "gtceu.centrifuge": "ǝbnɟıɹʇuǝƆ", @@ -2727,7 +2729,8 @@ "gtceu.fluid_pipe.channels": "%dɟ§ :sןǝuuɐɥƆǝ§", "gtceu.fluid_pipe.cryo_proof": "sɔıuǝboʎɹƆ ǝןpuɐɥ uɐƆ9§", "gtceu.fluid_pipe.gas_proof": "sǝsɐ⅁ ǝןpuɐɥ uɐƆ9§", - "gtceu.fluid_pipe.max_temperature": "ʞ %dɟ§ :ʇıɯıꞀ ǝɹnʇɐɹǝdɯǝ⟘ɔ§", + "gtceu.fluid_pipe.max_temperature": "ʞ %sɟ§ :ǝɹnʇɐɹǝdɯǝ⟘ xɐWɔ§", + "gtceu.fluid_pipe.min_temperature": "ʞ %sɟ§ :ǝɹnʇɐɹǝdɯǝ⟘ uıWɔ§", "gtceu.fluid_pipe.not_gas_proof": "¡ʞɐǝן ʎɐɯ sǝsɐ⅁ㄣ§", "gtceu.fluid_pipe.plasma_proof": "sɐɯsɐןԀ ןןɐ ǝןpuɐɥ uɐƆ9§", "gtceu.fluid_solidifier": "ɹǝıɟıpıןoS pınןℲ", @@ -2841,7 +2844,6 @@ "gtceu.item_filter.empty_item": ")ɯǝʇI oN( ʎʇdɯƎ", "gtceu.item_filter.footer": "ǝpıɹɹǝʌo oʇ ɯǝʇı ɥʇıʍ ʞɔıןƆǝ§", "gtceu.item_list.item_stored": "%d :pǝɹoʇSㄥ§", - "gtceu.pipe.priority": "%dɟ§ :ʎʇıɹoıɹԀ6§", "gtceu.jade.cleaned_this_second": "s/%s :pɹɐzɐɥ pǝuɐǝןƆ", "gtceu.jade.energy_stored": "∩Ǝ %d / %d", "gtceu.jade.progress_computation": "∩MƆ %s / %s", @@ -3824,6 +3826,7 @@ "gtceu.oc.tooltip.4": "ƆO ʇɔǝɟɹǝԀ ʎq ǝbuɐɥɔ oʇ ʇɟıɥS pןoH", "gtceu.ore_washer": "ɹǝɥsɐM ǝɹO", "gtceu.packer": "ɹǝʞɔɐԀ", + "gtceu.pipe.priority": "%dɟ§ :ʎʇıɹoıɹԀ6§", "gtceu.plasma_generator": "ɹoʇɐɹǝuǝ⅁ ɐɯsɐןԀ", "gtceu.polarizer": "ɹǝzıɹɐןoԀ", "gtceu.primitive_blast_furnace": "ǝɔɐuɹnℲ ʇsɐןᗺ ǝʌıʇıɯıɹԀ", @@ -4223,6 +4226,7 @@ "item.gtceu.data_stick": "ʞɔıʇS ɐʇɐᗡ", "item.gtceu.data_stick.tooltip": "ǝbɐɹoʇS ɐʇɐᗡ ʎʇıɔɐdɐƆ ʍoꞀ Ɐㄥ§", "item.gtceu.diamond_grinding_head": "pɐǝH buıpuıɹ⅁ puoɯɐıᗡ", + "item.gtceu.dielectric_laser_mirror": "ɹoɹɹıW ɹǝsɐꞀ ɔıɹʇɔǝןǝıᗡ", "item.gtceu.diode": "ǝpoıᗡ", "item.gtceu.diode.tooltip": "ʇuǝuodɯoƆ ɔıuoɹʇɔǝןƎ ɔısɐᗺㄥ§", "item.gtceu.doge_coin": "uıoƆ ǝboᗡ", @@ -5257,7 +5261,6 @@ "material.gtceu.einsteinium": "ɯnıuıǝʇsuıƎ", "material.gtceu.electrotine": "ǝuıʇoɹʇɔǝןƎ", "material.gtceu.electrum": "ɯnɹʇɔǝןƎ", - "material.gtceu.elementium": "ɯnıʇuǝɯǝןƎ", "material.gtceu.emerald": "pןɐɹǝɯƎ", "material.gtceu.ender_air": "ɹıⱯ ɹǝpuƎ", "material.gtceu.ender_eye": "ǝʎƎ ɹǝpuƎ", diff --git a/src/generated/resources/assets/gtceu/lang/en_us.json b/src/generated/resources/assets/gtceu/lang/en_us.json index aac137a6c6..1c24066c16 100644 --- a/src/generated/resources/assets/gtceu/lang/en_us.json +++ b/src/generated/resources/assets/gtceu/lang/en_us.json @@ -333,7 +333,6 @@ "block.gtceu.hpca_empty_component": "Empty HPCA Component", "block.gtceu.hpca_heat_sink_component": "HPCA Heat Sink Component", "block.gtceu.hssg_coil_block": "HSS-G Coil Block", - "block.gtceu.huge_duct_pipe": "Huge Duct Pipe", "block.gtceu.hv_16a_energy_converter": "HV 16A Energy Converter", "block.gtceu.hv_1a_energy_converter": "HV 1A Energy Converter", "block.gtceu.hv_4a_energy_converter": "HV 4A Energy Converter", @@ -527,7 +526,6 @@ "block.gtceu.large_combustion_engine": "Large Combustion Engine", "block.gtceu.large_cutter": "Large Cutting Saw", "block.gtceu.large_distillery": "Large Fractionating Distillery", - "block.gtceu.large_duct_pipe": "Large Duct Pipe", "block.gtceu.large_electrolyzer": "Large Electrolysis Chamber", "block.gtceu.large_electromagnet": "Large Electromagnet", "block.gtceu.large_engraving_laser": "Large Engraving Laser", @@ -543,6 +541,7 @@ "block.gtceu.large_wiremill": "Large Wire Factory", "block.gtceu.laser_hazard_sign_block": "Laser Hazard Sign Block", "block.gtceu.laser_pipe": "Laser Pipe", + "block.gtceu.laser_reflector_pipe": "Laser Reflector Pipe", "block.gtceu.laser_safe_engraving_casing": "Laser-Safe Engraving Casing", "block.gtceu.light_blue_borderless_lamp": "Light Blue Borderless Lamp", "block.gtceu.light_blue_lamp": "Light Blue Lamp", @@ -914,7 +913,6 @@ "block.gtceu.nichrome_coil_block": "Nichrome Coil Block", "block.gtceu.noise_hazard_sign_block": "Noise Hazard Sign Block", "block.gtceu.nonconducting_casing": "Nonconducting Casing", - "block.gtceu.normal_duct_pipe": "Normal Duct Pipe", "block.gtceu.normal_laser_pipe.tooltip": "§7Transmitting power with §fno loss§7 in straight lines", "block.gtceu.normal_optical_pipe.tooltip": "§7Transmitting §fComputation§7 or §fResearch Data§7", "block.gtceu.object_holder": "Object Holder", @@ -1083,7 +1081,6 @@ "block.gtceu.shock_proof_cutting_casing": "Shock Proof Cutting Casing", "block.gtceu.slicing_blades": "Slicing Blades", "block.gtceu.small_dark_concrete_bricks": "Small Dark Concrete Bricks", - "block.gtceu.small_duct_pipe": "Small Duct Pipe", "block.gtceu.small_light_concrete_bricks": "Small Light Concrete Bricks", "block.gtceu.small_marble_bricks": "Small Marble Bricks", "block.gtceu.small_red_granite_bricks": "Small Red Granite Bricks", @@ -2009,7 +2006,6 @@ "compass.node.gtceu.materials/spring": "Spring", "compass.node.gtceu.materials/tiny_dust": "Tiny Dust", "compass.node.gtceu.materials/tool_heads": "Tool Heads", - "compass.node.gtceu.materials/wire_and_cable": "Wire And Cable", "compass.node.gtceu.materials/wire_cutter_head": "Wire Cutter Head", "compass.node.gtceu.misc/advanced_power_thruster": "Advanced Power Thruster", "compass.node.gtceu.misc/ancient_gold_coin": "Ancient Gold Coin", @@ -2032,6 +2028,7 @@ "compass.node.gtceu.misc/crystal_cpu": "Crystal Cpu", "compass.node.gtceu.misc/crystal_soc": "Crystal Soc", "compass.node.gtceu.misc/diamond_grinding_head": "Diamond Grinding Head", + "compass.node.gtceu.misc/dielectric_laser_mirror": "Dielectric Laser Mirror", "compass.node.gtceu.misc/doge_coin": "Doge Coin", "compass.node.gtceu.misc/duct_tape": "Duct Tape", "compass.node.gtceu.misc/electric_motor": "Electric Motor", @@ -2605,6 +2602,10 @@ "fluid.tile.lava": "Lava", "fluid.tile.water": "Water", "fluid_cell.empty": "Empty", + "gregtech.top.pipe.amperage": "Average Amperage / s:", + "gregtech.top.pipe.fluid_last": "Last Fluid:", + "gregtech.top.pipe.item_last": "Last Item:", + "gregtech.top.pipe.voltage": "Average Voltage / s:", "gtceu.air_scrubber": "Air Scrubber", "gtceu.alloy_blast_smelter": "Alloy Blast Smelter", "gtceu.alloy_smelter": "Alloy Smelter", @@ -2622,6 +2623,7 @@ "gtceu.cable.amperage": "Max Amperage: §e%d", "gtceu.cable.loss_per_block": "Loss/Meter/Ampere: §c%d§7 EU-Volt", "gtceu.cable.superconductor": "§d%s Superconductor", + "gtceu.cable.superconductor_loss": "§cLoss is §f0§c under critical temperature §f%s§f K", "gtceu.cable.voltage": "Max Voltage: §a%d §a(%s§a)", "gtceu.canner": "Canner", "gtceu.centrifuge": "Centrifuge", @@ -2727,7 +2729,8 @@ "gtceu.fluid_pipe.channels": "§eChannels: §f%d", "gtceu.fluid_pipe.cryo_proof": "§6Can handle Cryogenics", "gtceu.fluid_pipe.gas_proof": "§6Can handle Gases", - "gtceu.fluid_pipe.max_temperature": "§cTemperature Limit: §f%d K", + "gtceu.fluid_pipe.max_temperature": "§cMax Temperature: §f%s K", + "gtceu.fluid_pipe.min_temperature": "§cMin Temperature: §f%s K", "gtceu.fluid_pipe.not_gas_proof": "§4Gases may leak!", "gtceu.fluid_pipe.plasma_proof": "§6Can handle all Plasmas", "gtceu.fluid_solidifier": "Fluid Solidifier", @@ -2841,7 +2844,6 @@ "gtceu.item_filter.empty_item": "Empty (No Item)", "gtceu.item_filter.footer": "§eClick with item to override", "gtceu.item_list.item_stored": "§7Stored: %d", - "gtceu.pipe.priority": "§9Priority: §f%d", "gtceu.jade.cleaned_this_second": "Cleaned hazard: %s/s", "gtceu.jade.energy_stored": "%d / %d EU", "gtceu.jade.progress_computation": "%s / %s CWU", @@ -3824,6 +3826,7 @@ "gtceu.oc.tooltip.4": "Hold Shift to change by Perfect OC", "gtceu.ore_washer": "Ore Washer", "gtceu.packer": "Packer", + "gtceu.pipe.priority": "§9Priority: §f%d", "gtceu.plasma_generator": "Plasma Generator", "gtceu.polarizer": "Polarizer", "gtceu.primitive_blast_furnace": "Primitive Blast Furnace", @@ -4223,6 +4226,7 @@ "item.gtceu.data_stick": "Data Stick", "item.gtceu.data_stick.tooltip": "§7A Low Capacity Data Storage", "item.gtceu.diamond_grinding_head": "Diamond Grinding Head", + "item.gtceu.dielectric_laser_mirror": "Dielectric Laser Mirror", "item.gtceu.diode": "Diode", "item.gtceu.diode.tooltip": "§7Basic Electronic Component", "item.gtceu.doge_coin": "Doge Coin", @@ -5257,7 +5261,6 @@ "material.gtceu.einsteinium": "Einsteinium", "material.gtceu.electrotine": "Electrotine", "material.gtceu.electrum": "Electrum", - "material.gtceu.elementium": "Elementium", "material.gtceu.emerald": "Emerald", "material.gtceu.ender_air": "Ender Air", "material.gtceu.ender_eye": "Ender Eye", diff --git a/src/generated/resources/assets/gtceu/models/item/dielectric_laser_mirror.json b/src/generated/resources/assets/gtceu/models/item/dielectric_laser_mirror.json new file mode 100644 index 0000000000..32ac94cbee --- /dev/null +++ b/src/generated/resources/assets/gtceu/models/item/dielectric_laser_mirror.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/generated", + "textures": { + "layer0": "gtceu:item/dielectric_laser_mirror" + } +} \ No newline at end of file diff --git a/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json b/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json index c8cfbac305..048db8a64c 100644 --- a/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json +++ b/src/generated/resources/data/forge/tags/blocks/mineable/wire_cutter.json @@ -1,6 +1,7 @@ { "values": [ "gtceu:laser_pipe", + "gtceu:laser_reflector_pipe", "gtceu:optical_fiber_cable" ] } \ No newline at end of file diff --git a/src/generated/resources/data/forge/tags/blocks/mineable/wrench.json b/src/generated/resources/data/forge/tags/blocks/mineable/wrench.json index a6622a6fef..b94072e2e6 100644 --- a/src/generated/resources/data/forge/tags/blocks/mineable/wrench.json +++ b/src/generated/resources/data/forge/tags/blocks/mineable/wrench.json @@ -175,10 +175,6 @@ "gtceu:brown_large_metal_sheet", "gtceu:green_large_metal_sheet", "gtceu:red_large_metal_sheet", - "gtceu:black_large_metal_sheet", - "gtceu:small_duct_pipe", - "gtceu:normal_duct_pipe", - "gtceu:large_duct_pipe", - "gtceu:huge_duct_pipe" + "gtceu:black_large_metal_sheet" ] } \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/loot_tables/blocks/large_duct_pipe.json b/src/generated/resources/data/gtceu/loot_tables/blocks/large_duct_pipe.json deleted file mode 100644 index 3fc36553a0..0000000000 --- a/src/generated/resources/data/gtceu/loot_tables/blocks/large_duct_pipe.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "type": "minecraft:block", - "pools": [ - { - "bonus_rolls": 0.0, - "conditions": [ - { - "condition": "minecraft:survives_explosion" - } - ], - "entries": [ - { - "type": "minecraft:item", - "name": "gtceu:large_duct_pipe" - } - ], - "rolls": 1.0 - } - ], - "random_sequence": "gtceu:blocks/large_duct_pipe" -} \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/loot_tables/blocks/huge_duct_pipe.json b/src/generated/resources/data/gtceu/loot_tables/blocks/laser_reflector_pipe.json similarity index 74% rename from src/generated/resources/data/gtceu/loot_tables/blocks/huge_duct_pipe.json rename to src/generated/resources/data/gtceu/loot_tables/blocks/laser_reflector_pipe.json index 5d5feeb4b8..d25afea720 100644 --- a/src/generated/resources/data/gtceu/loot_tables/blocks/huge_duct_pipe.json +++ b/src/generated/resources/data/gtceu/loot_tables/blocks/laser_reflector_pipe.json @@ -11,11 +11,11 @@ "entries": [ { "type": "minecraft:item", - "name": "gtceu:huge_duct_pipe" + "name": "gtceu:laser_reflector_pipe" } ], "rolls": 1.0 } ], - "random_sequence": "gtceu:blocks/huge_duct_pipe" + "random_sequence": "gtceu:blocks/laser_reflector_pipe" } \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/loot_tables/blocks/normal_duct_pipe.json b/src/generated/resources/data/gtceu/loot_tables/blocks/normal_duct_pipe.json deleted file mode 100644 index ad7dfb81e2..0000000000 --- a/src/generated/resources/data/gtceu/loot_tables/blocks/normal_duct_pipe.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "type": "minecraft:block", - "pools": [ - { - "bonus_rolls": 0.0, - "conditions": [ - { - "condition": "minecraft:survives_explosion" - } - ], - "entries": [ - { - "type": "minecraft:item", - "name": "gtceu:normal_duct_pipe" - } - ], - "rolls": 1.0 - } - ], - "random_sequence": "gtceu:blocks/normal_duct_pipe" -} \ No newline at end of file diff --git a/src/generated/resources/data/gtceu/loot_tables/blocks/small_duct_pipe.json b/src/generated/resources/data/gtceu/loot_tables/blocks/small_duct_pipe.json deleted file mode 100644 index 51aaac2bbc..0000000000 --- a/src/generated/resources/data/gtceu/loot_tables/blocks/small_duct_pipe.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "type": "minecraft:block", - "pools": [ - { - "bonus_rolls": 0.0, - "conditions": [ - { - "condition": "minecraft:survives_explosion" - } - ], - "entries": [ - { - "type": "minecraft:item", - "name": "gtceu:small_duct_pipe" - } - ], - "rolls": 1.0 - } - ], - "random_sequence": "gtceu:blocks/small_duct_pipe" -} \ No newline at end of file diff --git a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java index cdad437542..f9c02c059d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java +++ b/src/main/java/com/gregtechceu/gtceu/api/addon/IGTAddon.java @@ -127,6 +127,7 @@ default void registerBedrockOreVeins() {} /** * Initialize custom {@link NetLogicType} instances here. + * * @see NetLogicEntryTypes */ default void loadNetLogicTypes() {} diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java index ab36bfde6d..22016f262e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/IPropertyFluidFilter.java @@ -3,8 +3,6 @@ import com.gregtechceu.gtceu.api.fluids.FluidState; import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; import com.gregtechceu.gtceu.api.fluids.attribute.IAttributedFluid; -import com.gregtechceu.gtceu.utils.FormattingUtil; -import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java index 821d50eb18..d85ec8cd8c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractDoubleLogicData.java @@ -2,8 +2,8 @@ import net.minecraft.nbt.DoubleTag; import net.minecraft.network.FriendlyByteBuf; - import net.minecraft.resources.ResourceLocation; + import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java index 970e5f97ca..f1290eadfb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractIntLogicData.java @@ -2,8 +2,8 @@ import net.minecraft.nbt.IntTag; import net.minecraft.network.FriendlyByteBuf; - import net.minecraft.resources.ResourceLocation; + import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java index 92fc75efd4..8848f524e4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractLongLogicData.java @@ -2,8 +2,8 @@ import net.minecraft.nbt.LongTag; import net.minecraft.network.FriendlyByteBuf; - import net.minecraft.resources.ResourceLocation; + import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java index 968f9e8963..e41b63d019 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/AbstractTransientLogicData.java @@ -2,6 +2,7 @@ import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; + import org.jetbrains.annotations.Nullable; public abstract class AbstractTransientLogicData> diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java index b445a1144b..52751ae3fb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ChannelCountLogic.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.logic; import com.gregtechceu.gtceu.GTCEu; + import org.jetbrains.annotations.NotNull; public final class ChannelCountLogic extends AbstractIntLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java index f4805b6713..50a7a3c42c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicData.java @@ -200,7 +200,8 @@ public void decode(FriendlyByteBuf buf) { this.logicEntrySet.trim(); } - public static void writeEntry(@NotNull FriendlyByteBuf buf, @NotNull NetLogicEntry entry, boolean fullChange) { + public static void writeEntry(@NotNull FriendlyByteBuf buf, @NotNull NetLogicEntry entry, + boolean fullChange) { buf.writeVarInt(NetLogicRegistry.getNetworkID(entry)); buf.writeBoolean(fullChange); entry.encode(buf, fullChange); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java index 3827931561..a563a4b10c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicEntry.java @@ -10,7 +10,6 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.common.util.INBTSerializable; -import lombok.Getter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java index 1b57bf28f6..624d5c2eff 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistrationEvent.java @@ -1,10 +1,10 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; -import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.event.IModBusEvent; +import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; + import java.util.Comparator; public final class NetLogicRegistrationEvent extends Event implements IModBusEvent { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index 91ba4e7834..e6a971e3b1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -1,13 +1,14 @@ package com.gregtechceu.gtceu.api.graphnet.logic; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; import com.lowdragmc.lowdraglib.LDLib; -import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; -import net.minecraft.client.Minecraft; +import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraftforge.common.MinecraftForge; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java index ce6f4b48a5..a1522287c5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicType.java @@ -2,11 +2,13 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.util.StringRepresentable; + import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; public class NetLogicType> implements StringRepresentable { + private final @NotNull String name; private final @NotNull Supplier<@NotNull T> supplier; private final @NotNull T defaultable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java index c85cea837e..4a7d7db91c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/ThroughputLogic.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.logic; import com.gregtechceu.gtceu.GTCEu; + import org.jetbrains.annotations.NotNull; public final class ThroughputLogic extends AbstractLongLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java index af79cf7de6..ec5ed7a118 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/WeightFactorLogic.java @@ -1,6 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.logic; import com.gregtechceu.gtceu.GTCEu; + import org.jetbrains.annotations.NotNull; public final class WeightFactorLogic extends AbstractDoubleLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java index 54dc566382..151a3b7e9e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/WorldPipeNet.java @@ -12,6 +12,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.graphnet.pipenet.predicate.BlockedPredicate; import com.gregtechceu.gtceu.api.graphnet.predicate.EdgePredicate; +import com.gregtechceu.gtceu.api.graphnet.predicate.NetPredicateType; import com.gregtechceu.gtceu.api.graphnet.worldnet.WorldPosNet; import com.gregtechceu.gtceu.common.cover.ShutterCover; import com.gregtechceu.gtceu.utils.GTUtil; @@ -134,7 +135,7 @@ protected boolean predicateEdge(@NotNull NetEdge edge, @NotNull WorldPipeNetNode protected void coverPredication(@NotNull NetEdge edge, @Nullable CoverBehavior a, @Nullable CoverBehavior b) { if (a instanceof ShutterCover aS && aS.isWorkingEnabled() || b instanceof ShutterCover bS && bS.isWorkingEnabled()) { - edge.getPredicateHandler().setPredicate(BlockedPredicate.INSTANCE); + edge.getPredicateHandler().setPredicate(BlockedPredicate.TYPE.getNew()); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java index f8f1854642..90bc5caf41 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistrationEvent.java @@ -1,9 +1,10 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.event.IModBusEvent; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,7 +15,7 @@ public final class PipeStructureRegistrationEvent extends Event implements IModB private final Map, Set> registry = new Object2ObjectLinkedOpenHashMap<>(); public void register(@NotNull T structure) { - //noinspection unchecked + // noinspection unchecked Set structures = (Set) registry.computeIfAbsent(structure.getClass(), k -> new ObjectLinkedOpenHashSet<>()); structures.add(structure); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java index 1fee935c71..b5621a1268 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -1,10 +1,7 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; -import com.gregtechceu.gtceu.utils.GTUtil; - -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import net.minecraftforge.common.MinecraftForge; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.UnmodifiableView; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index d7a321f99e..4b255fc0c2 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -12,8 +12,8 @@ import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicRegistry; +import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNet; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java index 42fbe50bab..212ac04ed5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/predicate/FilterPredicate.java @@ -54,11 +54,6 @@ public boolean andy() { return true; } - @Override - public @NotNull FilterPredicate getNew() { - return new FilterPredicate(); - } - @Override public boolean test(IPredicateTestObject object) { Object test = object.recombine(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java index a69cd6c2b2..04038b2a3d 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicate.java @@ -3,7 +3,6 @@ import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; import net.minecraft.nbt.Tag; -import net.minecraft.util.StringRepresentable; import net.minecraftforge.common.util.INBTSerializable; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java index 71c7637861..8bb9a51936 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/EdgePredicateHandler.java @@ -6,7 +6,6 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; -import net.minecraft.util.StringRepresentable; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java index 7149683c6c..3cda89a254 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistrationEvent.java @@ -1,9 +1,10 @@ package com.gregtechceu.gtceu.api.graphnet.predicate; -import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.event.IModBusEvent; +import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; + import java.util.Comparator; public final class NetPredicateRegistrationEvent extends Event implements IModBusEvent { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java index 03f0788976..729615c76b 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java @@ -1,12 +1,14 @@ package com.gregtechceu.gtceu.api.graphnet.predicate; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; import com.lowdragmc.lowdraglib.LDLib; -import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; + import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraftforge.common.MinecraftForge; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java index fa2517103e..ad13c66786 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateType.java @@ -2,6 +2,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.util.StringRepresentable; + import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java index 293520f8cf..53e585ad2b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/cache/ColorQuadCache.java @@ -23,15 +23,15 @@ public ColorQuadCache(List prototypes) { } public List getQuads(ColorData data) { - //List existing = cache.get(data); - //if (existing == null) { - // existing = new ObjectArrayList<>(); - // for (BakedQuad quad : prototypes) { - // existing.add(quad); - // } - // cache.put(data, existing); - // // if (cache.size() > 20) cache.removeLast(); - //} + // List existing = cache.get(data); + // if (existing == null) { + // existing = new ObjectArrayList<>(); + // for (BakedQuad quad : prototypes) { + // existing.add(quad); + // } + // cache.put(data, existing); + // // if (cache.size() > 20) cache.removeLast(); + // } return prototypes; } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java index 68467b65ed..f7c085f9f4 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/quad/PipeQuadHelper.java @@ -1,8 +1,8 @@ package com.gregtechceu.gtceu.client.renderer.pipe.quad; import com.gregtechceu.gtceu.client.renderer.pipe.util.SpriteInformation; - import com.gregtechceu.gtceu.utils.GTUtil; + import com.lowdragmc.lowdraglib.client.bakedpipeline.Quad; import net.minecraft.client.renderer.RenderType; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index 48fecbca84..f0f22e6b15 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -4,7 +4,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IInsulatable; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java index a42822ac42..ae6b8e4c95 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctPipeBlock.java @@ -2,11 +2,10 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.common.pipelike.handlers.DuctNetHandler; -import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import org.jetbrains.annotations.NotNull; @@ -22,7 +21,8 @@ protected String getConnectLangKey() { } @Override - protected @NotNull IPipeNetNodeHandler getHandler(BlockGetter world, BlockPos pos) { + @NotNull + public IPipeNetNodeHandler getHandler(PipeBlockEntity blockEntityContext) { return DuctNetHandler.INSTANCE; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java index ff28287351..ab9e1471d8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java index 401b8ff2a9..91bdf59643 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserPipeBlock.java @@ -2,14 +2,11 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.IPipeNetNodeHandler; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.ActivablePipeBlock; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.LaserNetHandler; -import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.state.BlockBehaviour; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java index ff0a874643..3d30095e68 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java index ef80607190..32db68214a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalPipeBlock.java @@ -6,9 +6,7 @@ import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.common.pipelike.handlers.DuctNetHandler; -import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.state.BlockBehaviour; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java index 84b1db419f..7cbfd291ec 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java index be1c680824..30c26bd56f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -4,7 +4,6 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeChanneledStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IPipeMaterialStructure; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistrationEvent; -import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.PipeStructureRegistry; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java index 46601ecdee..64e242d2b8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/handlers/properties/MaterialEnergyProperties.java @@ -179,10 +179,10 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { .setLogicEntry(WeightFactorLogic.TYPE.getWith(loss + 0.001 / amperage)) .setLogicEntry(ThroughputLogic.TYPE.getWith(amperage)) .setLogicEntry(VoltageLimitLogic.TYPE.getWith(voltageLimit)) - .setLogicEntry(TemperatureLogic.TYPE.getNew() - .getWith(TemperatureLossFunction.getOrCreateCable(coolingFactor), materialMeltTemperature, - 1, - 100 * cable.material(), cable.partialBurnThreshold())); + .setLogicEntry( + TemperatureLogic.TYPE.getWith(TemperatureLossFunction.getOrCreateCable(coolingFactor), + materialMeltTemperature, 1, 100 * cable.material(), + cable.partialBurnThreshold())); if (superconductorCriticalTemperature > 0) { data.setLogicEntry(SuperconductorLogic.TYPE.getWith(superconductorCriticalTemperature)); } @@ -195,9 +195,8 @@ public void mutateData(NetLogicData data, IPipeStructure structure) { .setLogicEntry(WeightFactorLogic.TYPE.getWith(loss + 0.001 / amperage)) .setLogicEntry(ThroughputLogic.TYPE.getWith(amperage)) .setLogicEntry(VoltageLimitLogic.TYPE.getWith(voltageLimit)) - .setLogicEntry(TemperatureLogic.TYPE.getNew() - .getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), materialMeltTemperature, 1, - 50 * pipe.material(), null)); + .setLogicEntry(TemperatureLogic.TYPE.getWith(TemperatureLossFunction.getOrCreatePipe(coolingFactor), + materialMeltTemperature, 1, 50 * pipe.material(), null)); if (superconductorCriticalTemperature > 0) { data.setLogicEntry(SuperconductorLogic.TYPE.getWith(superconductorCriticalTemperature)); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java index e006647557..cf3abde20f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/EnergyFlowLogic.java @@ -2,17 +2,13 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractTransientLogicData; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; import com.lowdragmc.lowdraglib.Platform; -import net.minecraft.nbt.ByteTag; -import net.minecraft.network.FriendlyByteBuf; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import lombok.Getter; import org.jetbrains.annotations.NotNull; import java.util.Collections; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java index 1ddc93821c..0502c1f4a5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/SuperconductorLogic.java @@ -2,7 +2,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractIntLogicData; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; + import org.jetbrains.annotations.NotNull; public final class SuperconductorLogic extends AbstractIntLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java index 2cef05b9de..d93c765d93 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLimitLogic.java @@ -3,7 +3,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; + import org.jetbrains.annotations.NotNull; public final class VoltageLimitLogic extends AbstractLongLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java index 29971c201d..6e5bf78ed4 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/energy/VoltageLossLogic.java @@ -3,7 +3,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractLongLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicEntry; -import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; + import org.jetbrains.annotations.NotNull; public final class VoltageLossLogic extends AbstractLongLogicData { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java index 73132aca6e..2d3f8600d5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidCapabilityObject.java @@ -88,7 +88,7 @@ public Capability[] getCapabilities() { public LazyOptional getCapabilityForSide(Capability capability, @Nullable Direction facing) { if (capability == ForgeCapabilities.FLUID_HANDLER) { if (facing == null) return LazyOptional.empty(); // hard override to prevent TOP from displaying a tank. - //noinspection ConstantValue + // noinspection ConstantValue return ForgeCapabilities.FLUID_HANDLER.orEmpty(capability, facing == null ? LazyOptional.of(() -> FluidTransferHelperImpl.toFluidHandler(this)) : LazyOptional.of(() -> FluidTransferHelperImpl.toFluidHandler(wrappers.get(facing)))); diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java index eaa464869a..d4d0ff6d87 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidFlowLogic.java @@ -3,8 +3,10 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractTransientLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; + import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; + import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java index a7527ecfeb..f453ca7e3d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/fluid/FluidTraverseData.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.common.pipelike.net.fluid; -import com.google.common.primitives.Ints; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.fluids.FluidState; import com.gregtechceu.gtceu.api.fluids.GTFluid; @@ -30,6 +29,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleTypes; +import com.google.common.primitives.Ints; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java index 504d542e38..a6b3f791e2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemFlowLogic.java @@ -3,11 +3,14 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.graphnet.logic.AbstractTransientLogicData; import com.gregtechceu.gtceu.api.graphnet.logic.NetLogicType; + import com.lowdragmc.lowdraglib.Platform; + +import net.minecraft.world.item.ItemStack; + import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Collections; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java index 88db6b2df9..c3f9479c5d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/net/item/ItemTraverseData.java @@ -1,6 +1,5 @@ package com.gregtechceu.gtceu.common.pipelike.net.item; -import com.google.common.primitives.Ints; import com.gregtechceu.gtceu.api.graphnet.IGraphNet; import com.gregtechceu.gtceu.api.graphnet.NetNode; import com.gregtechceu.gtceu.api.graphnet.edge.AbstractNetFlowEdge; @@ -19,6 +18,7 @@ import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.IItemHandler; +import com.google.common.primitives.Ints; import org.jetbrains.annotations.NotNull; public class ItemTraverseData extends AbstractTraverseData { @@ -85,5 +85,4 @@ private void recordFlow(@NotNull NetNode node, long flow) { } logic.recordFlow(getQueryTick(), getTestObject().recombine(Ints.saturatedCast(flow))); } - } diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java b/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java index d710bcfecf..f2e1c7fa8f 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/IntegrationLang.java @@ -101,7 +101,6 @@ private static void initWailaLikeLang(RegistrateLangProvider provider) { provider.add("gtceu.top.progress_sec", " / %s s"); provider.add("gtceu.top.progress_tick", " / %s t"); - provider.add("gregtech.top.pipe.voltage", "Average Voltage / s:"); provider.add("gregtech.top.pipe.amperage", "Average Amperage / s:"); provider.add("gregtech.top.pipe.fluid_last", "Last Fluid:"); diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java index 392fa7176c..0ea88d4eb7 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/misc/ComputerRecipes.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.machine.multiblock.CleanroomType; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.data.recipe.CustomTags; + import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java index dd22115d93..99260d0be2 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/element/FluidStackElement.java @@ -3,11 +3,13 @@ import com.lowdragmc.lowdraglib.gui.util.DrawerHelper; import com.lowdragmc.lowdraglib.gui.util.TextFormattingUtil; import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -import com.mojang.blaze3d.systems.RenderSystem; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.phys.Vec2; + +import com.mojang.blaze3d.systems.RenderSystem; import snownee.jade.api.ui.Element; public class FluidStackElement extends Element { @@ -45,6 +47,5 @@ public void render(GuiGraphics guiGraphics, float x, float y, float width, float } RenderSystem.enableBlend(); RenderSystem.setShaderColor(1, 1, 1, 1); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java index 8cd976f81d..1f95857bda 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/jade/provider/PipeTileInfoProvider.java @@ -11,20 +11,18 @@ import com.gregtechceu.gtceu.common.pipelike.net.fluid.FluidFlowLogic; import com.gregtechceu.gtceu.common.pipelike.net.item.ItemFlowLogic; import com.gregtechceu.gtceu.integration.jade.element.FluidStackElement; + import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -import com.lowdragmc.lowdraglib.side.fluid.forge.FluidHelperImpl; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import mcjty.theoneprobe.api.CompoundText; -import mcjty.theoneprobe.api.ElementAlignment; -import net.minecraft.core.registries.BuiltInRegistries; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; + +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import snownee.jade.api.BlockAccessor; import snownee.jade.api.IBlockComponentProvider; import snownee.jade.api.IServerDataProvider; @@ -54,7 +52,8 @@ public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPlugi CompoundTag fluid = serverData.getCompound("Fluid"); FluidStack stack = FluidStack.loadFromTag(fluid.getCompound("LastFluid")); - iTooltip.add(IElementHelper.get().text("gtceu.top.pipe.fluid_last").align(IElement.Align.LEFT)); + iTooltip.add(IElementHelper.get().text(Component.translatable("gtceu.top.pipe.fluid_last")) + .align(IElement.Align.LEFT)); iTooltip.append(new FluidStackElement(stack, 14, 14)); iTooltip.append(stack.getDisplayName()); @@ -72,7 +71,8 @@ public void appendTooltip(ITooltip iTooltip, BlockAccessor blockAccessor, IPlugi CompoundTag item = serverData.getCompound("Item"); ItemStack stack = ItemStack.of(item.getCompound("LastItem")); - iTooltip.add(IElementHelper.get().text("gtceu.top.pipe.item_last").align(IElement.Align.LEFT)); + iTooltip.add(IElementHelper.get().text(Component.translatable("gtceu.top.pipe.item_last")) + .align(IElement.Align.LEFT)); iTooltip.append(IElementHelper.get().item(stack)); iTooltip.append(stack.getDisplayName()); diff --git a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java index f949e03a3f..8f18eef354 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/top/provider/PipeTileInfoProvider.java @@ -12,20 +12,19 @@ import com.gregtechceu.gtceu.common.pipelike.net.item.ItemFlowLogic; import com.gregtechceu.gtceu.integration.top.element.FluidStackElement; import com.gregtechceu.gtceu.integration.top.element.FluidStyle; -import com.lowdragmc.lowdraglib.side.fluid.FluidHelper; + import com.lowdragmc.lowdraglib.side.fluid.FluidStack; -import com.lowdragmc.lowdraglib.side.fluid.forge.FluidHelperImpl; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import mcjty.theoneprobe.api.*; -import mcjty.theoneprobe.apiimpl.styles.TextStyle; + import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; + +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; +import mcjty.theoneprobe.api.*; public class PipeTileInfoProvider implements IProbeInfoProvider { @@ -102,7 +101,8 @@ private void addFluidFlowInformation(ProbeMode probeMode, IProbeInfo iProbeInfo, FluidStack stack = entry.getKey().recombine(); iProbeInfo.horizontal(iProbeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER)) .element(new FluidStackElement(logic.getLast(), new FluidStyle().bounds(14, 14))) - .text(entry.getLongValue() * 20 / FluidFlowLogic.MEMORY_TICKS + " mB/S " + stack.getDisplayName().getString()); + .text(entry.getLongValue() * 20 / FluidFlowLogic.MEMORY_TICKS + " mB/S " + + stack.getDisplayName().getString()); } } diff --git a/src/main/resources/assets/gtceu/textures/item/dielectric_laser_mirror.png b/src/main/resources/assets/gtceu/textures/item/dielectric_laser_mirror.png new file mode 100644 index 0000000000000000000000000000000000000000..398c95041dc3b5d096da5e531af0d80b447bcc00 GIT binary patch literal 5232 zcmeHLe{dAl9p8i>fdksBK#(+p+l`=N_ip!o-*N}WyMr8Za3n!;ZKv>V_g%8(?)JFd ziADKv)Q-r`}uyp-|y#r-19=Nb#9#zyy?r7vhn;8K+$X%i*r-PUhvZOTky4 z3Y_CS4HcjC-;-OOzT{}nZ@)a9Cm zA3T?{QCfe)+|qJ&{?dDX^4-d#kB`aE&z?H_%^zM%CJr5Id7}MDPfu1;U;Oyqu=ziz z@2W)9UuC`}94|$5K#+n^myEvS2e16g; z#UW|ZnRE>8Ns3hlYQBba#Dx%7>|QuPf!>@{g`&hby*`mh=n_Vq6ff7acDr5A81x1M zjS#e49aTV*j>-j?qMySJWj-#(6j6$jm=gr0O2tW0$WEs6i^P1sG<{SaPyy+oPlA}9 z)iL@=M4#y)E1oJuGLX=)9&#z#rut$iOOV?D}f>gxNpjbn4!xpui%tVlTns*2~Rl5pCD4&mWOME3x z&+B$lI6fyxyeM$$(8vUNONg=3zzQw2DP(2opb>^>!3-D>;(39!f($BeR8~NghnNbH z>qNw32TVw?o2@hpd7d@}Lkw**T7q=QWHti>YZ6Q>%%E5n7g1M&aAsDRNjNo0&G*8G*I~qn!?#8Ab>iZ5AeIQ>g@=TPVdN04=8&0p(C1i;aqVD6e(URNnt02lOnNa+U!FcN&pIQ0|g>d#$e(YJI5MI zSvwvWmF8hdB2h;1tJSIgJyinN_P_PNhDCKVk)*mUIKcOp zAcHC>sCgo;eiL5-qU8{s9|H}Wniq#@23v?VTX@LREMNg`;%z}1*z88y$QpnJ^^)1j z_OD=?U6w*h0>oiqInohng&I`VioAbdsU8@bO`-zgbwHBQjGZ2o%tGl0iq+#2BUPcw zb6=)?@#4j|#HX>?5#L|FcJJOjgfQ)pIT+3{ljxQtw{yls?d|P-nIzen(eHG8@#4ia zG);h`d%fPY;Z6r>f;(|IckUdKmzOsLdRu}^mo5!)*tv5jQBzZsUe2*8Yi3<|F6Ee; zo2x>Gi=OgLKe4)BzOd@}?&|95tF5iQsSnbrq*ySC(P&J)sx{-Z@s*i+3UCtvHeiy> fl7@3k5q$m64%>lG?Ay!6;Y_@qrS5|dude+c{=ARO literal 0 HcmV?d00001 From 6c7ecd0db631b514ca66932578235b71820a8b67 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Fri, 13 Sep 2024 08:48:17 +0300 Subject: [PATCH 48/70] disable gradle-home-cache-cleanup so that action works again --- gradle/scripts/publishing.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle/scripts/publishing.gradle b/gradle/scripts/publishing.gradle index b2807e361e..716d04e122 100644 --- a/gradle/scripts/publishing.gradle +++ b/gradle/scripts/publishing.gradle @@ -8,7 +8,7 @@ publishing { publications { mavenJava(MavenPublication) { groupId = project.maven_group - artifactId = project.archivesBaseName + artifactId = base.archivesName version = project.version from components.java diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0d1842103b..e1adfb4938 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From 388b11a0d9a10b125f46d9ed375ed9516ff16296 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 10:55:09 +0300 Subject: [PATCH 49/70] fix errors, spotless, datagen refresh --- dependencies.gradle | 2 +- gradle/scripts/jars.gradle | 3 --- .../compass/nodes/materials/chainsaw_head.json | 2 +- .../api/machine/multiblock/PartAbility.java | 4 ++-- .../gregtechceu/gtceu/client/ClientProxy.java | 1 + .../gtceu/common/data/GTMachines.java | 16 ++++++++-------- .../electric/ActiveTransformerMachine.java | 6 +++--- .../gtceu/forge/ForgeCommonEventListener.java | 1 - 8 files changed, 16 insertions(+), 19 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 97321c2a82..41d9ce5908 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -5,7 +5,7 @@ dependencies { // Packages that aren't mods, and thus need to be included in the release files. api(shadow('org.jgrapht:jgrapht-core:1.5.2')) // JGraphT 1.5.2 - forgeRuntimeLibrary('org.jgrapht:jgrapht-core:1.5.2') + additionalRuntimeClasspath('org.jgrapht:jgrapht-core:1.5.2') // LDLib modApi(forge.ldlib.forge) { transitive = false } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 7aab1738ff..584509f267 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -13,9 +13,6 @@ obfuscation { reobfuscate(tasks.named('slimJar'), sourceSets.main) { archiveClassifier = "slim" } - reobfuscate(tasks.named('shadowJar'), sourceSets.main) { - archiveClassifier = "shadow" - } reobfuscate(tasks.named('shadowJar'), sourceSets.main) { archiveClassifier = null archiveClassifier.convention(null) diff --git a/src/generated/resources/assets/gtceu/compass/nodes/materials/chainsaw_head.json b/src/generated/resources/assets/gtceu/compass/nodes/materials/chainsaw_head.json index 11db4c67b3..f0714fb296 100644 --- a/src/generated/resources/assets/gtceu/compass/nodes/materials/chainsaw_head.json +++ b/src/generated/resources/assets/gtceu/compass/nodes/materials/chainsaw_head.json @@ -5,7 +5,7 @@ }, "page": "gtceu:materials/chainsaw_head", "position": [ - -250, + -300, 250 ], "section": "gtceu:materials" diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/PartAbility.java b/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/PartAbility.java index ce2fb49ae8..2a305c4ae0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/PartAbility.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/multiblock/PartAbility.java @@ -48,8 +48,8 @@ public class PartAbility { public static final PartAbility TANK_VALVE = new PartAbility("tank_valve"); public static final PartAbility PASSTHROUGH_HATCH = new PartAbility("passthrough_hatch"); public static final PartAbility PARALLEL_HATCH = new PartAbility("parallel_hatch"); - public static final PartAbility INPUT_LASER = new PartAbility("input_laser"); - public static final PartAbility OUTPUT_LASER = new PartAbility("output_laser"); + public static final PartAbility LASER_RECEPTION = new PartAbility("laser_reception"); + public static final PartAbility LASER_TRANSMISSION = new PartAbility("laser_transmission"); public static final PartAbility COMPUTATION_DATA_RECEPTION = new PartAbility("computation_data_reception"); public static final PartAbility COMPUTATION_DATA_TRANSMISSION = new PartAbility("computation_data_transmission"); diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index b372e7595d..fc3e8178e5 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -29,6 +29,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.event.*; import net.minecraftforge.eventbus.api.SubscribeEvent; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java index 4621237371..9d17335169 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java @@ -1183,17 +1183,17 @@ public static BiConsumer> createTankTooltips(String n HV, EV, IV, LuV, ZPM, UV); public static final MachineDefinition[] LASER_INPUT_HATCH_256 = registerLaserHatch(IO.IN, 256, - PartAbility.INPUT_LASER); + PartAbility.LASER_RECEPTION); public static final MachineDefinition[] LASER_OUTPUT_HATCH_256 = registerLaserHatch(IO.OUT, 256, - PartAbility.OUTPUT_LASER); + PartAbility.LASER_TRANSMISSION); public static final MachineDefinition[] LASER_INPUT_HATCH_1024 = registerLaserHatch(IO.IN, 1024, - PartAbility.INPUT_LASER); + PartAbility.LASER_RECEPTION); public static final MachineDefinition[] LASER_OUTPUT_HATCH_1024 = registerLaserHatch(IO.OUT, 1024, - PartAbility.OUTPUT_LASER); + PartAbility.LASER_TRANSMISSION); public static final MachineDefinition[] LASER_INPUT_HATCH_4096 = registerLaserHatch(IO.IN, 4096, - PartAbility.INPUT_LASER); + PartAbility.LASER_RECEPTION); public static final MachineDefinition[] LASER_OUTPUT_HATCH_4096 = registerLaserHatch(IO.OUT, 4096, - PartAbility.OUTPUT_LASER); + PartAbility.LASER_TRANSMISSION); ////////////////////////////////////// // ******* Multiblock *******// @@ -2127,9 +2127,9 @@ public static BiConsumer> createTankTooltips(String n .setMinGlobalLimited(PowerSubstationMachine.MIN_CASINGS) .or(autoAbilities(true, false, false)) .or(abilities(PartAbility.INPUT_ENERGY, PartAbility.SUBSTATION_INPUT_ENERGY, - PartAbility.INPUT_LASER).setMinGlobalLimited(1)) + PartAbility.LASER_RECEPTION).setMinGlobalLimited(1)) .or(abilities(PartAbility.OUTPUT_ENERGY, PartAbility.SUBSTATION_OUTPUT_ENERGY, - PartAbility.OUTPUT_LASER).setMinGlobalLimited(1))) + PartAbility.LASER_TRANSMISSION).setMinGlobalLimited(1))) .where('G', blocks(CASING_LAMINATED_GLASS.get())) .where('B', Predicates.powerSubstationBatteries()) .build()) diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/ActiveTransformerMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/ActiveTransformerMachine.java index efdeed95fa..958e049d8e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/ActiveTransformerMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/ActiveTransformerMachine.java @@ -128,7 +128,7 @@ private List getPrioritySortedParts() { if (PartAbility.SUBSTATION_OUTPUT_ENERGY.isApplicable(partBlock)) return 2; - if (PartAbility.OUTPUT_LASER.isApplicable(partBlock)) + if (PartAbility.LASER_TRANSMISSION.isApplicable(partBlock)) return 3; } @@ -154,8 +154,8 @@ public static TraceabilityPredicate getHatchPredicates() { .or(abilities(PartAbility.OUTPUT_ENERGY).setPreviewCount(2)) .or(abilities(PartAbility.SUBSTATION_INPUT_ENERGY).setPreviewCount(1)) .or(abilities(PartAbility.SUBSTATION_OUTPUT_ENERGY).setPreviewCount(1)) - .or(abilities(PartAbility.INPUT_LASER).setPreviewCount(1)) - .or(abilities(PartAbility.OUTPUT_LASER).setPreviewCount(1)); + .or(abilities(PartAbility.LASER_RECEPTION).setPreviewCount(1)) + .or(abilities(PartAbility.LASER_TRANSMISSION).setPreviewCount(1)); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java index 442b22bd56..5670bae562 100644 --- a/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/forge/ForgeCommonEventListener.java @@ -25,7 +25,6 @@ import com.gregtechceu.gtceu.common.commands.GTCommands; import com.gregtechceu.gtceu.common.commands.HazardCommands; import com.gregtechceu.gtceu.common.commands.MedicalConditionCommands; -import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTItems; From b0acd1417729a0a11da60f4aeeabd3f1b6696aee Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 14:55:32 +0300 Subject: [PATCH 50/70] attempt number 1 at fixing the github build --- build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle b/build.gradle index 8520ec1d85..a10435e7c5 100644 --- a/build.gradle +++ b/build.gradle @@ -26,7 +26,6 @@ tasks.register('slimJar', ShadowJar) { afterEvaluate { tasks.withType(ShadowJar).configureEach { - dependsOn shadowJar.configurations minimize() relocate("org.jgrapht", "${maven_group}.repack.org.jgrapht") relocate("org.jheaps", "${maven_group}.repack.org.jheaps") From 6d48dccdd734a5ffa915a96e9d9640c6a7da6a88 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 14:57:01 +0300 Subject: [PATCH 51/70] number 2 --- gradle/scripts/jars.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 584509f267..ab35d587ab 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -6,6 +6,7 @@ shadowJar { slimJar { from sourceSets.main.output + configurations = [project.configurations.shadow] archiveClassifier = "dev-slim" } From bfca36fbd4dbe1a5c99b0b63a7ad7665ed1b3e76 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 15:07:56 +0300 Subject: [PATCH 52/70] attempt number 3 --- build.gradle | 17 +++++++++-------- dependencies.gradle | 2 +- gradle/scripts/jars.gradle | 9 +++++++-- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index a10435e7c5..f1fe80d3b8 100644 --- a/build.gradle +++ b/build.gradle @@ -24,8 +24,17 @@ tasks.register('slimJar', ShadowJar) { from sourceSets.main.output } +apply from: "$rootDir/gradle/scripts/moddevgradle.gradle" +apply from: "$rootDir/gradle/scripts/repositories.gradle" +apply from: "$rootDir/gradle/scripts/jars.gradle" +apply from: "$rootDir/dependencies.gradle" +apply from: "$rootDir/gradle/scripts/resources.gradle" +apply from: "$rootDir/gradle/scripts/publishing.gradle" +apply from: "$rootDir/gradle/scripts/spotless.gradle" + afterEvaluate { tasks.withType(ShadowJar).configureEach { + configurations = [project.configurations.includedLibrary] minimize() relocate("org.jgrapht", "${maven_group}.repack.org.jgrapht") relocate("org.jheaps", "${maven_group}.repack.org.jheaps") @@ -33,14 +42,6 @@ afterEvaluate { } } -apply from: "$rootDir/gradle/scripts/moddevgradle.gradle" -apply from: "$rootDir/gradle/scripts/repositories.gradle" -apply from: "$rootDir/dependencies.gradle" -apply from: "$rootDir/gradle/scripts/resources.gradle" -apply from: "$rootDir/gradle/scripts/jars.gradle" -apply from: "$rootDir/gradle/scripts/publishing.gradle" -apply from: "$rootDir/gradle/scripts/spotless.gradle" - // Include resources generated by data generators. sourceSets.main.resources { srcDir 'src/generated/resources' } diff --git a/dependencies.gradle b/dependencies.gradle index 41d9ce5908..d6c2b9c5ed 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -4,7 +4,7 @@ dependencies { // Shadowed Dependencies // Packages that aren't mods, and thus need to be included in the release files. - api(shadow('org.jgrapht:jgrapht-core:1.5.2')) // JGraphT 1.5.2 + api(includedLibrary('org.jgrapht:jgrapht-core:1.5.2')) // JGraphT 1.5.2 additionalRuntimeClasspath('org.jgrapht:jgrapht-core:1.5.2') // LDLib diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index ab35d587ab..f6c0427787 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -1,12 +1,17 @@ +configurations { + includedLibrary { + canBeConsumed = false + canBeResolved = true + } +} + shadowJar { from jar.outputs - configurations = [project.configurations.shadow] archiveClassifier = "dev" } slimJar { from sourceSets.main.output - configurations = [project.configurations.shadow] archiveClassifier = "dev-slim" } From 80d63a2f2ed9aa02bb01fd8e581523fcff3fb9e4 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 15:08:13 +0300 Subject: [PATCH 53/70] fix laser redirector pipe model --- .../gregtechceu/gtceu/common/data/GTModels.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java index 989b19cfcc..0887bdfac8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTModels.java @@ -447,6 +447,20 @@ public static void registerPipeModels() { createPipeBlockState(blockId, blockModelId, block); } + { + JsonObject json = new JsonObject(); + json.addProperty("loader", "gtceu:pipe"); + String modelId = LaserStructure.MIRROR.getModel().getLoc().toString(); + json.addProperty("model_id", modelId); + + LaserPipeBlock block = GTBlocks.LASER_REFLECTOR_PIPE.get(); + ResourceLocation blockId = GTBlocks.LASER_REFLECTOR_PIPE.getId(); + ResourceLocation blockModelId = blockId.withPrefix("block/"); + GTDynamicResourcePack.addBlockModel(blockModelId, json); + GTDynamicResourcePack.addItemModel(blockId, json); + + createPipeBlockState(blockId, blockModelId, block); + } { JsonObject json = new JsonObject(); json.addProperty("loader", "gtceu:pipe"); From bf838aea7b613e7c9998549924338483567fd20a Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 15:12:07 +0300 Subject: [PATCH 54/70] attempt 4 --- gradle/scripts/jars.gradle | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index f6c0427787..6de0d095e2 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -7,11 +7,13 @@ configurations { shadowJar { from jar.outputs + configurations = [project.configurations.includedLibrary] archiveClassifier = "dev" } slimJar { from sourceSets.main.output + configurations = [project.configurations.includedLibrary] archiveClassifier = "dev-slim" } From 051050768efbe0eb0ffddc8846bf6e6a59d394c1 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 15:20:11 +0300 Subject: [PATCH 55/70] attempt 5 --- .github/workflows/auto-build.yml | 4 ++++ .github/workflows/auto-publish.yml | 4 ++++ .github/workflows/build-on-push.yml | 4 ++++ gradle/scripts/publishing.gradle | 1 + 4 files changed, 13 insertions(+) diff --git a/.github/workflows/auto-build.yml b/.github/workflows/auto-build.yml index fbd05675b6..ba7501a95c 100644 --- a/.github/workflows/auto-build.yml +++ b/.github/workflows/auto-build.yml @@ -26,6 +26,10 @@ jobs: - name: Setup Build uses: ./.github/actions/build_setup + # run gradlew jar to set up necessary files before shadow can break them in the Build step + - name: Setup Build part 2 + run: ./gradlew jar --build-cache + - name: Build run: ./gradlew build --build-cache diff --git a/.github/workflows/auto-publish.yml b/.github/workflows/auto-publish.yml index d531bc1dcd..bb97683f09 100644 --- a/.github/workflows/auto-publish.yml +++ b/.github/workflows/auto-publish.yml @@ -39,6 +39,10 @@ jobs: - name: Setup Build uses: ./.github/actions/build_setup + # run gradlew jar to set up necessary files before shadow can break them in the Build step + - name: Setup Build part 2 + run: ./gradlew jar --build-cache + - name: Build run: ./gradlew build --build-cache diff --git a/.github/workflows/build-on-push.yml b/.github/workflows/build-on-push.yml index cde92e010b..eb0780dbf5 100644 --- a/.github/workflows/build-on-push.yml +++ b/.github/workflows/build-on-push.yml @@ -30,6 +30,10 @@ jobs: if: steps.filter.outputs.code == 'true' uses: ./.github/actions/build_setup + # run gradlew jar to set up necessary files before shadow can break them in the Build step + - name: Setup Build part 2 + run: ./gradlew jar --build-cache + - name: Build if: steps.filter.outputs.code == 'true' run: ./gradlew assemble --build-cache diff --git a/gradle/scripts/publishing.gradle b/gradle/scripts/publishing.gradle index 716d04e122..61db621b85 100644 --- a/gradle/scripts/publishing.gradle +++ b/gradle/scripts/publishing.gradle @@ -1,4 +1,5 @@ artifacts { + archives tasks.shadowJar archives tasks.reobfShadowJar archives tasks.reobfSlimJar archives tasks.sourcesJar From 635d51221b3f50a531d60d61b1e515e57fb5e399 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 15:24:47 +0300 Subject: [PATCH 56/70] yippee it works --- .github/actions/build_setup/action.yml | 5 +++++ .github/workflows/auto-build.yml | 4 ---- .github/workflows/auto-publish.yml | 4 ---- .github/workflows/build-on-push.yml | 4 ---- 4 files changed, 5 insertions(+), 12 deletions(-) diff --git a/.github/actions/build_setup/action.yml b/.github/actions/build_setup/action.yml index 40e38cd7df..4de2577cfa 100644 --- a/.github/actions/build_setup/action.yml +++ b/.github/actions/build_setup/action.yml @@ -38,3 +38,8 @@ runs: notifications jdks wrapper + + # run gradlew jar to set up necessary files before shadow can break them in the Build step + - name: Pre-build + shell: bash + run: ./gradlew jar --build-cache diff --git a/.github/workflows/auto-build.yml b/.github/workflows/auto-build.yml index ba7501a95c..fbd05675b6 100644 --- a/.github/workflows/auto-build.yml +++ b/.github/workflows/auto-build.yml @@ -26,10 +26,6 @@ jobs: - name: Setup Build uses: ./.github/actions/build_setup - # run gradlew jar to set up necessary files before shadow can break them in the Build step - - name: Setup Build part 2 - run: ./gradlew jar --build-cache - - name: Build run: ./gradlew build --build-cache diff --git a/.github/workflows/auto-publish.yml b/.github/workflows/auto-publish.yml index bb97683f09..d531bc1dcd 100644 --- a/.github/workflows/auto-publish.yml +++ b/.github/workflows/auto-publish.yml @@ -39,10 +39,6 @@ jobs: - name: Setup Build uses: ./.github/actions/build_setup - # run gradlew jar to set up necessary files before shadow can break them in the Build step - - name: Setup Build part 2 - run: ./gradlew jar --build-cache - - name: Build run: ./gradlew build --build-cache diff --git a/.github/workflows/build-on-push.yml b/.github/workflows/build-on-push.yml index eb0780dbf5..cde92e010b 100644 --- a/.github/workflows/build-on-push.yml +++ b/.github/workflows/build-on-push.yml @@ -30,10 +30,6 @@ jobs: if: steps.filter.outputs.code == 'true' uses: ./.github/actions/build_setup - # run gradlew jar to set up necessary files before shadow can break them in the Build step - - name: Setup Build part 2 - run: ./gradlew jar --build-cache - - name: Build if: steps.filter.outputs.code == 'true' run: ./gradlew assemble --build-cache From 30e68ad585d607aa60b0a06a2b63bc221a90cc1c Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 18:19:57 +0300 Subject: [PATCH 57/70] fix pipe structures not actually being registered --- .../gtceu/api/graphnet/logic/NetLogicRegistry.java | 4 ++-- .../api/graphnet/pipenet/physical/PipeStructureRegistry.java | 4 ++-- .../gtceu/api/graphnet/predicate/NetPredicateRegistry.java | 4 ++-- src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java | 4 ++-- src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java index e6a971e3b1..30b9143639 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/logic/NetLogicRegistry.java @@ -4,7 +4,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; -import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.ModLoader; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; @@ -22,7 +22,7 @@ public final class NetLogicRegistry { static { NetLogicRegistrationEvent event = new NetLogicRegistrationEvent(); - MinecraftForge.EVENT_BUS.post(event); + ModLoader.get().postEvent(event); Set> gather = event.getGather(); NAMES_TO_NETWORK_IDS = HashBiMap.create(gather.size()); REGISTRY = new Int2ObjectArrayMap<>(gather.size()); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java index b5621a1268..4b98f129e4 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/PipeStructureRegistry.java @@ -1,6 +1,6 @@ package com.gregtechceu.gtceu.api.graphnet.pipenet.physical; -import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.ModLoader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.UnmodifiableView; @@ -20,7 +20,7 @@ public final class PipeStructureRegistry { private static Map, Set> fireEvent() { PipeStructureRegistrationEvent event = new PipeStructureRegistrationEvent(); - MinecraftForge.EVENT_BUS.post(event); + ModLoader.get().postEvent(event); return event.getRegistry(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java index 729615c76b..7ee0d99242 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/NetPredicateRegistry.java @@ -4,7 +4,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; -import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.ModLoader; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; @@ -22,7 +22,7 @@ public final class NetPredicateRegistry { static { NetPredicateRegistrationEvent event = new NetPredicateRegistrationEvent(); - MinecraftForge.EVENT_BUS.post(event); + ModLoader.get().postEvent(event); Set> gather = event.getGather(); NAMES_TO_NETWORK_IDS = HashBiMap.create(gather.size()); REGISTRY = new Int2ObjectArrayMap<>(gather.size()); diff --git a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java index 232a7aa8ad..ca9670334a 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java @@ -247,7 +247,7 @@ public void modConstruct(FMLConstructModEvent event) { } @SubscribeEvent - public static void registerPipeStructures(PipeStructureRegistrationEvent event) { + public void registerPipeStructures(PipeStructureRegistrationEvent event) { CableStructure.register(event); MaterialPipeStructure.register(event); LaserStructure.register(event); @@ -256,7 +256,7 @@ public static void registerPipeStructures(PipeStructureRegistrationEvent event) } @SubscribeEvent - public static void registerNetLogics(NetLogicRegistrationEvent event) { + public void registerNetLogics(NetLogicRegistrationEvent event) { event.accept(ChannelCountLogic.TYPE); event.accept(EnergyFlowLogic.TYPE); event.accept(FluidFlowLogic.TYPE); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java index f6b9cf7bd3..10245bc952 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTBlocks.java @@ -403,7 +403,7 @@ private static void registerMaterialPipeBlock(Material material, MaterialPipeStr MATERIAL_PIPE_BLOCKS_BUILDER.put(pipeType.prefix(), material, entry); } - // Optical Pipe Blocks + // Duct Pipe Blocks private static void generateDuctPipeBlocks() { GTCEu.LOGGER.debug("Generating GTCEu Duct Pipe Blocks..."); for (var structure : PipeStructureRegistry.getStructures(DuctStructure.class)) { From 0ec799f6df18208066bd579e7fd68e5386d399fc Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 18:49:18 +0300 Subject: [PATCH 58/70] fix laser bender grid overlay not working correctly --- .../client/renderer/BlockHighLightRenderer.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java index 8e9b8fb5ef..a01d1cabde 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighLightRenderer.java @@ -143,19 +143,19 @@ public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, } // draw pipe connection grid highlight - var pipeStructure = held.getItem() instanceof PipeBlockItem pipeBlockItem ? - pipeBlockItem.getBlock().getStructure() : - null; - if (pipeStructure != null && blockEntity instanceof PipeBlockEntity pipeBlockEntity && - pipeBlockEntity.getStructure() == pipeStructure) { + var pipeBlock = held.getItem() instanceof PipeBlockItem pipeBlockItem ? + pipeBlockItem.getBlock() : null; + var pipeStructure = pipeBlock == null ? null : pipeBlock.getStructure(); + if (pipeStructure != null && pipeBlock.hasPipeCollisionChangingItem(level, blockPos, player) && + blockEntity instanceof PipeBlockEntity pipeBlockEntity) { Vec3 pos = camera.getPosition(); poseStack.pushPose(); poseStack.translate(-pos.x, -pos.y, -pos.z); var buffer = multiBufferSource.getBuffer(RenderType.lines()); RenderSystem.lineWidth(3); - drawGridOverlays(poseStack, buffer, target, side -> level.isEmptyBlock(blockPos.relative(side)) ? - pipeStructure.getPipeTexture(true) : null); + drawGridOverlays(poseStack, buffer, target, side -> level.isEmptyBlock(blockPos.relative(side)) && + pipeBlockEntity.canConnectTo(side) ? pipeStructure.getPipeTexture(true) : null); poseStack.popPose(); } From 69dee7bede19fd97f2c9246cfa7ae702ded3d14c Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Thu, 26 Sep 2024 19:07:28 +0300 Subject: [PATCH 59/70] fix laser bender texture showing through because the texture wasn't full block --- .../textures/block/pipe/pipe_laser_side.png | Bin 377 -> 5816 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/src/main/resources/assets/gtceu/textures/block/pipe/pipe_laser_side.png b/src/main/resources/assets/gtceu/textures/block/pipe/pipe_laser_side.png index b371bdb0b021efc17533bd2bb2d82a564836710c..dd3da3493cfeb05418ed06c546948b529c6e5a81 100644 GIT binary patch literal 5816 zcmeHLdsGuw8Xqg7Vi8b$q1H6MwUbOKmuYA0R^iflgxxf@-i7n0Bc>fvW4o3 z)~YSq;tQXkRHaI-^#O_^f+&bfL8_uf1zp72DrN5s1cQyc>p9#1yywi!z2D<^zx(^X zdrxjY4GodGx_G%j5ab#Z=pP2Y?$p!E8N5d{w_yMTTJ(hS6kDX|x1`Of(V< z!m3e0koCraNKMjy(Yr5l!izoDeqVHs6a7QePcdtz-05+p&z6w8t~(BSNGC)VaWj8! z`dZp{(|t~GMUR%U=dLNMy{Au;(*GP{NpcXOdI?2ghC}_Xu#Jg1)Ep&cQ+N3C;BrM z4c~iW7@2jU>Q>w&$zFnR<+zP{{_Tmw{qy5yJGTha4`gqx{-?b9wEvSIm$n_5b9gnX z99WbT`ml0GNJUc5TL~-gWp02joyn5*9e-n~G$VC?N#G~BcXa1Aqq$SF3%}?yRzF|% z7218p8#t*#M z=f>_QrPk4p22Tiy8FPJB@i!}ZHBRakvz-s^k3au)%mDQBjKvk`-37*mZNW9x`&)jU z{4Clt961$cJeA_kKfCto?%7$*)AJvw^76O; z)Pz+^8pn_PDEAWU`LNvjP2uSZmj>D6(Vp<39Tx`diO|Jgs|-C-_@!6afgy{I9;=_H zzM%-tS`=K7)!hA>bO<{HG_u+BXSGh;7Y`FiW zZq~sG8PJaVUk+$Y_4S=Mcm6HEN$d8gBO7zb?J-T{`q~My1;^bsBv(9~e&kACrjO@W z`wp%@zPTcAhJ4#@^Ucz_9K(Wzu*55A=+gt1>zSbi+@t|R@T_Z!Q$>%ej#kf?zE`&j zQMN?B|3h4B^sbBLEg>qOGfOu~KmS(n{6S{JE~Ic-q5I5*tbd$K_TDwML25o+-}`7& zOC{XvJxSZUX_jv?gGDEo1$3{R6jhbualUR4S?2WA@?CL+?r}j{_vR}jvI^GaHToXD zdT;8cvC~>r9|k@cnZK*~gfxx+o^afeajq91oT_*ltR@x7y&tY5LvE)oPAV?VE1q(u zE;YxgK{%&n=c78~+KU;cpQEnASD&qk!pkZYlI@#^94Hu`sLfFqmLv>c7jlM3^+~Ub zojdNCKjyh_artMfrp^06KUrJR^XkeonRU#j+9?aOnrhm1>>S~|ByHo;wm&`!b{pM* z>Keka=`yd3pxFIcdxYM(UM2X2mMGq_(SJx`0CSns_KL1DvblHqbipNMIjqU)s{{(q}95m&l*Hx2iZ?&&oex| zHoNcE1ef2{`=0HJE;CpvWb>b-!4GaX9o;!e5yzL+FLg=FuKPaZawOb3qE^~k{`aLX zbe@j{m2GgFn`YmyIicYn>;&gmf(D#ZQSupLr9sESaD#$iS#?HmjzN&m6sr+a#t|e# zLBwkG5@u8WNhU*sOPG-YIU+au5o%3fl8FdU3W-oA#VJvoIc2hok5vo+bOebptU9gU zEVfFRG_Dx*DKVSLpiRg)2{TF_%J4Io2nL_UXCZKaRg=JFPIh7Vm~fRi%wO680Y(z0 znk0>4Hrrycuq-^5!4%8ppeV{lxNI&L1{Sb6QBPu4SZ^LlL9}D|6K17JV;D3^D_>&+c306y4O%*f`j5VlUow)ZfT0SN%4BOr$!<_K`yv%?6p zA>O1U0ul&4Ino{iS9bav<4sz6Ik=KdXbBxKHG^3>U8a-;$wNCmC<Jl5Jp_gMH2ypMj?P6_PJ8cZC8=vtq6m(o zut+H6!hBpHfJJ*g)hX)J26$+S- zfV84KB?fy7ytxXVkcaYx96N}aCJm@cOluz%1%(4BJ|W;E91#jDxLg$GV;~SJ23VvJ zc!NkVA;uHXP`FYoHJEf5NT)`J#S(0zK9*Kcgo}McgCtBYt37a95~{^W6>tE1K%>VE z7V}Hv2#t;iCozgoj*u(ldGk<|D-fYVp6I2~9KvJN~y;5u>?3jIttb%*ElE!F2Ug|lsF$2VJIjDE~0`l9)iILA{3z_6hlO)sw=wL zpdu}piSUgDJOZvjfzn(t#&x7>d{=vmnxOIkD1#9cen}aZ$?jMzn>sOUtMy_3i4Pyz z!0w0ve(f@Fbb*tQ-FXyt@I@Uue_`v$!(TW9fPOp48}a*=uD5i(5d&{z{IiWOY#OhbeGeIrC3-Q1m;o_AYjNu)6-9QzinmnIf%b_*@#Bc`FN|fWghRlW^OlPPSCp1UH=~0;4k8nL+)_2wDv^7jn6~7Akb| zg%~f|Wwy6N4s6Q**%kD~VCK@2GKZOXEdVuRCt)D$*QJpr(H1T}wS$)}d>s=s-+If!JPx#1ZP1_K>z@;j|==^1(RJ87k>c`Nkly^Os;v4?Zw}F+RWu3LJ3>F$M`qaj*bLGYG(J1<8Q`OdbYcmN0@s7%Bz^ zAix6den$4f#q*aL+`U}Ed}ME61R@L&3QTw)f|4UT*syZ>e+fwmhGQ&_V7}F# z{a{yR6cjLm1&{#FFaX&I3NTopp}P Date: Fri, 27 Sep 2024 09:17:50 +0300 Subject: [PATCH 60/70] try to fix shadow using dependencies from runtimeClasspath --- gradle/scripts/jars.gradle | 1 - .../pipenet/physical/tile/PipeBlockEntity.java | 10 ++++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 6de0d095e2..3545343ed1 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -6,7 +6,6 @@ configurations { } shadowJar { - from jar.outputs configurations = [project.configurations.includedLibrary] archiveClassifier = "dev" } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 4b255fc0c2..474cc8f505 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -529,7 +529,6 @@ protected void initialize() { this.netLogicDatas.clear(); this.capabilities.clear(); this.netCapabilities.clear(); - boolean firstNode = true; for (WorldPipeNetNode node : PipeBlock.getNodesForTile(this)) { this.addCapabilities(node.getNet().getNewCapabilityObjects(node)); this.netCapabilities.put(node, new PipeCapabilityWrapper(this, node)); @@ -542,9 +541,10 @@ protected void initialize() { for (var entry : node.getData().getEntries()) { node.getData().markLogicEntryAsUpdated(entry, true); } - if (firstNode) { - firstNode = false; - this.temperatureLogic = node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); + if (this.temperatureLogic == null) { + TemperatureLogic candidate = node.getData().getLogicEntryNullable(TemperatureLogic.TYPE); + if (candidate != null) + updateTemperatureLogic(candidate); } } if (this.legacy) { @@ -603,7 +603,9 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { // particle // public void updateTemperatureLogic(@NotNull TemperatureLogic logic) { + this.temperatureLogic = logic; if (overheatParticle == null || !overheatParticle.isAlive()) { + // TODO figure out if this can crash if playing on a server long tick = Platform.getMinecraftServer().getTickCount(); int temp = logic.getTemperature(tick); if (temp > GTOverheatParticle.TEMPERATURE_CUTOFF) { From 3a8c495a6220bdb8e7cfe3155102fe21c73e1dd3 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 29 Sep 2024 13:45:55 +0300 Subject: [PATCH 61/70] fix moving when a server closes crashing the client --- src/main/java/com/gregtechceu/gtceu/utils/input/KeyBind.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/gregtechceu/gtceu/utils/input/KeyBind.java b/src/main/java/com/gregtechceu/gtceu/utils/input/KeyBind.java index 44b48c90d4..aab85ef715 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/input/KeyBind.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/input/KeyBind.java @@ -66,7 +66,7 @@ public static void onInputEvent(InputEvent.Key event) { updating.add(keybind); } } - if (!updating.isEmpty()) { + if (!updating.isEmpty() && Minecraft.getInstance().getConnection() != null) { GTNetwork.NETWORK.sendToServer(new CPacketKeysPressed(updating)); } } From 1e6a6b07f4ddc5be6a95135cfe9b005da6efac08 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 29 Sep 2024 15:22:31 +0300 Subject: [PATCH 62/70] fix server --- .../gtceu/api/cover/CoverDefinition.java | 6 +- .../pipenet/logic/TemperatureLogic.java | 4 +- .../pipenet/physical/block/PipeBlock.java | 9 +- .../physical/tile/PipeBlockEntity.java | 8 +- .../traverse/AbstractTraverseData.java | 38 ++--- .../gregtechceu/gtceu/client/ClientProxy.java | 15 +- .../forge/ForgeClientEventListener.java | 3 + .../client/particle/GTOverheatParticle.java | 3 +- .../gtceu/client/particle/GTParticle.java | 2 +- .../client/particle/GTParticleManager.java | 1 - .../renderer/cover/ConveyorCoverRenderer.java | 73 --------- .../renderer/cover/FacadeCoverRenderer.java | 44 +----- .../cover/FluidRegulatorCoverRenderer.java | 65 -------- .../client/renderer/cover/ICoverRenderer.java | 47 ------ .../renderer/cover/ICoverableRenderer.java | 7 +- .../renderer/cover/PumpCoverRenderer.java | 65 -------- .../renderer/cover/RobotArmCoverRenderer.java | 65 -------- .../renderer/cover/SimpleCoverRenderer.java | 66 -------- .../machine/QuantumChestRenderer.java | 6 +- .../renderer/pipe/AbstractPipeModel.java | 4 +- .../renderer/pipe/ActivablePipeModel.java | 2 +- .../gtceu/client/renderer/pipe/PipeModel.java | 1 - .../renderer/pipe/PipeModelRedirector.java | 3 + .../renderer/pipe/PipeModelRegistry.java | 3 + .../AdvancedActivityDetectorCover.java | 9 ++ .../detector/AdvancedEnergyDetectorCover.java | 8 + .../detector/AdvancedFluidDetectorCover.java | 8 + .../detector/AdvancedItemDetectorCover.java | 8 + .../cover/detector/EnergyDetectorCover.java | 3 +- .../cover/detector/FluidDetectorCover.java | 3 +- .../cover/detector/ItemDetectorCover.java | 3 +- .../voiding/AdvancedItemVoidingCover.java | 9 ++ .../cover/voiding/ItemVoidingCover.java | 14 ++ .../gtceu/common/data/GTCovers.java | 144 +++++------------- .../gtceu/common/network/GTNetwork.java | 2 + .../network/packets/SPacketSyncTickCount.java | 33 ++++ .../pipelike/block/cable/CableBlock.java | 21 +++ .../pipelike/block/cable/CableStructure.java | 29 ++-- .../pipelike/block/duct/DuctStructure.java | 3 + .../pipelike/block/laser/LaserStructure.java | 13 +- .../block/optical/OpticalStructure.java | 11 +- .../block/pipe/MaterialPipeStructure.java | 37 +++-- .../block/pipe/pipe_optical_side_overlay.png | Bin 0 -> 113 bytes .../pipe/pipe_optical_side_overlay_active.png | Bin 0 -> 197 bytes ...ipe_optical_side_overlay_active.png.mcmeta | 5 + 45 files changed, 284 insertions(+), 619 deletions(-) delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ConveyorCoverRenderer.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FluidRegulatorCoverRenderer.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverRenderer.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/cover/PumpCoverRenderer.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/cover/RobotArmCoverRenderer.java delete mode 100644 src/main/java/com/gregtechceu/gtceu/client/renderer/cover/SimpleCoverRenderer.java create mode 100644 src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java create mode 100644 src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay.png create mode 100644 src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay_active.png create mode 100644 src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay_active.png.mcmeta diff --git a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java index 90b76e6f13..c895cfcc71 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java +++ b/src/main/java/com/gregtechceu/gtceu/api/cover/CoverDefinition.java @@ -1,7 +1,6 @@ package com.gregtechceu.gtceu.api.cover; import com.gregtechceu.gtceu.api.capability.ICoverable; -import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; @@ -23,13 +22,10 @@ public interface TieredCoverBehaviourProvider { @Getter private final ResourceLocation id; private final CoverBehaviourProvider behaviorCreator; - @Getter - private final CoverRenderer coverRenderer; - public CoverDefinition(ResourceLocation id, CoverBehaviourProvider behaviorCreator, CoverRenderer coverRenderer) { + public CoverDefinition(ResourceLocation id, CoverBehaviourProvider behaviorCreator) { this.behaviorCreator = behaviorCreator; this.id = id; - this.coverRenderer = coverRenderer; } public CoverBehavior createCoverBehavior(ICoverable metaBlockEntity, Direction side) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index 9e47e677b0..568481c783 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -12,10 +12,12 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IFreezable; import com.gregtechceu.gtceu.api.graphnet.traverse.util.CompleteLossOperator; import com.gregtechceu.gtceu.api.graphnet.traverse.util.MultLossOperator; +import com.gregtechceu.gtceu.client.ClientProxy; import com.gregtechceu.gtceu.client.particle.GTOverheatParticle; import com.lowdragmc.lowdraglib.Platform; +import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; @@ -276,7 +278,7 @@ public void encode(FriendlyByteBuf buf, boolean fullChange) { @Override public void decode(FriendlyByteBuf buf, boolean fullChange) { - this.lastRestorationTick = Platform.getMinecraftServer().getTickCount(); + this.lastRestorationTick = ClientProxy.getServerTickCount(); this.energy = buf.readFloat(); if (fullChange) { this.temperatureMaximum = buf.readVarInt(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 696c3413ef..7363cd496e 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -13,6 +13,7 @@ import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeCoverHolder; import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.ToolHelper; +import com.gregtechceu.gtceu.client.ClientProxy; import com.gregtechceu.gtceu.common.data.GTBlockEntities; import com.gregtechceu.gtceu.common.item.CoverPlaceBehavior; import com.gregtechceu.gtceu.config.ConfigHolder; @@ -20,8 +21,10 @@ import com.gregtechceu.gtceu.utils.EntityDamageUtil; import com.gregtechceu.gtceu.utils.GTUtil; +import com.lowdragmc.lowdraglib.LDLib; import com.lowdragmc.lowdraglib.Platform; +import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; @@ -530,10 +533,12 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) { PipeBlockEntity tile = getBlockEntity(level, pos); - if (tile != null) { + if (tile != null && level instanceof Level level1) { TemperatureLogic temperatureLogic = tile.getTemperatureLogic(); int temp = temperatureLogic == null ? 0 : temperatureLogic - .getTemperature(Platform.getMinecraftServer().getTickCount()); + .getTemperature(!level1.isClientSide ? + level1.getServer().getTickCount() : + ClientProxy.getServerTickCount()); // max light at 5000 K // min light at 500 K if (temp >= 5000) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 474cc8f505..58fb110afb 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -24,6 +24,7 @@ import com.gregtechceu.gtceu.api.item.tool.GTToolType; import com.gregtechceu.gtceu.api.item.tool.IToolGridHighLight; import com.gregtechceu.gtceu.api.machine.TickableSubscription; +import com.gregtechceu.gtceu.client.ClientProxy; import com.gregtechceu.gtceu.client.particle.GTOverheatParticle; import com.gregtechceu.gtceu.client.particle.GTParticleManager; import com.gregtechceu.gtceu.client.renderer.pipe.AbstractPipeModel; @@ -44,6 +45,7 @@ import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; +import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleOptions; @@ -145,7 +147,6 @@ public class PipeBlockEntity extends NeighborCacheBlockEntity @Getter @Nullable private TemperatureLogic temperatureLogic; - @OnlyIn(Dist.CLIENT) @Nullable private GTOverheatParticle overheatParticle; @@ -605,8 +606,9 @@ public void receiveCustomData(int discriminator, @NotNull FriendlyByteBuf buf) { public void updateTemperatureLogic(@NotNull TemperatureLogic logic) { this.temperatureLogic = logic; if (overheatParticle == null || !overheatParticle.isAlive()) { - // TODO figure out if this can crash if playing on a server - long tick = Platform.getMinecraftServer().getTickCount(); + long tick = this.level.isClientSide ? + ClientProxy.getServerTickCount() : + Platform.getMinecraftServer().getTickCount();; int temp = logic.getTemperature(tick); if (temp > GTOverheatParticle.TEMPERATURE_CUTOFF) { IPipeStructure structure = this.getStructure(); diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java index b959c79276..079f73dc03 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/traverse/AbstractTraverseData.java @@ -6,44 +6,30 @@ import com.gregtechceu.gtceu.api.graphnet.path.INetPath; import com.gregtechceu.gtceu.api.graphnet.predicate.test.IPredicateTestObject; +import lombok.Getter; import org.jetbrains.annotations.Nullable; public abstract class AbstractTraverseData> implements ITraverseData { - private final IGraphNet net; + @Getter + private final IGraphNet graphNet; + @Getter private final IPredicateTestObject testObject; - private final SimulatorKey simulator; + @Nullable + @Getter + private final SimulatorKey simulatorKey; + @Getter private final long queryTick; - public AbstractTraverseData(IGraphNet net, IPredicateTestObject testObject, SimulatorKey simulator, + public AbstractTraverseData(IGraphNet graphNet, IPredicateTestObject testObject, SimulatorKey simulatorKey, long queryTick) { - this.net = net; + this.graphNet = graphNet; this.testObject = testObject; - this.simulator = simulator; + this.simulatorKey = simulatorKey; this.queryTick = queryTick; } - @Override - public IGraphNet getGraphNet() { - return net; - } - - @Override - public IPredicateTestObject getTestObject() { - return testObject; - } - - @Override - public @Nullable SimulatorKey getSimulatorKey() { - return simulator; - } - public boolean simulating() { - return simulator != null; - } - - @Override - public long getQueryTick() { - return queryTick; + return simulatorKey != null; } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index fc3e8178e5..fbfc18bd43 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -21,6 +21,8 @@ import com.lowdragmc.lowdraglib.gui.compass.CompassManager; import com.lowdragmc.lowdraglib.gui.compass.component.RecipeComponent; +import lombok.Getter; +import lombok.Setter; import net.minecraft.client.model.BoatModel; import net.minecraft.client.model.ChestBoatModel; import net.minecraft.client.renderer.blockentity.HangingSignRenderer; @@ -31,6 +33,7 @@ import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.event.*; +import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import com.google.common.collect.BiMap; @@ -41,24 +44,28 @@ * @date 2023/7/30 * @implNote ClientProxy */ -@OnlyIn(Dist.CLIENT) public class ClientProxy extends CommonProxy { public static final BiMap CLIENT_ORE_VEINS = HashBiMap.create(); public static final BiMap CLIENT_FLUID_VEINS = HashBiMap.create(); public static final BiMap CLIENT_BEDROCK_ORE_VEINS = HashBiMap.create(); + @Getter @Setter + private static long serverTickCount = -1L; + public ClientProxy() { super(); init(); } + @OnlyIn(Dist.CLIENT) public static void init() { RecipeComponent.registerRecipeViewCreator(new GTRecipeViewCreator()); CompassManager.INSTANCE.registerUIConfig(GTCEu.MOD_ID, new GTCompassUIConfig()); CompassManager.INSTANCE.registerAction("multiblock", MultiblockAction::new); } + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onRegisterEntityRenderers(EntityRenderersEvent.RegisterRenderers event) { event.registerEntityRenderer(GTEntityTypes.DYNAMITE.get(), ThrownItemRenderer::new); @@ -78,32 +85,38 @@ public void onRegisterEntityRenderers(EntityRenderersEvent.RegisterRenderers eve } } + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void registerKeyBindings(RegisterKeyMappingsEvent event) { KeyBind.onRegisterKeyBinds(event); } + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onRegisterGuiOverlays(RegisterGuiOverlaysEvent event) { event.registerAboveAll("hud", new HudGuiOverlay()); } + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onRegisterParticleProviders(RegisterParticleProvidersEvent event) { event.registerSpriteSet(GTParticleTypes.HAZARD_PARTICLE.get(), HazardParticle.Provider::new); } + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void modifyModels(ModelEvent.ModifyBakingResult event) { AbstractPipeModel.invalidateCaches(); PipeModelRegistry.registerModels(event.getModels()::put); } + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void registerAdditionalModels(ModelEvent.RegisterAdditional event) { PipeModelRegistry.registerModels((id, $) -> event.register(id)); } + @OnlyIn(Dist.CLIENT) @SubscribeEvent public void modelRegistry(final ModelEvent.RegisterGeometryLoaders e) { e.register("pipe", UnbakedPipeModel.Loader.INSTANCE); diff --git a/src/main/java/com/gregtechceu/gtceu/client/forge/ForgeClientEventListener.java b/src/main/java/com/gregtechceu/gtceu/client/forge/ForgeClientEventListener.java index 1a7d80450b..996bfcf896 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/forge/ForgeClientEventListener.java +++ b/src/main/java/com/gregtechceu/gtceu/client/forge/ForgeClientEventListener.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; +import com.gregtechceu.gtceu.client.ClientProxy; import com.gregtechceu.gtceu.client.EnvironmentalHazardClientHandler; import com.gregtechceu.gtceu.client.TooltipsHandler; import com.gregtechceu.gtceu.client.renderer.BlockHighLightRenderer; @@ -53,6 +54,8 @@ public static void onClientTickEvent(TickEvent.ClientTickEvent event) { MultiblockInWorldPreviewRenderer.onClientTick(); EnvironmentalHazardClientHandler.INSTANCE.onClientTick(); GTValues.CLIENT_TIME++; + } else { + ClientProxy.setServerTickCount(ClientProxy.getServerTickCount() + 1); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java index 79a497dafc..8eb68cc6aa 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java @@ -4,6 +4,7 @@ import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.graphnet.pipenet.logic.TemperatureLogic; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; +import com.gregtechceu.gtceu.client.ClientProxy; import com.gregtechceu.gtceu.client.renderer.GTRenderTypes; import com.gregtechceu.gtceu.client.renderer.IRenderSetup; import com.gregtechceu.gtceu.client.util.BloomUtils; @@ -171,7 +172,7 @@ public GTOverheatParticle(@NotNull PipeBlockEntity tileEntity, @NotNull Temperat } private int getTemperature() { - long tick = Minecraft.getInstance().levelRenderer.getTicks(); + long tick = ClientProxy.getServerTickCount(); return temperatureLogic.getTemperature(tick); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java index 356a350c6b..ece35c29e8 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticle.java @@ -18,7 +18,6 @@ * GTParticle instances are managed by {@link GTParticleManager}. GTParticle instances with same {@link IRenderSetup}s * will be drawn together as a batch. */ -@OnlyIn(Dist.CLIENT) public abstract class GTParticle { public double posX; @@ -105,6 +104,7 @@ protected void onExpired() {} * @param buffer buffer builder * @param context render context */ + @OnlyIn(Dist.CLIENT) public void renderParticle(@NotNull PoseStack poseStack, @NotNull BufferBuilder buffer, @NotNull EffectRenderContext context) {} diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java index 5e29267d84..1f4e997694 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java @@ -33,7 +33,6 @@ /** * Singleton class responsible for managing, updating and rendering {@link GTParticle} instances. */ -@OnlyIn(Dist.CLIENT) @Mod.EventBusSubscriber(value = Dist.CLIENT, modid = GTCEu.MOD_ID) public class GTParticleManager { diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ConveyorCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ConveyorCoverRenderer.java deleted file mode 100644 index 8cbfc2a8f4..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ConveyorCoverRenderer.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.cover; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.recipe.IO; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.client.util.StaticFaceBakery; -import com.gregtechceu.gtceu.common.cover.ConveyorCover; - -import com.lowdragmc.lowdraglib.LDLib; -import com.lowdragmc.lowdraglib.client.model.ModelFactory; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.function.Consumer; - -/** - * @author KilaBash - * @date 2023/3/12 - * @implNote ConveyorCoverRenderer - */ -public class ConveyorCoverRenderer implements ICoverRenderer { - - public final static ConveyorCoverRenderer INSTANCE = new ConveyorCoverRenderer(); - public final static ResourceLocation CONVEYOR_OVERLAY = GTCEu.id("block/cover/overlay_conveyor"); - public final static ResourceLocation CONVEYOR_OVERLAY_OUT = GTCEu.id("block/cover/overlay_conveyor_emissive"); - public final static ResourceLocation CONVEYOR_OVERLAY_IN = GTCEu - .id("block/cover/overlay_conveyor_inverted_emissive"); - - protected ConveyorCoverRenderer() { - if (LDLib.isClient()) { - registerEvent(); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void renderCover(List quads, @Nullable Direction side, RandomSource rand, - @NotNull CoverBehavior coverBehavior, @Nullable Direction modelFacing, BlockPos pos, - BlockAndTintGetter level, ModelState modelState) { - if (side == coverBehavior.attachedSide && coverBehavior instanceof ConveyorCover conveyor && - modelFacing != null) { - quads.add( - StaticFaceBakery.bakeFace(modelFacing, ModelFactory.getBlockSprite(CONVEYOR_OVERLAY), modelState)); - quads.add(StaticFaceBakery.bakeFace(modelFacing, - ModelFactory - .getBlockSprite(conveyor.getIo() == IO.OUT ? CONVEYOR_OVERLAY_OUT : CONVEYOR_OVERLAY_IN), - modelState, -101, 15)); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void onPrepareTextureAtlas(ResourceLocation atlasName, Consumer register) { - if (atlasName.equals(TextureAtlas.LOCATION_BLOCKS)) { - register.accept(CONVEYOR_OVERLAY); - register.accept(CONVEYOR_OVERLAY_IN); - register.accept(CONVEYOR_OVERLAY_OUT); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java index 547f9f4785..831513e450 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FacadeCoverRenderer.java @@ -1,16 +1,15 @@ package com.gregtechceu.gtceu.client.renderer.cover; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; import com.gregtechceu.gtceu.client.model.ModelUtil; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; -import com.gregtechceu.gtceu.common.cover.FacadeCover; import com.gregtechceu.gtceu.common.item.FacadeItemBehaviour; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.client.bakedpipeline.FaceQuad; import com.lowdragmc.lowdraglib.client.model.ModelFactory; +import com.lowdragmc.lowdraglib.client.renderer.IRenderer; import com.lowdragmc.lowdraglib.utils.FacadeBlockAndTintGetter; import net.minecraft.client.Minecraft; @@ -19,27 +18,22 @@ import net.minecraft.client.renderer.block.BlockRenderDispatcher; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelState; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import com.mojang.blaze3d.vertex.PoseStack; -import org.jetbrains.annotations.NotNull; import org.joml.AxisAngle4d; import org.joml.Quaternionf; import java.util.LinkedList; -import java.util.List; /** * @author KilaBash @@ -48,7 +42,7 @@ * It can only be used for item. * call it in other renderer to render a facade cover. */ -public class FacadeCoverRenderer implements ICoverRenderer { +public class FacadeCoverRenderer implements IRenderer { public final static FacadeCoverRenderer INSTANCE = new FacadeCoverRenderer(); @@ -110,40 +104,6 @@ public void renderItem(ItemStack stack, ItemDisplayContext transformType, boolea } } - @Override - @OnlyIn(Dist.CLIENT) - public void renderCover(List quads, Direction side, RandomSource rand, - @NotNull CoverBehavior coverBehavior, Direction modelFacing, BlockPos pos, - BlockAndTintGetter level, ModelState modelState) { - if (coverBehavior instanceof FacadeCover facadeCover) { - var state = facadeCover.getFacadeState(); - if (state.getRenderShape() == RenderShape.MODEL) { - BlockRenderDispatcher brd = Minecraft.getInstance().getBlockRenderer(); - BakedModel model = brd.getBlockModel(state); - if (side == coverBehavior.attachedSide) { - quads.addAll(ModelUtil.getBakedModelQuads(model, level, pos, state, side, rand)); - } else if (side == null && coverBehavior.coverHolder.shouldRenderBackSide()) { - var normal = coverBehavior.attachedSide.getNormal(); - var cube = new AABB( - normal.getX() == 0 ? 0 : normal.getX() > 0 ? 1 : 0, - normal.getY() == 0 ? 0 : normal.getY() > 0 ? 1 : 0, - normal.getZ() == 0 ? 0 : normal.getZ() > 0 ? 1 : 0, - normal.getX() == 0 ? 1 : normal.getX() > 0 ? 1 : 0, - normal.getY() == 0 ? 1 : normal.getY() > 0 ? 1 : 0, - normal.getZ() == 0 ? 1 : normal.getZ() > 0 ? 1 : 0); - for (BakedQuad quad : ModelUtil.getBakedModelQuads(model, level, pos, state, - coverBehavior.attachedSide, rand)) { - quads.add(FaceQuad.builder(coverBehavior.attachedSide.getOpposite(), quad.getSprite()) - .cube(cube) - .shade(quad.isShade()) - .tintIndex(quad.getTintIndex()) - .bake()); - } - } - } - } - } - public static CoverRenderer createRenderer(final BlockAndTintGetter world, BlockPos pos, final BlockState state) { BlockRenderDispatcher dispatcher = Minecraft.getInstance().getBlockRenderer(); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FluidRegulatorCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FluidRegulatorCoverRenderer.java deleted file mode 100644 index 735d502630..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/FluidRegulatorCoverRenderer.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.cover; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.recipe.IO; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.client.util.StaticFaceBakery; -import com.gregtechceu.gtceu.common.cover.PumpCover; - -import com.lowdragmc.lowdraglib.LDLib; -import com.lowdragmc.lowdraglib.client.model.ModelFactory; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.NotNull; - -import java.util.List; -import java.util.function.Consumer; - -/** - * @author KilaBash - * @date 2023/3/12 - * @implNote ConveyorCoverRenderer - */ -public class FluidRegulatorCoverRenderer implements ICoverRenderer { - - public final static FluidRegulatorCoverRenderer INSTANCE = new FluidRegulatorCoverRenderer(); - public final static ResourceLocation PUMP_OVERLAY_OUT = GTCEu.id("block/cover/overlay_pump"); - public final static ResourceLocation PUMP_OVERLAY_IN = GTCEu.id("block/cover/overlay_pump_inverted"); - - protected FluidRegulatorCoverRenderer() { - if (LDLib.isClient()) { - registerEvent(); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void renderCover(List quads, Direction side, RandomSource rand, - @NotNull CoverBehavior coverBehavior, Direction modelFacing, BlockPos pos, - BlockAndTintGetter level, ModelState modelState) { - if (side == coverBehavior.attachedSide && coverBehavior instanceof PumpCover pump && modelFacing != null) { - quads.add(StaticFaceBakery.bakeFace(modelFacing, - ModelFactory.getBlockSprite(pump.getIo() == IO.OUT ? PUMP_OVERLAY_OUT : PUMP_OVERLAY_IN), - modelState)); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void onPrepareTextureAtlas(ResourceLocation atlasName, Consumer register) { - if (atlasName.equals(TextureAtlas.LOCATION_BLOCKS)) { - register.accept(PUMP_OVERLAY_IN); - register.accept(PUMP_OVERLAY_OUT); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverRenderer.java deleted file mode 100644 index bf67108162..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverRenderer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.cover; - -import com.gregtechceu.gtceu.api.cover.CoverBehavior; - -import com.lowdragmc.lowdraglib.client.renderer.IRenderer; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * @author KilaBash - * @date 2023/2/24 - * @implNote ICoverRenderer - * Do not use it as a block renderer alone. It should be called from {@link ICoverableRenderer} - */ -public interface ICoverRenderer extends IRenderer { - - /** - * Use - * {@link #renderCover(List, Direction, RandomSource, CoverBehavior, Direction, BlockPos, BlockAndTintGetter, ModelState)} - * instead - */ - @Override - @Deprecated - @OnlyIn(Dist.CLIENT) - default List renderModel(BlockAndTintGetter level, BlockPos pos, BlockState state, Direction side, - RandomSource rand) { - return IRenderer.super.renderModel(level, pos, state, side, rand); - } - - @OnlyIn(Dist.CLIENT) - void renderCover(List quads, @Nullable Direction side, RandomSource rand, - @NotNull CoverBehavior coverBehavior, @Nullable Direction modelFacing, BlockPos pos, - BlockAndTintGetter level, ModelState modelState); -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java index 731fe39570..2940530f03 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/ICoverableRenderer.java @@ -3,10 +3,12 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; +import com.gregtechceu.gtceu.client.renderer.pipe.util.ColorData; import com.gregtechceu.gtceu.utils.GTUtil; import com.lowdragmc.lowdraglib.client.bakedpipeline.FaceQuad; import com.lowdragmc.lowdraglib.client.model.ModelFactory; +import com.lowdragmc.lowdraglib.client.model.forge.LDLRendererModel; import com.lowdragmc.lowdraglib.client.renderer.IRenderer; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -23,6 +25,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.EnumSet; import java.util.LinkedList; import java.util.List; @@ -82,7 +85,9 @@ default void renderCovers(List quads, @Nullable Direction side, Rando .cube(cube).cubeUV().tintIndex(-1).bake()); } } - // cover.getCoverRenderer().renderCover(quads, side, rand, cover, modelFacing, pos, level, modelState); + cover.getRenderer().addQuads(quads, face, rand, EnumSet.noneOf(Direction.class), false, + LDLRendererModel.RendererBakedModel.CURRENT_MODEL_DATA.get(), new ColorData(), + LDLRendererModel.RendererBakedModel.CURRENT_RENDER_TYPE.get()); } } } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/PumpCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/PumpCoverRenderer.java deleted file mode 100644 index 02efbe0c6e..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/PumpCoverRenderer.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.cover; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.recipe.IO; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.client.util.StaticFaceBakery; -import com.gregtechceu.gtceu.common.cover.PumpCover; - -import com.lowdragmc.lowdraglib.LDLib; -import com.lowdragmc.lowdraglib.client.model.ModelFactory; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.NotNull; - -import java.util.List; -import java.util.function.Consumer; - -/** - * @author KilaBash - * @date 2023/3/12 - * @implNote ConveyorCoverRenderer - */ -public class PumpCoverRenderer implements ICoverRenderer { - - public final static PumpCoverRenderer INSTANCE = new PumpCoverRenderer(); - public final static ResourceLocation PUMP_OVERLAY_OUT = GTCEu.id("block/cover/overlay_pump"); - public final static ResourceLocation PUMP_OVERLAY_IN = GTCEu.id("block/cover/overlay_pump_inverted"); - - protected PumpCoverRenderer() { - if (LDLib.isClient()) { - registerEvent(); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void renderCover(List quads, Direction side, RandomSource rand, - @NotNull CoverBehavior coverBehavior, Direction modelFacing, BlockPos pos, - BlockAndTintGetter level, ModelState modelState) { - if (side == coverBehavior.attachedSide && coverBehavior instanceof PumpCover pump && modelFacing != null) { - quads.add(StaticFaceBakery.bakeFace(modelFacing, - ModelFactory.getBlockSprite(pump.getIo() == IO.OUT ? PUMP_OVERLAY_OUT : PUMP_OVERLAY_IN), - modelState)); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void onPrepareTextureAtlas(ResourceLocation atlasName, Consumer register) { - if (atlasName.equals(TextureAtlas.LOCATION_BLOCKS)) { - register.accept(PUMP_OVERLAY_IN); - register.accept(PUMP_OVERLAY_OUT); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/RobotArmCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/RobotArmCoverRenderer.java deleted file mode 100644 index 1a953cf9db..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/RobotArmCoverRenderer.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.cover; - -import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.api.capability.recipe.IO; -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.client.util.StaticFaceBakery; -import com.gregtechceu.gtceu.common.cover.RobotArmCover; - -import com.lowdragmc.lowdraglib.LDLib; -import com.lowdragmc.lowdraglib.client.model.ModelFactory; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.function.Consumer; - -public class RobotArmCoverRenderer implements ICoverRenderer { - - public final static RobotArmCoverRenderer INSTANCE = new RobotArmCoverRenderer(); - public final static ResourceLocation ARM_OVERLAY = GTCEu.id("block/cover/overlay_arm"); - public final static ResourceLocation ARM_OVERLAY_OUT = GTCEu.id("block/cover/overlay_arm_emissive"); - public final static ResourceLocation AR_OVERLAY_IN = GTCEu.id("block/cover/overlay_arm_inverted_emissive"); - - protected RobotArmCoverRenderer() { - if (LDLib.isClient()) { - registerEvent(); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void renderCover(List quads, @Nullable Direction side, RandomSource rand, - @NotNull CoverBehavior coverBehavior, @Nullable Direction modelFacing, BlockPos pos, - BlockAndTintGetter level, ModelState modelState) { - if (side == coverBehavior.attachedSide && coverBehavior instanceof RobotArmCover robotArm && - modelFacing != null) { - quads.add(StaticFaceBakery.bakeFace(modelFacing, ModelFactory.getBlockSprite(ARM_OVERLAY), modelState)); - quads.add(StaticFaceBakery.bakeFace(modelFacing, - ModelFactory.getBlockSprite(robotArm.getIo() == IO.OUT ? ARM_OVERLAY_OUT : AR_OVERLAY_IN), - modelState, -101, 15)); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void onPrepareTextureAtlas(ResourceLocation atlasName, Consumer register) { - if (atlasName.equals(TextureAtlas.LOCATION_BLOCKS)) { - register.accept(ARM_OVERLAY); - register.accept(AR_OVERLAY_IN); - register.accept(ARM_OVERLAY_OUT); - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/SimpleCoverRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/SimpleCoverRenderer.java deleted file mode 100644 index 8f1d7f0f9d..0000000000 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/cover/SimpleCoverRenderer.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.gregtechceu.gtceu.client.renderer.cover; - -import com.gregtechceu.gtceu.api.cover.CoverBehavior; -import com.gregtechceu.gtceu.client.util.StaticFaceBakery; - -import com.lowdragmc.lowdraglib.LDLib; -import com.lowdragmc.lowdraglib.client.model.ModelFactory; -import com.lowdragmc.lowdraglib.utils.ResourceHelper; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import org.jetbrains.annotations.NotNull; - -import java.util.List; -import java.util.function.Consumer; - -/** - * @author KilaBash - * @date 2023/2/24 - * @implNote SimpleCoverRenderer - */ -public class SimpleCoverRenderer implements ICoverRenderer { - - ResourceLocation texture; - ResourceLocation emissiveTexture; - - public SimpleCoverRenderer(ResourceLocation texture) { - this.texture = texture; - if (LDLib.isClient()) { - registerEvent(); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void onPrepareTextureAtlas(ResourceLocation atlasName, Consumer register) { - if (atlasName.equals(TextureAtlas.LOCATION_BLOCKS)) { - register.accept(texture); - emissiveTexture = new ResourceLocation(texture.getNamespace(), texture.getPath() + "_emissive"); - if (ResourceHelper.isTextureExist(emissiveTexture)) register.accept(emissiveTexture); - else emissiveTexture = null; - } - } - - @OnlyIn(Dist.CLIENT) - public void renderCover(List quads, Direction side, RandomSource rand, - @NotNull CoverBehavior coverBehavior, Direction modelFacing, BlockPos pos, - BlockAndTintGetter level, ModelState modelState) { - if (side == coverBehavior.attachedSide && modelFacing != null) { - quads.add(StaticFaceBakery.bakeFace(modelFacing, ModelFactory.getBlockSprite(texture), modelState)); - if (emissiveTexture != null) { - quads.add(StaticFaceBakery.bakeFace(modelFacing, ModelFactory.getBlockSprite(emissiveTexture), - modelState)); - } - } - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/machine/QuantumChestRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/machine/QuantumChestRenderer.java index 6abe6b85d7..efa8d13468 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/machine/QuantumChestRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/machine/QuantumChestRenderer.java @@ -2,6 +2,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; +import com.gregtechceu.gtceu.client.ClientProxy; import com.gregtechceu.gtceu.common.machine.storage.QuantumChestMachine; import com.gregtechceu.gtceu.core.mixins.GuiGraphicsAccessor; @@ -61,7 +62,7 @@ public void renderItem(ItemStack stack, ItemDisplayContext transformType, boolea ItemStack itemStack = ItemStack.of(stack.getOrCreateTagElement("stored")); int storedAmount = stack.getOrCreateTag().getInt("storedAmount"); - float tick = Minecraft.getInstance().level.getGameTime() + Minecraft.getInstance().getFrameTime(); + float tick = Minecraft.getInstance().levelRenderer.getTicks() + Minecraft.getInstance().getFrameTime(); // Don't need to handle locked items here since they don't get saved to the item renderChest(poseStack, buffer, Direction.NORTH, itemStack, storedAmount, tick, ItemStack.EMPTY); @@ -76,9 +77,8 @@ public void render(BlockEntity blockEntity, float partialTicks, PoseStack poseSt int combinedLight, int combinedOverlay) { if (blockEntity instanceof IMachineBlockEntity machineBlockEntity && machineBlockEntity.getMetaMachine() instanceof QuantumChestMachine machine) { - var level = machine.getLevel(); var frontFacing = machine.getFrontFacing(); - float tick = level.getGameTime() + partialTicks; + float tick = ClientProxy.getServerTickCount() + partialTicks; renderChest(poseStack, buffer, frontFacing, machine.getStored(), machine.getStoredAmount(), tick, machine.getLockedItem().getStackInSlot(0)); } diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java index 0217f66d7f..dea537f80e 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/AbstractPipeModel.java @@ -38,7 +38,6 @@ import java.util.Collections; import java.util.List; -@OnlyIn(Dist.CLIENT) public abstract class AbstractPipeModel { public static ModelProperty THICKNESS_PROPERTY = new ModelProperty<>(); @@ -70,6 +69,7 @@ public AbstractPipeModel() { PIPE_CACHES.add(pipeCache); } + @OnlyIn(Dist.CLIENT) public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData modelData, @Nullable RenderType renderType) { @@ -88,6 +88,7 @@ public AbstractPipeModel() { return Collections.emptyList(); } + @OnlyIn(Dist.CLIENT) protected void renderCovers(List quads, @NotNull CoverRendererPackage rendererPackage, RandomSource rand, @NotNull ModelData data, RenderType renderType) { int color = safeInt(data.get(COLOR_PROPERTY)); @@ -116,6 +117,7 @@ protected static int safeInt(@Nullable Integer integer) { return integer == null ? 0 : integer; } + @OnlyIn(Dist.CLIENT) public @NotNull List getQuads(K key, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, @Nullable Material frameMaterial, byte frameMask, byte coverMask, diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java index 96ebfa74fd..c6d4a8847c 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/ActivablePipeModel.java @@ -32,7 +32,6 @@ import java.util.List; import java.util.stream.Collectors; -@OnlyIn(Dist.CLIENT) public class ActivablePipeModel extends AbstractPipeModel { public static final ModelProperty ACTIVE_PROPERTY = new ModelProperty<>(); @@ -61,6 +60,7 @@ public ActivablePipeModel(@NotNull TextureInformation inTex, } @Override + @OnlyIn(Dist.CLIENT) public @NotNull List getQuads(ActivableCacheKey key, byte connectionMask, byte closedMask, byte blockedMask, ColorData data, @Nullable Material frameMaterial, diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java index cb3d177b6e..37130de7dd 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -27,7 +27,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -@OnlyIn(Dist.CLIENT) public class PipeModel extends AbstractPipeModel { private final @NotNull TextureInformation inTex; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java index 44fa90088a..b617e08d3a 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRedirector.java @@ -19,6 +19,8 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.model.data.ModelData; import lombok.Getter; @@ -28,6 +30,7 @@ import java.util.List; import java.util.function.Function; +@OnlyIn(Dist.CLIENT) public class PipeModelRedirector implements BakedModel { private final boolean ambientOcclusion; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java index b2b94fa443..7cb019bf8b 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -16,6 +16,8 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Range; @@ -25,6 +27,7 @@ import java.util.Map; import java.util.function.BiConsumer; +@OnlyIn(Dist.CLIENT) public final class PipeModelRegistry { public static final Map MODELS = new HashMap<>(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedActivityDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedActivityDetectorCover.java index 415ba2eeca..6fcef4b8ee 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedActivityDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedActivityDetectorCover.java @@ -1,8 +1,11 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.utils.RedstoneUtil; import net.minecraft.MethodsReturnNonnullByDefault; @@ -18,6 +21,12 @@ public AdvancedActivityDetectorCover(CoverDefinition definition, ICoverable cove super(definition, coverHolder, attachedSide); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_activity_detector_advanced"), + GTCEu.id("block/cover/overlay_activity_detector_advanced_emissive")).build(); + } + @Override protected void update() { if (this.coverHolder.getOffsetTimer() % 20 != 0) diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedEnergyDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedEnergyDetectorCover.java index 8f7e8f2939..2645ae7cc5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedEnergyDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedEnergyDetectorCover.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.capability.IEnergyInfoProvider; import com.gregtechceu.gtceu.api.cover.CoverDefinition; @@ -7,6 +8,8 @@ import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.LongInputWidget; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.data.lang.LangHandler; import com.gregtechceu.gtceu.utils.GTMath; import com.gregtechceu.gtceu.utils.RedstoneUtil; @@ -67,6 +70,11 @@ public AdvancedEnergyDetectorCover(CoverDefinition definition, ICoverable coverH this.usePercent = true; } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_energy_detector_advanced"), null).build(); + } + @Override protected void update() { if (coverHolder.getOffsetTimer() % 20 != 0) return; diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedFluidDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedFluidDetectorCover.java index 7639696228..9405cff9fe 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedFluidDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedFluidDetectorCover.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.IUICover; @@ -9,6 +10,8 @@ import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.LongInputWidget; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.data.lang.LangHandler; import com.gregtechceu.gtceu.utils.GTMath; import com.gregtechceu.gtceu.utils.RedstoneUtil; @@ -67,6 +70,11 @@ public AdvancedFluidDetectorCover(CoverDefinition definition, ICoverable coverHo filterHandler = FilterHandlers.fluid(this); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_detector_advanced"), null).build(); + } + @Override public List getAdditionalDrops() { var list = super.getAdditionalDrops(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedItemDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedItemDetectorCover.java index b4bc1f6944..152676cdbe 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedItemDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/AdvancedItemDetectorCover.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.cover.detector; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.IUICover; @@ -9,6 +10,8 @@ import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.IntInputWidget; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.data.lang.LangHandler; import com.gregtechceu.gtceu.utils.RedstoneUtil; @@ -66,6 +69,11 @@ public AdvancedItemDetectorCover(CoverDefinition definition, ICoverable coverHol filterHandler = FilterHandlers.item(this); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_detector_advanced"), null).build(); + } + @Override public List getAdditionalDrops() { var list = super.getAdditionalDrops(); diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java index 60cc061f3f..6daa7fb0af 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/EnergyDetectorCover.java @@ -23,8 +23,7 @@ public EnergyDetectorCover(CoverDefinition definition, ICoverable coverHolder, D @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_energy_detector"), - GTCEu.id("block/cover/overlay_energy_detector_emissive")).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_energy_detector"), null).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java index 2dea6a67f3..228c839f12 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/FluidDetectorCover.java @@ -24,8 +24,7 @@ public FluidDetectorCover(CoverDefinition definition, ICoverable coverHolder, Di @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_detector"), - GTCEu.id("block/cover/overlay_fluid_detector_emissive")).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_fluid_detector"), null).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java index 4b2ee48909..ef75943bb1 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/detector/ItemDetectorCover.java @@ -28,8 +28,7 @@ public boolean canAttach(@NotNull ICoverable coverable, @NotNull Direction side) @Override protected CoverRenderer buildRenderer() { - return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_detector"), - GTCEu.id("block/cover/overlay_item_detector_emissive")).build(); + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_detector"), null).build(); } @Override diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedItemVoidingCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedItemVoidingCover.java index a7fa86fcb5..7d9ac739cb 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedItemVoidingCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/AdvancedItemVoidingCover.java @@ -1,11 +1,14 @@ package com.gregtechceu.gtceu.common.cover.voiding; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.cover.filter.ItemFilter; import com.gregtechceu.gtceu.api.cover.filter.SimpleItemFilter; import com.gregtechceu.gtceu.api.gui.widget.EnumSelectorWidget; import com.gregtechceu.gtceu.api.gui.widget.IntInputWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.data.VoidingMode; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; @@ -44,6 +47,12 @@ public AdvancedItemVoidingCover(CoverDefinition definition, ICoverable coverHold super(definition, coverHolder, attachedSide); } + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_voiding_advanced"), + GTCEu.id("block/cover/overlay_item_voiding_advanced_emissive")).build(); + } + ////////////////////////////////////////////// // *********** COVER LOGIC ***********// ////////////////////////////////////////////// diff --git a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/ItemVoidingCover.java b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/ItemVoidingCover.java index f5b6b6084a..0c4fba016e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/ItemVoidingCover.java +++ b/src/main/java/com/gregtechceu/gtceu/common/cover/voiding/ItemVoidingCover.java @@ -1,5 +1,6 @@ package com.gregtechceu.gtceu.common.cover.voiding; +import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.capability.IControllable; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.cover.CoverDefinition; @@ -7,6 +8,8 @@ import com.gregtechceu.gtceu.api.cover.filter.ItemFilter; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.gui.widget.ToggleButtonWidget; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRenderer; +import com.gregtechceu.gtceu.client.renderer.pipe.cover.CoverRendererBuilder; import com.gregtechceu.gtceu.common.cover.ConveyorCover; import com.lowdragmc.lowdraglib.gui.widget.LabelWidget; @@ -42,6 +45,17 @@ protected boolean isSubscriptionActive() { return isWorkingEnabled() && isEnabled(); } + @Override + public @NotNull CoverRenderer getRenderer() { + if (renderer == null) renderer = buildRenderer(); + return renderer; + } + + @Override + protected CoverRenderer buildRenderer() { + return new CoverRendererBuilder(GTCEu.id("block/cover/overlay_item_voiding"), null).build(); + } + ////////////////////////////////////////////// // *********** COVER LOGIC ***********// ////////////////////////////////////////////// diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java index fa2bbd92a5..8f6c0bc541 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTCovers.java @@ -7,7 +7,6 @@ import com.gregtechceu.gtceu.api.addon.IGTAddon; import com.gregtechceu.gtceu.api.cover.CoverDefinition; import com.gregtechceu.gtceu.api.registry.GTRegistries; -import com.gregtechceu.gtceu.client.renderer.cover.*; import com.gregtechceu.gtceu.common.cover.*; import com.gregtechceu.gtceu.common.cover.detector.*; import com.gregtechceu.gtceu.common.cover.voiding.AdvancedFluidVoidingCover; @@ -17,8 +16,6 @@ import net.minecraftforge.fml.ModLoader; -import it.unimi.dsi.fastutil.ints.Int2ObjectFunction; - import java.util.Arrays; import java.util.Locale; @@ -38,126 +35,59 @@ public class GTCovers { GTRegistries.COVERS.unfreeze(); } - public final static CoverDefinition FACADE = register( - "facade", FacadeCover::new, - FacadeCoverRenderer.INSTANCE); - - public final static CoverDefinition ITEM_FILTER = register( - "item_filter", ItemFilterCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_item_filter"))); - - public final static CoverDefinition FLUID_FILTER = register( - "fluid_filter", FluidFilterCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_fluid_filter"))); - - public final static CoverDefinition INFINITE_WATER = register( - "infinite_water", InfiniteWaterCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_infinite_water"))); - - public final static CoverDefinition SHUTTER = register( - "shutter", ShutterCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_shutter"))); - - public final static CoverDefinition[] CONVEYORS = registerTiered( - "conveyor", ConveyorCover::new, - tier -> ConveyorCoverRenderer.INSTANCE, ALL_TIERS); - - public final static CoverDefinition[] ROBOT_ARMS = registerTiered( - "robot_arm", RobotArmCover::new, - tier -> RobotArmCoverRenderer.INSTANCE, ALL_TIERS); - - public final static CoverDefinition[] PUMPS = registerTiered( - "pump", PumpCover::new, - tier -> PumpCoverRenderer.INSTANCE, ALL_TIERS); - - public final static CoverDefinition[] FLUID_REGULATORS = registerTiered( - "fluid_regulator", FluidRegulatorCover::new, - tier -> FluidRegulatorCoverRenderer.INSTANCE, ALL_TIERS); - - public final static CoverDefinition COMPUTER_MONITOR = register( - "computer_monitor", ComputerMonitorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_display"))); - - public final static CoverDefinition MACHINE_CONTROLLER = register( - "machine_controller", MachineControllerCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_controller"))); + public final static CoverDefinition FACADE = register("facade", FacadeCover::new); + public final static CoverDefinition ITEM_FILTER = register("item_filter", ItemFilterCover::new); + public final static CoverDefinition FLUID_FILTER = register("fluid_filter", FluidFilterCover::new); + public final static CoverDefinition INFINITE_WATER = register("infinite_water", InfiniteWaterCover::new); + public final static CoverDefinition SHUTTER = register("shutter", ShutterCover::new); + public final static CoverDefinition[] CONVEYORS = registerTiered("conveyor", ConveyorCover::new, ALL_TIERS); + public final static CoverDefinition[] ROBOT_ARMS = registerTiered("robot_arm", RobotArmCover::new, ALL_TIERS); + public final static CoverDefinition[] PUMPS = registerTiered("pump", PumpCover::new, ALL_TIERS); + public final static CoverDefinition[] FLUID_REGULATORS = registerTiered("fluid_regulator", FluidRegulatorCover::new, + ALL_TIERS); + + public final static CoverDefinition COMPUTER_MONITOR = register("computer_monitor", ComputerMonitorCover::new); + public final static CoverDefinition MACHINE_CONTROLLER = register("machine_controller", + MachineControllerCover::new); // Voiding - public final static CoverDefinition ITEM_VOIDING = register( - "item_voiding", ItemVoidingCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_item_voiding"))); - public final static CoverDefinition ITEM_VOIDING_ADVANCED = register( - "item_voiding_advanced", AdvancedItemVoidingCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_item_voiding_advanced"))); - public final static CoverDefinition FLUID_VOIDING = register( - "fluid_voiding", FluidVoidingCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_fluid_voiding"))); - public final static CoverDefinition FLUID_VOIDING_ADVANCED = register( - "fluid_voiding_advanced", AdvancedFluidVoidingCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_fluid_voiding_advanced"))); + public final static CoverDefinition ITEM_VOIDING = register("item_voiding", ItemVoidingCover::new); + public final static CoverDefinition ITEM_VOIDING_ADVANCED = register("item_voiding_advanced", + AdvancedItemVoidingCover::new); + public final static CoverDefinition FLUID_VOIDING = register("fluid_voiding", FluidVoidingCover::new); + public final static CoverDefinition FLUID_VOIDING_ADVANCED = register("fluid_voiding_advanced", + AdvancedFluidVoidingCover::new); // Detectors - public final static CoverDefinition ACTIVITY_DETECTOR = register( - "activity_detector", ActivityDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_activity_detector"))); - public final static CoverDefinition ACTIVITY_DETECTOR_ADVANCED = register( - "activity_detector_advanced", AdvancedActivityDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_activity_detector_advanced"))); - public final static CoverDefinition FLUID_DETECTOR = register( - "fluid_detector", FluidDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_fluid_detector"))); - public final static CoverDefinition FLUID_DETECTOR_ADVANCED = register( - "fluid_detector_advanced", AdvancedFluidDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_fluid_detector_advanced"))); - public final static CoverDefinition ITEM_DETECTOR = register( - "item_detector", ItemDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_item_detector"))); - public final static CoverDefinition ITEM_DETECTOR_ADVANCED = register( - "item_detector_advanced", AdvancedItemDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_item_detector_advanced"))); - public final static CoverDefinition ENERGY_DETECTOR = register( - "energy_detector", EnergyDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_energy_detector"))); - public final static CoverDefinition ENERGY_DETECTOR_ADVANCED = register( - "energy_detector_advanced", AdvancedEnergyDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_energy_detector_advanced"))); - public final static CoverDefinition MAINTENANCE_DETECTOR = register( - "maintenance_detector", MaintenanceDetectorCover::new, - new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_maintenance_detector"))); + public final static CoverDefinition ACTIVITY_DETECTOR = register("activity_detector", ActivityDetectorCover::new); + public final static CoverDefinition ACTIVITY_DETECTOR_ADVANCED = register("activity_detector_advanced", + AdvancedActivityDetectorCover::new); + public final static CoverDefinition FLUID_DETECTOR = register("fluid_detector", FluidDetectorCover::new); + public final static CoverDefinition FLUID_DETECTOR_ADVANCED = register("fluid_detector_advanced", + AdvancedFluidDetectorCover::new); + public final static CoverDefinition ITEM_DETECTOR = register("item_detector", ItemDetectorCover::new); + public final static CoverDefinition ITEM_DETECTOR_ADVANCED = register("item_detector_advanced", + AdvancedItemDetectorCover::new); + public final static CoverDefinition ENERGY_DETECTOR = register("energy_detector", EnergyDetectorCover::new); + public final static CoverDefinition ENERGY_DETECTOR_ADVANCED = register("energy_detector_advanced", + AdvancedEnergyDetectorCover::new); + public final static CoverDefinition MAINTENANCE_DETECTOR = register("maintenance_detector", + MaintenanceDetectorCover::new); // Solar Panels - public final static CoverDefinition[] SOLAR_PANEL = registerTiered( - "solar_panel", CoverSolarPanel::new, - tier -> new SimpleCoverRenderer(GTCEu.id("block/cover/overlay_solar_panel")), ALL_TIERS_WITH_ULV); + public final static CoverDefinition[] SOLAR_PANEL = registerTiered("solar_panel", CoverSolarPanel::new, + ALL_TIERS_WITH_ULV); /////////////////////////////////////////////// // *********** UTIL METHODS ***********// /////////////////////////////////////////////// public static CoverDefinition register(String id, CoverDefinition.CoverBehaviourProvider behaviorCreator) { - return register(id, behaviorCreator, new SimpleCoverRenderer(GTCEu.id("block/cover/" + id))); - } - - public static CoverDefinition register(String id, CoverDefinition.CoverBehaviourProvider behaviorCreator, - ICoverRenderer coverRenderer) { - var definition = new CoverDefinition(GTCEu.id(id), behaviorCreator, - (quads, side, rand, renderPlate, renderBackside, modelData, colorData, renderType) -> coverRenderer - .renderCover(quads, side, - rand, null, null, null, null, null)); + var definition = new CoverDefinition(GTCEu.id(id), behaviorCreator); GTRegistries.COVERS.register(GTCEu.id(id), definition); return definition; } - public static CoverDefinition[] registerTiered(String id, - CoverDefinition.TieredCoverBehaviourProvider behaviorCreator, - Int2ObjectFunction coverRenderer, int... tiers) { - return Arrays.stream(tiers).mapToObj(tier -> { - var name = id + "." + GTValues.VN[tier].toLowerCase(Locale.ROOT); - return register(name, (def, coverable, side) -> behaviorCreator.create(def, coverable, side, tier), - coverRenderer.apply(tier)); - }).toArray(CoverDefinition[]::new); - } - public static CoverDefinition[] registerTiered(String id, CoverDefinition.TieredCoverBehaviourProvider behaviorCreator, int... tiers) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java b/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java index 940f8497c8..58a1ad67e3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java +++ b/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java @@ -16,6 +16,8 @@ public class GTNetwork { public static void init() { NETWORK.registerC2S(CPacketKeysPressed.class); + NETWORK.registerS2C(SPacketSyncTickCount.class); + NETWORK.registerS2C(SPacketSyncOreVeins.class); NETWORK.registerS2C(SPacketSyncFluidVeins.class); NETWORK.registerS2C(SPacketSyncBedrockOreVeins.class); diff --git a/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java new file mode 100644 index 0000000000..a1a8719f3a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java @@ -0,0 +1,33 @@ +package com.gregtechceu.gtceu.common.network.packets; + +import com.gregtechceu.gtceu.client.ClientProxy; +import com.lowdragmc.lowdraglib.Platform; +import com.lowdragmc.lowdraglib.networking.IHandlerContext; +import com.lowdragmc.lowdraglib.networking.IPacket; +import lombok.AllArgsConstructor; +import net.minecraft.network.FriendlyByteBuf; + +@AllArgsConstructor +public class SPacketSyncTickCount implements IPacket { + + private long serverTickCount; + + public SPacketSyncTickCount() { + serverTickCount = Platform.getMinecraftServer().getTickCount(); + } + + @Override + public void encode(FriendlyByteBuf buf) { + buf.writeVarLong(serverTickCount); + } + + @Override + public void decode(FriendlyByteBuf buf) { + serverTickCount = buf.readVarLong(); + } + + @Override + public void execute(IHandlerContext handler) { + ClientProxy.setServerTickCount(serverTickCount); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index 9798795301..bddaedb9cc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.Material; import com.gregtechceu.gtceu.api.graphnet.pipenet.WorldPipeNetNode; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.IBurnable; +import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.block.PipeMaterialBlock; import com.gregtechceu.gtceu.api.graphnet.pipenet.physical.tile.PipeBlockEntity; import com.gregtechceu.gtceu.api.item.tool.GTToolType; @@ -17,15 +18,19 @@ import com.lowdragmc.lowdraglib.Platform; import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; import org.jetbrains.annotations.Nullable; import java.util.Map; @@ -72,6 +77,22 @@ public void partialBurn(BlockState state, Level world, BlockPos pos) { if (structure.partialBurnStructure() != null) { BlockState newState = CACHE.get(material).get(structure.partialBurnStructure()).defaultBlockState(); world.setBlockAndUpdate(pos, newState); + + BlockEntity newBlockEntity = world.getBlockEntity(pos); + if (!(newBlockEntity instanceof PipeBlockEntity pipe)) return; + for (Direction facing : GTUtil.DIRECTIONS) { + if (pipe.isConnected(facing)) { + PipeBlock.connectTile(pipe, pipe.getPipeNeighbor(facing, false), facing); + BlockPos relativePos = pipe.getBlockPos().relative(facing); + ChunkAccess chunk = world.getChunk(relativePos); + if (chunk instanceof LevelChunk levelChunk) { + BlockEntity candidate = levelChunk + .getBlockEntity(relativePos, LevelChunk.EntityCreationType.CHECK); + if (candidate instanceof PipeBlockEntity otherPipe) + PipeBlock.connectTile(pipe, otherPipe, facing); + } + } + } } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index f0f22e6b15..3a251697cb 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -10,37 +10,41 @@ import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.function.Supplier; + public record CableStructure(String name, int material, int costFactor, TagPrefix prefix, @Nullable CableStructure partialBurnStructure, @Nullable Integer partialBurnThreshold, - float renderThickness, PipeModelRedirector model) + float renderThickness, Supplier> model) implements IPipeMaterialStructure, IInsulatable { public static final int INSULATION_BURN_TEMP = 1000; public static final CableStructure WIRE_SINGLE = new CableStructure("single_wire", 1, 2, TagPrefix.wireGtSingle, - null, null, 0.125f, PipeModelRegistry.getCableModel(0)); + null, null, 0.125f, () -> () -> PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_DOUBLE = new CableStructure("double_wire", 2, 2, TagPrefix.wireGtDouble, - null, null, 0.25f, PipeModelRegistry.getCableModel(0)); + null, null, 0.25f, () -> () -> PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_QUADRUPLE = new CableStructure("quadruple_wire", 4, 3, - TagPrefix.wireGtQuadruple, null, null, 0.375f, PipeModelRegistry.getCableModel(0)); + TagPrefix.wireGtQuadruple, null, null, 0.375f, () -> () -> PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_OCTAL = new CableStructure("octal_wire", 8, 3, TagPrefix.wireGtOctal, null, - null, 0.5f, PipeModelRegistry.getCableModel(0)); + null, 0.5f, () -> () -> PipeModelRegistry.getCableModel(0)); public static final CableStructure WIRE_HEX = new CableStructure("hex_wire", 16, 3, TagPrefix.wireGtHex, null, null, - 0.75f, PipeModelRegistry.getCableModel(0)); + 0.75f, () -> () -> PipeModelRegistry.getCableModel(0)); public static final CableStructure CABLE_SINGLE = new CableStructure("single_cable", 1, 1, TagPrefix.cableGtSingle, - WIRE_SINGLE, INSULATION_BURN_TEMP, 0.25f, PipeModelRegistry.getCableModel(1)); + WIRE_SINGLE, INSULATION_BURN_TEMP, 0.25f, () -> () -> PipeModelRegistry.getCableModel(1)); public static final CableStructure CABLE_DOUBLE = new CableStructure("double_cable", 2, 1, TagPrefix.cableGtDouble, - WIRE_DOUBLE, INSULATION_BURN_TEMP, 0.375f, PipeModelRegistry.getCableModel(2)); + WIRE_DOUBLE, INSULATION_BURN_TEMP, 0.375f, () -> () -> PipeModelRegistry.getCableModel(2)); public static final CableStructure CABLE_QUADRUPLE = new CableStructure("quadruple_cable", 4, 1, - TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, PipeModelRegistry.getCableModel(3)); + TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, () -> () -> PipeModelRegistry.getCableModel(3)); public static final CableStructure CABLE_OCTAL = new CableStructure("octal_cable", 8, 1, TagPrefix.cableGtOctal, - WIRE_OCTAL, INSULATION_BURN_TEMP, 0.75f, PipeModelRegistry.getCableModel(4)); + WIRE_OCTAL, INSULATION_BURN_TEMP, 0.75f, () -> () -> PipeModelRegistry.getCableModel(4)); public static final CableStructure CABLE_HEX = new CableStructure("hex_cable", 16, 1, TagPrefix.cableGtHex, - WIRE_HEX, INSULATION_BURN_TEMP, 1f, PipeModelRegistry.getCableModel(5)); + WIRE_HEX, INSULATION_BURN_TEMP, 1f, () -> () -> PipeModelRegistry.getCableModel(5)); @Override public @NotNull String getSerializedName() { @@ -73,8 +77,9 @@ public boolean isInsulated() { } @Override + @OnlyIn(Dist.CLIENT) public PipeModelRedirector getModel() { - return model; + return model.get().get(); } public static void register(@NotNull PipeStructureRegistrationEvent event) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java index ab9e1471d8..27c114875c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -5,6 +5,8 @@ import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; public record DuctStructure(String name, float renderThickness, float rateMultiplier) implements IPipeStructure { @@ -30,6 +32,7 @@ public boolean isPaintable() { } @Override + @OnlyIn(Dist.CLIENT) public PipeModelRedirector getModel() { return PipeModelRegistry.getDuctModel(); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java index 3d30095e68..44a9a488be 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -11,15 +11,19 @@ import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; -public record LaserStructure(String name, float renderThickness, boolean mirror, PipeModelRedirector model) +import java.util.function.Supplier; + +public record LaserStructure(String name, float renderThickness, boolean mirror, Supplier> model) implements IPipeStructure { public static final LaserStructure NORMAL = new LaserStructure("laser_pipe_normal", 0.375f, - false, PipeModelRegistry.getLaserModel()); + false, () -> () -> PipeModelRegistry.getLaserModel()); public static final LaserStructure MIRROR = new LaserStructure("laser_pipe_mirror", 0.5f, - true, PipeModelRegistry.getLaserModel()); + true, () -> () -> PipeModelRegistry.getLaserModel()); @Override public ResourceTexture getPipeTexture(boolean isBlock) { @@ -65,8 +69,9 @@ public boolean isPaintable() { } @Override + @OnlyIn(Dist.CLIENT) public PipeModelRedirector getModel() { - return model; + return model.get().get(); } public static void register(@NotNull PipeStructureRegistrationEvent event) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java index 7cbfd291ec..f006f9a16b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -11,13 +11,17 @@ import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; -public record OpticalStructure(String name, float renderThickness, PipeModelRedirector model) +import java.util.function.Supplier; + +public record OpticalStructure(String name, float renderThickness, Supplier> model) implements IPipeStructure { public static final OpticalStructure INSTANCE = new OpticalStructure("optical_pipe_normal", 0.375f, - PipeModelRegistry.getOpticalModel()); + () -> () -> PipeModelRegistry.getOpticalModel()); @Override public ResourceTexture getPipeTexture(boolean isBlock) { @@ -53,8 +57,9 @@ public boolean isPaintable() { } @Override + @OnlyIn(Dist.CLIENT) public PipeModelRedirector getModel() { - return model; + return model.get().get(); } public static void register(@NotNull PipeStructureRegistrationEvent event) { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java index 30c26bd56f..118659598e 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -7,45 +7,49 @@ import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRedirector; import com.gregtechceu.gtceu.client.renderer.pipe.PipeModelRegistry; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; +import java.util.function.Supplier; + public record MaterialPipeStructure(String name, int material, int channelCount, boolean restrictive, TagPrefix prefix, - float renderThickness, PipeModelRedirector model) + float renderThickness, Supplier> model) implements IPipeMaterialStructure, IPipeChanneledStructure { public static final MaterialPipeStructure TINY = new MaterialPipeStructure("tiny", 1, 1, false, - TagPrefix.pipeTiny, 0.25f, PipeModelRegistry.getPipeModel(0)); + TagPrefix.pipeTiny, 0.25f, () -> () -> PipeModelRegistry.getPipeModel(0)); public static final MaterialPipeStructure SMALL = new MaterialPipeStructure("small", 2, 1, false, - TagPrefix.pipeSmall, 0.375f, PipeModelRegistry.getPipeModel(1)); + TagPrefix.pipeSmall, 0.375f, () -> () -> PipeModelRegistry.getPipeModel(1)); public static final MaterialPipeStructure NORMAL = new MaterialPipeStructure("normal", 6, 1, false, - TagPrefix.pipeNormal, 0.5f, PipeModelRegistry.getPipeModel(2)); + TagPrefix.pipeNormal, 0.5f, () -> () -> PipeModelRegistry.getPipeModel(2)); public static final MaterialPipeStructure LARGE = new MaterialPipeStructure("large", 12, 1, false, - TagPrefix.pipeLarge, 0.75f, PipeModelRegistry.getPipeModel(3)); + TagPrefix.pipeLarge, 0.75f, () -> () -> PipeModelRegistry.getPipeModel(3)); public static final MaterialPipeStructure HUGE = new MaterialPipeStructure("huge", 24, 1, false, - TagPrefix.pipeHuge, 0.875f, PipeModelRegistry.getPipeModel(4)); + TagPrefix.pipeHuge, 0.875f, () -> () -> PipeModelRegistry.getPipeModel(4)); public static final MaterialPipeStructure QUADRUPLE = new MaterialPipeStructure("quadruple", 8, 4, false, - TagPrefix.pipeQuadruple, 0.95f, PipeModelRegistry.getPipeModel(5)); + TagPrefix.pipeQuadruple, 0.95f, () -> () -> PipeModelRegistry.getPipeModel(5)); public static final MaterialPipeStructure NONUPLE = new MaterialPipeStructure("nonuple", 18, 9, false, - TagPrefix.pipeNonuple, 0.95f, PipeModelRegistry.getPipeModel(6)); + TagPrefix.pipeNonuple, 0.95f, () -> () -> PipeModelRegistry.getPipeModel(6)); public static final MaterialPipeStructure TINY_RESTRICTIVE = new MaterialPipeStructure("tiny_restrictive", 1, - 1, true, TagPrefix.pipeTinyRestrictive, 0.25f, PipeModelRegistry.getPipeRestrictiveModel(0)); + 1, true, TagPrefix.pipeTinyRestrictive, 0.25f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(0)); public static final MaterialPipeStructure SMALL_RESTRICTIVE = new MaterialPipeStructure("small_restrictive", 2, - 1, true, TagPrefix.pipeSmallRestrictive, 0.375f, PipeModelRegistry.getPipeRestrictiveModel(1)); + 1, true, TagPrefix.pipeSmallRestrictive, 0.375f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(1)); public static final MaterialPipeStructure NORMAL_RESTRICTIVE = new MaterialPipeStructure("normal_restrictive", - 6, 1, true, TagPrefix.pipeNormalRestrictive, 0.5f, PipeModelRegistry.getPipeRestrictiveModel(2)); + 6, 1, true, TagPrefix.pipeNormalRestrictive, 0.5f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(2)); public static final MaterialPipeStructure LARGE_RESTRICTIVE = new MaterialPipeStructure("large_restrictive", - 12, 1, true, TagPrefix.pipeLargeRestrictive, 0.75f, PipeModelRegistry.getPipeRestrictiveModel(3)); + 12, 1, true, TagPrefix.pipeLargeRestrictive, 0.75f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(3)); public static final MaterialPipeStructure HUGE_RESTRICTIVE = new MaterialPipeStructure("huge_restrictive", 24, - 1, true, TagPrefix.pipeHugeRestrictive, 0.875f, PipeModelRegistry.getPipeRestrictiveModel(4)); + 1, true, TagPrefix.pipeHugeRestrictive, 0.875f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(4)); public static final MaterialPipeStructure QUADRUPLE_RESTRICTIVE = new MaterialPipeStructure( "quadruple_restrictive", 8, 4, true, TagPrefix.pipeQuadrupleRestrictive, 0.95f, - PipeModelRegistry.getPipeRestrictiveModel(5)); + () -> () -> PipeModelRegistry.getPipeRestrictiveModel(5)); public static final MaterialPipeStructure NONUPLE_RESTRICTIVE = new MaterialPipeStructure( "nonuple_restrictive", 18, 9, true, TagPrefix.pipeNonupleRestrictive, 0.95f, - PipeModelRegistry.getPipeRestrictiveModel(6)); + () -> () -> PipeModelRegistry.getPipeRestrictiveModel(6)); @Override public @NotNull String getSerializedName() { @@ -68,8 +72,9 @@ public int getChannelCount() { } @Override + @OnlyIn(Dist.CLIENT) public PipeModelRedirector getModel() { - return model; + return model.get().get(); } @Override diff --git a/src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay.png b/src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay.png new file mode 100644 index 0000000000000000000000000000000000000000..57fb4be366200b38c6282a8c68532142cab8f2bd GIT binary patch literal 113 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`7M?DSAr*1S2@6Dj@Uz^w;nF-Y zjlqM_lHsn5NW+?j1xYy#D$D|XO1ukZH#1ET6$t6!?U8b@VPN>CbKWrbfa7wY84RAT KelF{r5}E)Z79VK< literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay_active.png b/src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay_active.png new file mode 100644 index 0000000000000000000000000000000000000000..d0d5cdc54a591822b7d7ade664e72b143c97649d GIT binary patch literal 197 zcmeAS@N?(olHy`uVBq!ia0vp^0zj<5!3HFyJAa%3Qfx`y?k)`fL2$v|<&%LToCO|{ z#S9GG!XV7ZFl&wkP>{XE)7O>#IhzQRn6?U^4mVIJ$kW9!#N&8!!U6$LtER*R2IXxG%2CG3%8v^;n=iJQ`!{c((M m*zVD6IdQ_D3@51!28IRgI?{)f4jTeZXYh3Ob6Mw<&;$TuYCbps literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay_active.png.mcmeta b/src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay_active.png.mcmeta new file mode 100644 index 0000000000..21972735d3 --- /dev/null +++ b/src/main/resources/assets/gtceu/textures/block/pipe/pipe_optical_side_overlay_active.png.mcmeta @@ -0,0 +1,5 @@ +{ + "animation": { + "frametime": 25 + } +} From 8435c54530e4ec0821febd0a1a3487eb3c9876bb Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 29 Sep 2024 15:23:24 +0300 Subject: [PATCH 63/70] fix portable scanner using the wrong method for getting block tooltips, which broke it for cable/material blocks --- .../gregtechceu/gtceu/common/item/PortableScannerBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java index 97b8148af3..f432580436 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/PortableScannerBehavior.java @@ -433,7 +433,7 @@ else if (machine instanceof IDataInfoProvider) list.add(Component.translatable("behavior.portable_scanner.divider")); list.addAll(dataInfoProvider.getDataInfo(mode)); } else { - list.add(Component.translatable(state.getBlock().getDescriptionId()).withStyle(ChatFormatting.BLUE)); + list.add(state.getBlock().getName().withStyle(ChatFormatting.BLUE)); } // Environmental information From 656d7c371ba88f61740f9453caf1822abb7f0d04 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Sun, 29 Sep 2024 17:04:43 +0300 Subject: [PATCH 64/70] sbobldes --- .../api/graphnet/pipenet/logic/TemperatureLogic.java | 3 --- .../api/graphnet/pipenet/physical/block/PipeBlock.java | 2 -- .../graphnet/pipenet/physical/tile/PipeBlockEntity.java | 1 - .../java/com/gregtechceu/gtceu/client/ClientProxy.java | 8 ++++---- .../gtceu/client/particle/GTOverheatParticle.java | 1 - .../gtceu/client/particle/GTParticleManager.java | 1 - .../gregtechceu/gtceu/client/renderer/pipe/PipeModel.java | 2 -- .../gtceu/client/renderer/pipe/PipeModelRegistry.java | 4 ++-- .../common/network/packets/SPacketSyncTickCount.java | 5 ++++- .../gtceu/common/pipelike/block/cable/CableBlock.java | 4 ++-- .../gtceu/common/pipelike/block/cable/CableStructure.java | 4 +++- .../gtceu/common/pipelike/block/duct/DuctStructure.java | 1 + .../gtceu/common/pipelike/block/laser/LaserStructure.java | 5 +++-- .../common/pipelike/block/optical/OpticalStructure.java | 2 +- .../common/pipelike/block/pipe/MaterialPipeStructure.java | 7 +++++-- 15 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java index 568481c783..426804d363 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/logic/TemperatureLogic.java @@ -15,9 +15,6 @@ import com.gregtechceu.gtceu.client.ClientProxy; import com.gregtechceu.gtceu.client.particle.GTOverheatParticle; -import com.lowdragmc.lowdraglib.Platform; - -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java index 7363cd496e..0134f33845 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/block/PipeBlock.java @@ -21,10 +21,8 @@ import com.gregtechceu.gtceu.utils.EntityDamageUtil; import com.gregtechceu.gtceu.utils.GTUtil; -import com.lowdragmc.lowdraglib.LDLib; import com.lowdragmc.lowdraglib.Platform; -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java index 58fb110afb..db51b7cc3c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/pipenet/physical/tile/PipeBlockEntity.java @@ -45,7 +45,6 @@ import com.lowdragmc.lowdraglib.syncdata.field.FieldManagedStorage; import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder; -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleOptions; diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index fbfc18bd43..328bd058a6 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -21,8 +21,6 @@ import com.lowdragmc.lowdraglib.gui.compass.CompassManager; import com.lowdragmc.lowdraglib.gui.compass.component.RecipeComponent; -import lombok.Getter; -import lombok.Setter; import net.minecraft.client.model.BoatModel; import net.minecraft.client.model.ChestBoatModel; import net.minecraft.client.renderer.blockentity.HangingSignRenderer; @@ -33,11 +31,12 @@ import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.event.*; -import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; +import lombok.Getter; +import lombok.Setter; /** * @author KilaBash @@ -50,7 +49,8 @@ public class ClientProxy extends CommonProxy { public static final BiMap CLIENT_FLUID_VEINS = HashBiMap.create(); public static final BiMap CLIENT_BEDROCK_ORE_VEINS = HashBiMap.create(); - @Getter @Setter + @Getter + @Setter private static long serverTickCount = -1L; public ClientProxy() { diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java index 8eb68cc6aa..708d9733c8 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTOverheatParticle.java @@ -14,7 +14,6 @@ import com.lowdragmc.shimmer.client.shader.RenderUtils; -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.phys.AABB; diff --git a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java index 1f4e997694..82b49170da 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java +++ b/src/main/java/com/gregtechceu/gtceu/client/particle/GTParticleManager.java @@ -12,7 +12,6 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.CustomizeGuiOverlayEvent; import net.minecraftforge.client.event.RenderLevelStageEvent; import net.minecraftforge.event.TickEvent; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java index 37130de7dd..2b35ecba5f 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModel.java @@ -20,8 +20,6 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.model.data.ModelData; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java index 7cb019bf8b..2aefabfbd6 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/pipe/PipeModelRegistry.java @@ -11,13 +11,13 @@ import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import com.google.common.collect.Tables; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Range; diff --git a/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java index a1a8719f3a..28dc0229c8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java +++ b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketSyncTickCount.java @@ -1,12 +1,15 @@ package com.gregtechceu.gtceu.common.network.packets; import com.gregtechceu.gtceu.client.ClientProxy; + import com.lowdragmc.lowdraglib.Platform; import com.lowdragmc.lowdraglib.networking.IHandlerContext; import com.lowdragmc.lowdraglib.networking.IPacket; -import lombok.AllArgsConstructor; + import net.minecraft.network.FriendlyByteBuf; +import lombok.AllArgsConstructor; + @AllArgsConstructor public class SPacketSyncTickCount implements IPacket { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java index bddaedb9cc..e5b5e642a3 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableBlock.java @@ -27,10 +27,10 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; - -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.LevelChunk; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.Nullable; import java.util.Map; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java index 3a251697cb..4b71f9822b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/cable/CableStructure.java @@ -12,6 +12,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -40,7 +41,8 @@ public record CableStructure(String name, int material, int costFactor, TagPrefi public static final CableStructure CABLE_DOUBLE = new CableStructure("double_cable", 2, 1, TagPrefix.cableGtDouble, WIRE_DOUBLE, INSULATION_BURN_TEMP, 0.375f, () -> () -> PipeModelRegistry.getCableModel(2)); public static final CableStructure CABLE_QUADRUPLE = new CableStructure("quadruple_cable", 4, 1, - TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, () -> () -> PipeModelRegistry.getCableModel(3)); + TagPrefix.cableGtQuadruple, WIRE_QUADRUPLE, INSULATION_BURN_TEMP, 0.5f, + () -> () -> PipeModelRegistry.getCableModel(3)); public static final CableStructure CABLE_OCTAL = new CableStructure("octal_cable", 8, 1, TagPrefix.cableGtOctal, WIRE_OCTAL, INSULATION_BURN_TEMP, 0.75f, () -> () -> PipeModelRegistry.getCableModel(4)); public static final CableStructure CABLE_HEX = new CableStructure("hex_cable", 16, 1, TagPrefix.cableGtHex, diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java index 27c114875c..9f4b81ab0d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/duct/DuctStructure.java @@ -7,6 +7,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; public record DuctStructure(String name, float renderThickness, float rateMultiplier) implements IPipeStructure { diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java index 44a9a488be..1d95756fc5 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/laser/LaserStructure.java @@ -10,14 +10,15 @@ import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import net.minecraft.core.Direction; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; -public record LaserStructure(String name, float renderThickness, boolean mirror, Supplier> model) +public record LaserStructure(String name, float renderThickness, boolean mirror, + Supplier> model) implements IPipeStructure { public static final LaserStructure NORMAL = new LaserStructure("laser_pipe_normal", 0.375f, diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java index f006f9a16b..1f920b0c97 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/optical/OpticalStructure.java @@ -10,9 +10,9 @@ import com.lowdragmc.lowdraglib.gui.texture.ResourceTexture; import net.minecraft.core.Direction; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; diff --git a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java index 118659598e..7079d3b8f9 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java +++ b/src/main/java/com/gregtechceu/gtceu/common/pipelike/block/pipe/MaterialPipeStructure.java @@ -9,6 +9,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; + import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; @@ -38,9 +39,11 @@ public record MaterialPipeStructure(String name, int material, int channelCount, public static final MaterialPipeStructure SMALL_RESTRICTIVE = new MaterialPipeStructure("small_restrictive", 2, 1, true, TagPrefix.pipeSmallRestrictive, 0.375f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(1)); public static final MaterialPipeStructure NORMAL_RESTRICTIVE = new MaterialPipeStructure("normal_restrictive", - 6, 1, true, TagPrefix.pipeNormalRestrictive, 0.5f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(2)); + 6, 1, true, TagPrefix.pipeNormalRestrictive, 0.5f, + () -> () -> PipeModelRegistry.getPipeRestrictiveModel(2)); public static final MaterialPipeStructure LARGE_RESTRICTIVE = new MaterialPipeStructure("large_restrictive", - 12, 1, true, TagPrefix.pipeLargeRestrictive, 0.75f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(3)); + 12, 1, true, TagPrefix.pipeLargeRestrictive, 0.75f, + () -> () -> PipeModelRegistry.getPipeRestrictiveModel(3)); public static final MaterialPipeStructure HUGE_RESTRICTIVE = new MaterialPipeStructure("huge_restrictive", 24, 1, true, TagPrefix.pipeHugeRestrictive, 0.875f, () -> () -> PipeModelRegistry.getPipeRestrictiveModel(4)); From 7cee9f50a6b03768dcc34040755bde99e2206751 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Tue, 1 Oct 2024 17:02:41 +0300 Subject: [PATCH 65/70] fix mixin refmap in prod --- build.gradle | 3 +++ gradle/scripts/moddevgradle.gradle | 2 -- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index f1fe80d3b8..c6863faf25 100644 --- a/build.gradle +++ b/build.gradle @@ -24,6 +24,8 @@ tasks.register('slimJar', ShadowJar) { from sourceSets.main.output } +final refmapFile = mixin.add sourceSets.main, "gtceu.refmap.json" + apply from: "$rootDir/gradle/scripts/moddevgradle.gradle" apply from: "$rootDir/gradle/scripts/repositories.gradle" apply from: "$rootDir/gradle/scripts/jars.gradle" @@ -34,6 +36,7 @@ apply from: "$rootDir/gradle/scripts/spotless.gradle" afterEvaluate { tasks.withType(ShadowJar).configureEach { + from(refmapFile) configurations = [project.configurations.includedLibrary] minimize() relocate("org.jgrapht", "${maven_group}.repack.org.jgrapht") diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle index d5c5545250..24476dd75c 100644 --- a/gradle/scripts/moddevgradle.gradle +++ b/gradle/scripts/moddevgradle.gradle @@ -1,6 +1,4 @@ - mixin { - add sourceSets.main, "gtceu.refmap.json" config 'gtceu.mixins.json' } From 63b42717bc0aa2fec7aca0ef6c0fc23b0a3c9b5d Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Tue, 1 Oct 2024 18:42:15 +0300 Subject: [PATCH 66/70] fix bug in shadow that broke jar-in-jar --- gradle/scripts/jars.gradle | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 3545343ed1..1fa63c5a0b 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -5,13 +5,19 @@ configurations { } } +// hack to avoid a bug in Shadow: https://github.com/GradleUp/shadow/issues/111 +tasks.register('shadowBugWorkaround', Jar) { + dependsOn jarJar + from jarJar.outputs +} + shadowJar { + from tasks.shadowBugWorkaround configurations = [project.configurations.includedLibrary] archiveClassifier = "dev" } slimJar { - from sourceSets.main.output configurations = [project.configurations.includedLibrary] archiveClassifier = "dev-slim" } From 3e75a4d4269e35cb0b00469eead25707efc38d87 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Tue, 1 Oct 2024 19:00:02 +0300 Subject: [PATCH 67/70] fix fluid crash --- .../java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java index 2d9a1dd02a..64d4532a06 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java +++ b/src/main/java/com/gregtechceu/gtceu/api/fluids/FluidBuilder.java @@ -6,6 +6,7 @@ import com.gregtechceu.gtceu.api.data.chemical.material.properties.PropertyKey; import com.gregtechceu.gtceu.api.fluids.attribute.FluidAttribute; import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKey; +import com.gregtechceu.gtceu.api.fluids.store.FluidStorageKeys; import com.gregtechceu.gtceu.api.registry.registrate.GTRegistrate; import com.gregtechceu.gtceu.api.registry.registrate.IGTFluidBuilder; import com.gregtechceu.gtceu.utils.GTUtil; @@ -340,8 +341,9 @@ public int getDeterminedTemperature(@Nullable Material material, @Nullable Fluid } case GAS -> ROOM_TEMPERATURE; case PLASMA -> { - if (material.hasFluid() && material.getFluid() != null) { - yield BASE_PLASMA_TEMPERATURE + material.getFluid().getFluidType().getTemperature(); + if (material.hasFluid() && material.getFluidBuilder() != null && + material.getFluidBuilder() != material.getFluidBuilder(FluidStorageKeys.PLASMA)) { + yield BASE_PLASMA_TEMPERATURE + material.getFluidBuilder().temperature; } yield BASE_PLASMA_TEMPERATURE; } From 69d1b580ad39e7d7e94d569cec858aa62aba2b30 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Tue, 1 Oct 2024 19:47:24 +0300 Subject: [PATCH 68/70] teeny tiny little crash --- .../gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java index 4781538698..17e3f43200 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -30,6 +30,7 @@ public abstract class WorldNet extends SavedData implements IGraphNet, GenericGraphNetPath.Provider { + @Getter protected final GraphNetBacker backer; @Getter @Setter @@ -118,7 +119,7 @@ public void load(@NotNull CompoundTag nbt) { } @Override - public GraphNetBacker getBacker() { - return backer; + public void setDirty() { + super.setDirty(); } } From fa98dff1769adc4f42bb6d121abd002cee7c66e7 Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Tue, 1 Oct 2024 20:03:18 +0300 Subject: [PATCH 69/70] actually fix the crash (it's caused by remapping) --- .../gtceu/api/graphnet/GraphNetBacker.java | 12 ++++++------ .../gregtechceu/gtceu/api/graphnet/IGraphNet.java | 2 +- .../gtceu/api/graphnet/worldnet/WorldNet.java | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java index 409518342b..d73a5ec5c6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/GraphNetBacker.java @@ -59,7 +59,7 @@ public void addNode(NetNode node) { GraphVertex vertex = new GraphVertex(node); getGraph().addVertex(vertex); this.vertexMap.put(node.getEquivalencyData(), vertex); - backedNet.setDirty(); + backedNet.setNetDirty(); } @Nullable @@ -82,7 +82,7 @@ public boolean removeNode(@Nullable NetNode node) { if (group != null) { group.splitNode(node); } else this.removeVertex(node.wrapper); - backedNet.setDirty(); + backedNet.setNetDirty(); return true; } else return false; } @@ -92,7 +92,7 @@ public void removeVertex(GraphVertex vertex) { if (this.getGraph().removeVertex(vertex)) { this.vertexMap.remove(vertex.wrapped.getEquivalencyData()); vertex.wrapped.onRemove(); - backedNet.setDirty(); + backedNet.setNetDirty(); } } @@ -103,7 +103,7 @@ public NetEdge addEdge(@NotNull NetNode source, @NotNull NetNode target, double if (graphEdge != null) { getGraph().setEdgeWeight(graphEdge, weight); NetGroup.mergeEdge(source, target); - backedNet.setDirty(); + backedNet.setNetDirty(); } return graphEdge == null ? null : graphEdge.wrapped; } @@ -126,7 +126,7 @@ public boolean removeEdge(@NotNull NetNode source, NetNode target) { public GraphEdge removeEdge(GraphVertex source, GraphVertex target) { GraphEdge edge = this.getGraph().removeEdge(source, target); if (edge != null) { - backedNet.setDirty(); + backedNet.setNetDirty(); } return edge; } @@ -134,7 +134,7 @@ public GraphEdge removeEdge(GraphVertex source, GraphVertex target) { @ApiStatus.Internal public boolean removeEdge(GraphEdge edge) { if (this.getGraph().removeEdge(edge)) { - backedNet.setDirty(); + backedNet.setNetDirty(); return true; } return false; diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java index 41a0aac219..2022ab1eb1 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/IGraphNet.java @@ -209,5 +209,5 @@ default NetEdge getNewEdge() { * Should only be used by the internal {@link GraphNetBacker} backing this graphnet. */ @ApiStatus.Internal - void setDirty(); + void setNetDirty(); } diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java index 17e3f43200..b117f9fbb0 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/worldnet/WorldNet.java @@ -119,7 +119,7 @@ public void load(@NotNull CompoundTag nbt) { } @Override - public void setDirty() { + public void setNetDirty() { super.setDirty(); } } From e11ff745340e1096f8a40c6a2392f3109789919a Mon Sep 17 00:00:00 2001 From: screret <68943070+screret@users.noreply.github.com> Date: Tue, 1 Oct 2024 20:11:16 +0300 Subject: [PATCH 70/70] fix null crash --- .../gtceu/api/graphnet/predicate/test/ItemTestObject.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java index 3f8c7feffc..9338568cd6 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java +++ b/src/main/java/com/gregtechceu/gtceu/api/graphnet/predicate/test/ItemTestObject.java @@ -31,7 +31,7 @@ public ItemTestObject(@NotNull ItemStack stack) { @Contract(" -> new") public ItemStack recombine() { ItemStack stack = new ItemStack(item, 1); - stack.setTag(tag.copy()); + stack.setTag(tag == null ? null : tag.copy()); return stack; } @@ -39,7 +39,7 @@ public ItemStack recombine() { public ItemStack recombine(int amount) { assert amount <= getStackLimit() && amount > 0; ItemStack stack = new ItemStack(item, amount); - stack.setTag(tag.copy()); + stack.setTag(tag == null ? null : tag.copy()); return stack; }