From 2ba83ad19d3f13931b192a960b2204ca90f62bc6 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 30 Jul 2022 21:28:49 +0200 Subject: [PATCH 01/23] Bump to v2.0.0-milestone.2.2 --- CHANGELOG.md | 2 ++ build.gradle | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fadd2f234..1cae72230 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [2.0.0-milestone.2.1] - 2022-07-30 + ### Changed - The Importer will now extract as much of 1 resource type as possible, according to the per tick transfer quota, at diff --git a/build.gradle b/build.gradle index 687b03ddc..42c4d91f7 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ allprojects { subprojects { group = 'com.refinedmods.refinedstorage2' - version = '2.0.0-milestone.2.1' + version = '2.0.0-milestone.2.2' if (System.getenv('GITHUB_SHA') != null) { version += '+' + System.getenv('GITHUB_SHA').substring(0, 7) From 9a766a53175004d0dcc7ec10e7215646f91641e1 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 30 Jul 2022 23:33:10 +0200 Subject: [PATCH 02/23] Connection changes. - All directional blocks no longer transmit a network signal out of the direction. - All directional blocks no longer accept a network signal from the facing direction. - Fixed network connection state not rebuilding after using Wrench on a directional block. --- CHANGELOG.md | 9 + .../api/network/NetworkBuilder.java | 23 +- .../network/AbstractNetworkBuilderTest.java | 113 ++++++ .../api/network/NetworkBuilderTest.java | 363 ++++++++++++++---- .../platform/api/PlatformApi.java | 2 + .../platform/api/PlatformApiProxy.java | 5 + .../node/PlatformNetworkNodeContainer.java | 7 + .../platform/common/PlatformApiImpl.java | 6 + .../block/AbstractDirectionalBlock.java | 10 + .../common/block/CableBlockSupport.java | 27 +- .../block/direction/BiDirectionType.java | 12 + .../common/block/direction/DirectionType.java | 2 + .../block/direction/DirectionTypeImpl.java | 5 + ...ternalNetworkNodeContainerBlockEntity.java | 39 +- .../block/entity/ImporterBlockEntity.java | 23 +- 15 files changed, 532 insertions(+), 114 deletions(-) create mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cae72230..a1fc73ca7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Changed + +- All directional blocks no longer transmit a network signal out of the direction. +- All directional blocks no longer accept a network signal from the facing direction. + +### Fixed + +- Fixed network connection state not rebuilding after using Wrench on a directional block. + ## [2.0.0-milestone.2.1] - 2022-07-30 ### Changed diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java index c25262d9b..168f5b78f 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java @@ -29,15 +29,17 @@ public boolean initialize(final NetworkNodeContainer container, final Connection connections.removedEntries(), "Cannot have removed entries when starting from empty existing connections" ); - mergeNetworksOfNodes(connectionProvider, container, connections.foundEntries()); + mergeNetworksOfNodes(connectionProvider, container, connections.foundEntries(), false); return true; } private void mergeNetworksOfNodes(final ConnectionProvider connectionProvider, final NetworkNodeContainer pivot, - final Set foundEntries) { - final Network pivotNetwork = findPivotNetworkForMerge(connectionProvider, pivot, foundEntries) - .orElseGet(() -> createNetwork(pivot)); + final Set foundEntries, + final boolean pivotAlreadyHasNetwork) { + final Network pivotNetwork = pivotAlreadyHasNetwork + ? CoreValidations.validateNotNull(pivot.getNode().getNetwork(), "Pivot must have network") + : findPivotNetworkForMerge(connectionProvider, pivot, foundEntries).orElseGet(() -> createNetwork(pivot)); final Set mergedNetworks = new HashSet<>(); @@ -113,6 +115,19 @@ public void remove(final NetworkNodeContainer container, final ConnectionProvide splitNetworks(connectionProvider, connections.removedEntries(), container); } + public void update(final NetworkNodeContainer container, final ConnectionProvider connectionProvider) { + final Network network = container.getNode().getNetwork(); + if (network == null) { + throw new IllegalStateException("Cannot update node that has no network yet"); + } + + final Set containers = network.getComponent(GraphNetworkComponent.class).getContainers(); + + final Connections connections = connectionProvider.findConnections(container, containers); + splitNetworks(connectionProvider, connections.removedEntries(), container); + mergeNetworksOfNodes(connectionProvider, container, connections.foundEntries(), true); + } + @Nullable private NetworkNodeContainer findPivotNodeForRemove(final ConnectionProvider connectionProvider, final NetworkNodeContainer removedContainer, diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderTest.java new file mode 100644 index 000000000..1fcfd2f12 --- /dev/null +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderTest.java @@ -0,0 +1,113 @@ +package com.refinedmods.refinedstorage2.api.network; + +import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; +import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; +import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.api.network.test.NetworkTestFixtures; +import com.refinedmods.refinedstorage2.api.network.test.SpyingNetworkNode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; + +import org.junit.jupiter.api.BeforeEach; + +abstract class AbstractNetworkBuilderTest { + protected NetworkBuilder sut; + private ComponentMapFactory componentMapFactory; + + @BeforeEach + void setUp() { + componentMapFactory = NetworkTestFixtures.NETWORK_COMPONENT_MAP_FACTORY.copy(); + componentMapFactory.addFactory(InterceptingNetworkComponent.class, + network -> new InterceptingNetworkComponent()); + sut = new NetworkBuilder(new NetworkFactory(componentMapFactory)); + } + + protected void clearTracking(final Network network) { + Objects.requireNonNull(network) + .getComponent(InterceptingNetworkComponent.class) + .clear(); + } + + protected NetworkNodeContainer createContainerWithNetwork() { + return createContainerWithNetwork(container -> new NetworkImpl(componentMapFactory)); + } + + protected static NetworkNodeContainer createContainerWithNetwork( + final Function networkFactory) { + final NetworkNodeContainer container = createContainer(); + final Network network = networkFactory.apply(container); + container.getNode().setNetwork(network); + network.addContainer(container); + return container; + } + + protected static NetworkNodeContainer createContainer() { + final SpyingNetworkNode node = new SpyingNetworkNode(0); + return () -> node; + } + + protected static List getAddedContainers(final Network network) { + return network.getComponent(InterceptingNetworkComponent.class).added; + } + + protected static List getRemovedContainers(final Network network) { + return network.getComponent(InterceptingNetworkComponent.class).removed; + } + + protected static List> getNetworkSplits(final Network network) { + return network.getComponent(InterceptingNetworkComponent.class).splits; + } + + protected static List getNetworkMerges(final Network network) { + return network.getComponent(InterceptingNetworkComponent.class).merges; + } + + protected static int getAmountRemoved(final Network network) { + return network.getComponent(InterceptingNetworkComponent.class).amountRemoved; + } + + private static class InterceptingNetworkComponent implements NetworkComponent { + private final List added = new ArrayList<>(); + private final List removed = new ArrayList<>(); + private final List> splits = new ArrayList<>(); + private final List merges = new ArrayList<>(); + private int amountRemoved = 0; + + @Override + public void onContainerAdded(final NetworkNodeContainer container) { + added.add(container); + } + + @Override + public void onContainerRemoved(final NetworkNodeContainer container) { + removed.add(container); + } + + @Override + public void onNetworkRemoved() { + amountRemoved++; + } + + @Override + public void onNetworkSplit(final Set networks) { + splits.add(networks); + } + + @Override + public void onNetworkMergedWith(final Network newMainNetwork) { + merges.add(newMainNetwork); + } + + public void clear() { + added.clear(); + removed.clear(); + splits.clear(); + merges.clear(); + amountRemoved = 0; + } + } +} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java index 942870121..8fe84cedc 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java @@ -1,36 +1,18 @@ package com.refinedmods.refinedstorage2.api.network; -import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; -import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; -import com.refinedmods.refinedstorage2.api.network.test.NetworkTestFixtures; -import com.refinedmods.refinedstorage2.api.network.test.SpyingNetworkNode; -import java.util.ArrayList; import java.util.List; import java.util.Set; -import java.util.function.Function; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -class NetworkBuilderTest { - ComponentMapFactory componentMapFactory; - NetworkBuilder sut; - - @BeforeEach - void setUp() { - componentMapFactory = NetworkTestFixtures.NETWORK_COMPONENT_MAP_FACTORY.copy(); - componentMapFactory.addFactory(InterceptingNetworkComponent.class, - network -> new InterceptingNetworkComponent()); - sut = new NetworkBuilder(new NetworkFactory(componentMapFactory)); - } - +class NetworkBuilderTest extends AbstractNetworkBuilderTest { @Test void shouldFormNetwork() { // Arrange @@ -436,74 +418,305 @@ void shouldRemoveNetwork() { assertThat(getAmountRemoved(network)).isEqualTo(1); } - private NetworkNodeContainer createContainerWithNetwork() { - return createContainerWithNetwork(container -> new NetworkImpl(componentMapFactory)); - } - - private static NetworkNodeContainer createContainerWithNetwork( - final Function networkFactory) { + @Test + void shouldNotBeAbleToUpdateWithoutNetworkAssigned() { + // Arrange final NetworkNodeContainer container = createContainer(); - final Network network = networkFactory.apply(container); - container.getNode().setNetwork(network); - network.addContainer(container); - return container; - } - private static NetworkNodeContainer createContainer() { - final SpyingNetworkNode node = new SpyingNetworkNode(0); - return () -> node; - } + // Act + final Executable action = () -> sut.update(container, new FakeConnectionProvider()); - private static List getAddedContainers(final Network network) { - return network.getComponent(InterceptingNetworkComponent.class).added; + // Assert + assertThrows(IllegalStateException.class, action); } - private static List getRemovedContainers(final Network network) { - return network.getComponent(InterceptingNetworkComponent.class).removed; + @Test + void shouldUpdateWithSoleContainer() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + + final Network originalNetwork = container1.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider.with(container1, unrelatedContainer); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(originalNetwork) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(container1); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); } - private static List> getNetworkSplits(final Network network) { - return network.getComponent(InterceptingNetworkComponent.class).splits; + @Test + void shouldSplitNetworkWhenUpdatingWithSoleContainerOnLeftSide() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final Network originalNetwork = container1.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + // Note: container 1 is no longer connected. + connectionProvider + .with(container1, container2, container3, unrelatedContainer) + .connect(container2, container3); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(originalNetwork) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(container2.getNode().getNetwork()) + .isSameAs(container3.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container1.getNode().getNetwork()) + .isNotSameAs(originalNetwork) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(container1); + assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container2, container3); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).containsExactly( + Set.of(container2.getNode().getNetwork()) + ); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).containsExactlyInAnyOrder( + container2, container3 + ); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container2.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder( + container2, container3 + ); + assertThat(getRemovedContainers(container2.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); } - private static List getNetworkMerges(final Network network) { - return network.getComponent(InterceptingNetworkComponent.class).merges; + @Test + void shouldSplitNetworkWhenUpdatingWithTwoContainersOnBothSides() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final Network originalNetwork = container1.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(container1, container2, container3, container4, unrelatedContainer) + .connect(container1, container2) + .connect(container3, container4); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(container2.getNode().getNetwork()) + .isSameAs(originalNetwork) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(container3.getNode().getNetwork()) + .isSameAs(container4.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container1.getNode().getNetwork()) + .isNotSameAs(originalNetwork) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container1, container2); + assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container3, container4); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).containsExactly( + Set.of(container3.getNode().getNetwork()) + ); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); } - private static int getAmountRemoved(final Network network) { - return network.getComponent(InterceptingNetworkComponent.class).amountRemoved; + @Test + void shouldSplitNetworkAndMergeAdditionalContainerWhenUpdating() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = createContainerWithNetwork(); + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container2.getNode().getNetwork()); + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container2.getNode().getNetwork()); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + // Previous state: [[container1], [container2, container3, container4]] + + connectionProvider + .with(container1, container2, container3, container4, unrelatedContainer) + .connect(container1, container2) + .connect(container3, container4); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + clearTracking(container2.getNode().getNetwork()); + + final Network originalNetworkContainer1 = container1.getNode().getNetwork(); + final Network originalNetworkContainer2 = container2.getNode().getNetwork(); + + // Act + sut.update(container2, connectionProvider); + + // Assert + assertThat(container2.getNode().getNetwork()) + .isSameAs(container1.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isSameAs(originalNetworkContainer2) + .isNotSameAs(originalNetworkContainer1) + .isNotNull(); + + assertThat(container3.getNode().getNetwork()) + .isSameAs(container4.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container2.getNode().getNetwork()) + .isNotSameAs(originalNetworkContainer2) + .isNotNull(); + + assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container1, container2); + assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container3, container4); + + assertThat(getNetworkSplits(container2.getNode().getNetwork())).containsExactly( + Set.of(container3.getNode().getNetwork()) + ); + assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactly( + container1 + ); + assertThat(getRemovedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); } - private static class InterceptingNetworkComponent implements NetworkComponent { - private final List added = new ArrayList<>(); - private final List removed = new ArrayList<>(); - private final List> splits = new ArrayList<>(); - private final List merges = new ArrayList<>(); - private int amountRemoved = 0; - - @Override - public void onContainerAdded(final NetworkNodeContainer container) { - added.add(container); - } - - @Override - public void onContainerRemoved(final NetworkNodeContainer container) { - removed.add(container); - } - - @Override - public void onNetworkRemoved() { - amountRemoved++; - } - - @Override - public void onNetworkSplit(final Set networks) { - splits.add(networks); - } - - @Override - public void onNetworkMergedWith(final Network newMainNetwork) { - merges.add(newMainNetwork); - } + @Test + void shouldNotUpdateAnythingWhenStateIsTheSame() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer container3 = createContainerWithNetwork(); + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container3.getNode().getNetwork()); + + final Network originalNetworkContainer1 = container1.getNode().getNetwork(); + final Network originalNetworkContainer3 = container3.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(container1, container2, container3, container4, unrelatedContainer) + .connect(container1, container2) + .connect(container3, container4); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + clearTracking(container3.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(container2.getNode().getNetwork()) + .isSameAs(originalNetworkContainer1) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(originalNetworkContainer3) + .isNotNull(); + + assertThat(container3.getNode().getNetwork()) + .isSameAs(container4.getNode().getNetwork()) + .isSameAs(originalNetworkContainer3) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(originalNetworkContainer1) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container1, container2); + assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container3, container4); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); } } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index 8a4099712..8e134ddbb 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -38,4 +38,6 @@ public interface PlatformApi { void requestNetworkNodeInitialization(NetworkNodeContainer container, Level level, Runnable callback); void requestNetworkNodeRemoval(NetworkNodeContainer container, Level level); + + void requestNetworkNodeUpdate(NetworkNodeContainer container, Level level); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index 9bf5d8d9e..6c2e7b09d 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -81,6 +81,11 @@ public void requestNetworkNodeRemoval(final NetworkNodeContainer container, fina ensureLoaded().requestNetworkNodeRemoval(container, level); } + @Override + public void requestNetworkNodeUpdate(final NetworkNodeContainer container, final Level level) { + ensureLoaded().requestNetworkNodeUpdate(container, level); + } + private PlatformApi ensureLoaded() { if (delegate == null) { throw new IllegalStateException("Platform API not loaded yet"); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/PlatformNetworkNodeContainer.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/PlatformNetworkNodeContainer.java index 3a5b04f59..05cfe852b 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/PlatformNetworkNodeContainer.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/PlatformNetworkNodeContainer.java @@ -3,12 +3,16 @@ import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.1") public interface PlatformNetworkNodeContainer extends NetworkNodeContainer { /** * Returns whether the already discovered node can perform an outgoing connection. + * Changes to this return value won't cause a rebuild of the network state. + * If the return value ever changes, call {@link + * com.refinedmods.refinedstorage2.platform.api.PlatformApi#requestNetworkNodeUpdate(NetworkNodeContainer, Level)}. * * @param direction the outgoing direction * @return whether the node can perform an outgoing connection @@ -17,6 +21,9 @@ public interface PlatformNetworkNodeContainer extends NetworkNodeContainer { /** * Returns whether the not yet discovered node can accept an incoming connection. + * Changes to this return value won't cause a rebuild of the network state. + * If the return value ever changes, call {@link + * com.refinedmods.refinedstorage2.platform.api.PlatformApi#requestNetworkNodeUpdate(NetworkNodeContainer, Level)}. * * @param direction the incoming direction * @return whether the node can accept an incoming connection diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index a26271d64..3e7b919e6 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -132,4 +132,10 @@ public void requestNetworkNodeRemoval(final NetworkNodeContainer container, fina final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); networkBuilder.remove(container, connectionProvider); } + + @Override + public void requestNetworkNodeUpdate(final NetworkNodeContainer container, final Level level) { + final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); + networkBuilder.update(container, connectionProvider); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractDirectionalBlock.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractDirectionalBlock.java index 0206e3134..34a0bc0c7 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractDirectionalBlock.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractDirectionalBlock.java @@ -4,6 +4,7 @@ import javax.annotation.Nullable; +import net.minecraft.core.Direction; import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.block.Block; @@ -58,4 +59,13 @@ public T getDirection(@Nullable final BlockState state) { ? state.getValue(directionProperty) : null; } + + @Nullable + public Direction extractDirection(@Nullable final BlockState state) { + final T direction = getDirection(state); + if (direction == null) { + return null; + } + return getDirectionType().extractDirection(direction); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java index 4b1545cb9..dc6f87842 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.block; -import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -77,12 +77,12 @@ static BlockState getState(final BlockState currentState, final LevelAccessor world, final BlockPos pos, @Nullable final Direction blacklistedDirection) { - final boolean north = hasConnection(world, pos, Direction.NORTH, blacklistedDirection); - final boolean east = hasConnection(world, pos, Direction.EAST, blacklistedDirection); - final boolean south = hasConnection(world, pos, Direction.SOUTH, blacklistedDirection); - final boolean west = hasConnection(world, pos, Direction.WEST, blacklistedDirection); - final boolean up = hasConnection(world, pos, Direction.UP, blacklistedDirection); - final boolean down = hasConnection(world, pos, Direction.DOWN, blacklistedDirection); + final boolean north = hasVisualConnection(world, pos, Direction.NORTH, blacklistedDirection); + final boolean east = hasVisualConnection(world, pos, Direction.EAST, blacklistedDirection); + final boolean south = hasVisualConnection(world, pos, Direction.SOUTH, blacklistedDirection); + final boolean west = hasVisualConnection(world, pos, Direction.WEST, blacklistedDirection); + final boolean up = hasVisualConnection(world, pos, Direction.UP, blacklistedDirection); + final boolean down = hasVisualConnection(world, pos, Direction.DOWN, blacklistedDirection); return currentState .setValue(NORTH, north) @@ -93,14 +93,17 @@ static BlockState getState(final BlockState currentState, .setValue(DOWN, down); } - private static boolean hasConnection(final LevelAccessor world, - final BlockPos pos, - final Direction direction, - @Nullable final Direction blacklistedDirection) { + private static boolean hasVisualConnection(final LevelAccessor world, + final BlockPos pos, + final Direction direction, + @Nullable final Direction blacklistedDirection) { if (direction == blacklistedDirection) { return false; } final BlockPos offsetPos = pos.offset(direction.getNormal()); - return world.getBlockEntity(offsetPos) instanceof NetworkNodeContainer; + if (!(world.getBlockEntity(offsetPos) instanceof PlatformNetworkNodeContainer container)) { + return false; + } + return container.canAcceptIncomingConnection(direction.getOpposite()); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/BiDirectionType.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/BiDirectionType.java index 6a4effeb9..c82b89d7b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/BiDirectionType.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/BiDirectionType.java @@ -23,6 +23,18 @@ public BiDirection getDefault() { return BiDirection.NORTH; } + @Override + public Direction extractDirection(final BiDirection direction) { + return switch (direction) { + case NORTH -> Direction.NORTH; + case EAST -> Direction.EAST; + case SOUTH -> Direction.SOUTH; + case WEST -> Direction.WEST; + case UP_NORTH, UP_EAST, UP_SOUTH, UP_WEST -> Direction.UP; + case DOWN_NORTH, DOWN_EAST, DOWN_SOUTH, DOWN_WEST -> Direction.DOWN; + }; + } + @Override public BiDirection getDirection(final Direction clickedFace, final Direction playerFacing, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionType.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionType.java index 58ed2c06e..539f34119 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionType.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionType.java @@ -9,6 +9,8 @@ public interface DirectionType & StringRepresentable> { T getDefault(); + Direction extractDirection(T direction); + T getDirection(Direction clickedFace, Direction playerFacing, float playerPitch); T rotate(T direction); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionTypeImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionTypeImpl.java index 26b1c7698..d4b743913 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionTypeImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/direction/DirectionTypeImpl.java @@ -21,6 +21,11 @@ public Direction getDefault() { return Direction.NORTH; } + @Override + public Direction extractDirection(final Direction direction) { + return direction; + } + @Override public Direction getDirection(final Direction clickedFace, final Direction playerFacing, final float playerPitch) { return clickedFace.getOpposite(); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java index a6b38ab70..857f2bec2 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java @@ -1,12 +1,15 @@ package com.refinedmods.refinedstorage2.platform.common.block.entity; import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.blockentity.AbstractNetworkNodeContainerBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.block.AbstractDirectionalBlock; import com.refinedmods.refinedstorage2.platform.common.util.RedstoneMode; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -14,7 +17,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -// TODO: this should just block everything outgoing if directional, should also work when wrenching. public abstract class AbstractInternalNetworkNodeContainerBlockEntity extends AbstractNetworkNodeContainerBlockEntity { private static final Logger LOGGER = LogManager.getLogger(); @@ -105,4 +107,39 @@ public void setRedstoneMode(final RedstoneMode redstoneMode) { this.redstoneMode = redstoneMode; setChanged(); } + + @Override + public boolean canPerformOutgoingConnection(final Direction direction) { + final Direction myDirection = getDirection(); + if (myDirection == null) { + return true; + } + return myDirection != direction; + } + + @Override + public boolean canAcceptIncomingConnection(final Direction direction) { + final Direction myDirection = getDirection(); + if (myDirection == null) { + return true; + } + return myDirection != direction; + } + + @Override + public void setBlockState(final BlockState newBlockState) { + super.setBlockState(newBlockState); + if (getNode().getNetwork() != null && level != null && !level.isClientSide()) { + PlatformApi.INSTANCE.requestNetworkNodeUpdate(this, level); + } + } + + @Nullable + protected final Direction getDirection() { + final BlockState blockState = getBlockState(); + if (!(blockState.getBlock() instanceof AbstractDirectionalBlock directionalBlock)) { + return null; + } + return directionalBlock.extractDirection(blockState); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index e1b155879..e8c5f500d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -8,7 +8,6 @@ import com.refinedmods.refinedstorage2.platform.api.network.node.importer.ImporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.resource.FuzzyModeNormalizer; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.block.ImporterBlock; import com.refinedmods.refinedstorage2.platform.common.containermenu.ImporterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; import com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.ResourceFilterContainer; @@ -28,7 +27,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -91,7 +89,7 @@ public void setLevel(final Level level) { } private void updateTransferStrategy(final ServerLevel serverLevel) { - final Direction direction = getMyDirection(); + final Direction direction = getDirection(); if (direction == null) { LOGGER.warn( "Could not extract direction from importer block at {}, state is {}", @@ -118,25 +116,6 @@ private CompositeImporterTransferStrategy createStrategy(final ServerLevel serve return new CompositeImporterTransferStrategy(strategies); } - @Override - public boolean canPerformOutgoingConnection(final Direction direction) { - return getMyDirection() != direction; - } - - @Override - public boolean canAcceptIncomingConnection(final Direction direction) { - return getMyDirection() != direction; - } - - @Nullable - private Direction getMyDirection() { - final Block block = getBlockState().getBlock(); - if (!(block instanceof ImporterBlock importerBlock)) { - return null; - } - return importerBlock.getDirection(getBlockState()); - } - @Override public void saveAdditional(final CompoundTag tag) { super.saveAdditional(tag); From faa77737f32ba5cafef09c43b843db5abfc93b4f Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 30 Jul 2022 23:43:51 +0200 Subject: [PATCH 03/23] Extract interface out of NetworkBuilder. --- .../api/network/NetworkBuilder.java | 205 +---- .../api/network/NetworkBuilderImpl.java | 179 +++++ ...va => AbstractNetworkBuilderImplTest.java} | 4 +- .../NetworkBuilderImplInitializeTest.java | 184 +++++ .../network/NetworkBuilderImplRemoveTest.java | 246 ++++++ .../network/NetworkBuilderImplUpdateTest.java | 316 ++++++++ .../api/network/NetworkBuilderTest.java | 722 ------------------ .../platform/common/PlatformApiImpl.java | 4 +- 8 files changed, 964 insertions(+), 896 deletions(-) create mode 100644 refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImpl.java rename refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/{AbstractNetworkBuilderTest.java => AbstractNetworkBuilderImplTest.java} (96%) create mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplInitializeTest.java create mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplRemoveTest.java create mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplUpdateTest.java delete mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java index 168f5b78f..d6e1cccb7 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java @@ -1,176 +1,39 @@ package com.refinedmods.refinedstorage2.api.network; -import com.refinedmods.refinedstorage2.api.core.CoreValidations; -import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; -import com.refinedmods.refinedstorage2.api.network.node.NetworkNode; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; -import java.util.Collections; -import java.util.HashSet; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -public class NetworkBuilder { - private final NetworkFactory networkFactory; - - public NetworkBuilder(final NetworkFactory networkFactory) { - this.networkFactory = networkFactory; - } - - public boolean initialize(final NetworkNodeContainer container, final ConnectionProvider connectionProvider) { - if (container.getNode().getNetwork() != null) { - return false; - } - final Connections connections = connectionProvider.findConnections(container, Collections.emptySet()); - CoreValidations.validateEmpty( - connections.removedEntries(), - "Cannot have removed entries when starting from empty existing connections" - ); - mergeNetworksOfNodes(connectionProvider, container, connections.foundEntries(), false); - return true; - } - - private void mergeNetworksOfNodes(final ConnectionProvider connectionProvider, - final NetworkNodeContainer pivot, - final Set foundEntries, - final boolean pivotAlreadyHasNetwork) { - final Network pivotNetwork = pivotAlreadyHasNetwork - ? CoreValidations.validateNotNull(pivot.getNode().getNetwork(), "Pivot must have network") - : findPivotNetworkForMerge(connectionProvider, pivot, foundEntries).orElseGet(() -> createNetwork(pivot)); - - final Set mergedNetworks = new HashSet<>(); - - for (final NetworkNodeContainer entry : foundEntries) { - final NetworkNode entryNode = entry.getNode(); - final boolean isNotInPivotNetwork = !pivotNetwork.getComponent(GraphNetworkComponent.class) - .getContainers().contains(entry); - if (isNotInPivotNetwork) { - final Network mergedNetwork = mergeNetworkOfNode(pivotNetwork, entry, entryNode); - if (mergedNetwork != null) { - mergedNetworks.add(mergedNetwork); - } - } - } - - mergedNetworks.forEach(mn -> mn.merge(pivotNetwork)); - } - - @Nullable - private Network mergeNetworkOfNode(final Network newNetwork, - final NetworkNodeContainer entry, - final NetworkNode entryNode) { - final Network oldNetwork = entryNode.getNetwork(); - entryNode.setNetwork(newNetwork); - newNetwork.addContainer(entry); - return oldNetwork; - } - - private Network createNetwork(final NetworkNodeContainer container) { - final Network network = networkFactory.create(); - container.getNode().setNetwork(network); - network.addContainer(container); - return network; - } - - private Optional findPivotNetworkForMerge(final ConnectionProvider connectionProvider, - final NetworkNodeContainer addedContainer, - final Set foundEntries) { - for (final NetworkNodeContainer entry : connectionProvider.sort(foundEntries)) { - if (entry == addedContainer) { - continue; - } - final Network entryNetwork = entry.getNode().getNetwork(); - if (entryNetwork != null) { - return Optional.of(entryNetwork); - } - } - return Optional.empty(); - } - - public void remove(final NetworkNodeContainer container, final ConnectionProvider connectionProvider) { - final Network network = container.getNode().getNetwork(); - if (network == null) { - throw new IllegalStateException("Cannot remove node that has no network yet"); - } - - final Set containers = network.getComponent(GraphNetworkComponent.class).getContainers(); - - final NetworkNodeContainer pivot = findPivotNodeForRemove(connectionProvider, container, containers); - - if (pivot == null) { - network.remove(); - container.getNode().setNetwork(null); - return; - } - - final Connections connections = connectionProvider.findConnections(pivot, containers); - CoreValidations.validateContains( - connections.removedEntries(), - container, - "The removed container should be present in the removed entries, but isn't" - ); - splitNetworks(connectionProvider, connections.removedEntries(), container); - } - - public void update(final NetworkNodeContainer container, final ConnectionProvider connectionProvider) { - final Network network = container.getNode().getNetwork(); - if (network == null) { - throw new IllegalStateException("Cannot update node that has no network yet"); - } - - final Set containers = network.getComponent(GraphNetworkComponent.class).getContainers(); - - final Connections connections = connectionProvider.findConnections(container, containers); - splitNetworks(connectionProvider, connections.removedEntries(), container); - mergeNetworksOfNodes(connectionProvider, container, connections.foundEntries(), true); - } - - @Nullable - private NetworkNodeContainer findPivotNodeForRemove(final ConnectionProvider connectionProvider, - final NetworkNodeContainer removedContainer, - final Set containers) { - for (final NetworkNodeContainer entry : connectionProvider.sort(containers)) { - if (!entry.equals(removedContainer)) { - return entry; - } - } - return null; - } - - private void splitNetworks(final ConnectionProvider connectionProvider, - final Set removedEntries, - final NetworkNodeContainer removedEntry) { - final Network networkOfRemovedNode = removedEntry.getNode().getNetwork(); - if (networkOfRemovedNode == null) { - throw new IllegalStateException("Network of removed node cannot be empty"); - } - - removedEntries.forEach(e -> { - if (e.getNode().getNetwork() == null) { - throw new IllegalStateException("Network of resulting removed node cannot be empty"); - } - e.getNode().getNetwork().removeContainer(e); - e.getNode().setNetwork(null); - }); - - final Set networksResultingOfSplit = removedEntries - .stream() - .filter(e -> !e.equals(removedEntry)) - .map(e -> { - final boolean establishedNetwork = initialize(e, connectionProvider); - if (establishedNetwork) { - return e.getNode().getNetwork(); - } - return null; - }) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - - if (!networksResultingOfSplit.isEmpty()) { - networkOfRemovedNode.split(networksResultingOfSplit); - } - } +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") +public interface NetworkBuilder { + /** + * Initialized a not yet connected network node container. + * If the network node already has an associated {@link Network}, calling this will do nothing. + * This will perform a merge operation. + * + * @param container the container + * @param connectionProvider the connection provider + * @return true if the container has no network yet, and the initialization succeeded, false otherwise + */ + boolean initialize(NetworkNodeContainer container, ConnectionProvider connectionProvider); + + /** + * Removes a container from its network. + * Will remove the network if the container is the last container in the network, or otherwise it performs + * a split operation. + * + * @param container the container + * @param connectionProvider the connection provider + */ + void remove(NetworkNodeContainer container, ConnectionProvider connectionProvider); + + /** + * Updates the network associated with the given container. Makes the network state adapt to connection changes + * of an already connected container. + * Will perform split and/or merge operations. + * + * @param container the container + * @param connectionProvider the connection provider + */ + void update(NetworkNodeContainer container, ConnectionProvider connectionProvider); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImpl.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImpl.java new file mode 100644 index 000000000..dd5405c2a --- /dev/null +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImpl.java @@ -0,0 +1,179 @@ +package com.refinedmods.refinedstorage2.api.network; + +import com.refinedmods.refinedstorage2.api.core.CoreValidations; +import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.node.NetworkNode; +import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.Nullable; + +public class NetworkBuilderImpl implements NetworkBuilder { + private final NetworkFactory networkFactory; + + public NetworkBuilderImpl(final NetworkFactory networkFactory) { + this.networkFactory = networkFactory; + } + + @Override + public boolean initialize(final NetworkNodeContainer container, final ConnectionProvider connectionProvider) { + if (container.getNode().getNetwork() != null) { + return false; + } + final Connections connections = connectionProvider.findConnections(container, Collections.emptySet()); + CoreValidations.validateEmpty( + connections.removedEntries(), + "Cannot have removed entries when starting from empty existing connections" + ); + mergeNetworksOfNodes(connectionProvider, container, connections.foundEntries(), false); + return true; + } + + private void mergeNetworksOfNodes(final ConnectionProvider connectionProvider, + final NetworkNodeContainer pivot, + final Set foundEntries, + final boolean pivotAlreadyHasNetwork) { + final Network pivotNetwork = pivotAlreadyHasNetwork + ? CoreValidations.validateNotNull(pivot.getNode().getNetwork(), "Pivot must have network") + : findPivotNetworkForMerge(connectionProvider, pivot, foundEntries).orElseGet(() -> createNetwork(pivot)); + + final Set mergedNetworks = new HashSet<>(); + + for (final NetworkNodeContainer entry : foundEntries) { + final NetworkNode entryNode = entry.getNode(); + final boolean isNotInPivotNetwork = !pivotNetwork.getComponent(GraphNetworkComponent.class) + .getContainers().contains(entry); + if (isNotInPivotNetwork) { + final Network mergedNetwork = mergeNetworkOfNode(pivotNetwork, entry, entryNode); + if (mergedNetwork != null) { + mergedNetworks.add(mergedNetwork); + } + } + } + + mergedNetworks.forEach(mn -> mn.merge(pivotNetwork)); + } + + @Nullable + private Network mergeNetworkOfNode(final Network newNetwork, + final NetworkNodeContainer entry, + final NetworkNode entryNode) { + final Network oldNetwork = entryNode.getNetwork(); + entryNode.setNetwork(newNetwork); + newNetwork.addContainer(entry); + return oldNetwork; + } + + private Network createNetwork(final NetworkNodeContainer container) { + final Network network = networkFactory.create(); + container.getNode().setNetwork(network); + network.addContainer(container); + return network; + } + + private Optional findPivotNetworkForMerge(final ConnectionProvider connectionProvider, + final NetworkNodeContainer addedContainer, + final Set foundEntries) { + for (final NetworkNodeContainer entry : connectionProvider.sort(foundEntries)) { + if (entry == addedContainer) { + continue; + } + final Network entryNetwork = entry.getNode().getNetwork(); + if (entryNetwork != null) { + return Optional.of(entryNetwork); + } + } + return Optional.empty(); + } + + @Override + public void remove(final NetworkNodeContainer container, final ConnectionProvider connectionProvider) { + final Network network = container.getNode().getNetwork(); + if (network == null) { + throw new IllegalStateException("Cannot remove node that has no network yet"); + } + + final Set containers = network.getComponent(GraphNetworkComponent.class).getContainers(); + + final NetworkNodeContainer pivot = findPivotNodeForRemove(connectionProvider, container, containers); + + if (pivot == null) { + network.remove(); + container.getNode().setNetwork(null); + return; + } + + final Connections connections = connectionProvider.findConnections(pivot, containers); + CoreValidations.validateContains( + connections.removedEntries(), + container, + "The removed container should be present in the removed entries, but isn't" + ); + splitNetworks(connectionProvider, connections.removedEntries(), container); + } + + @Override + public void update(final NetworkNodeContainer container, final ConnectionProvider connectionProvider) { + final Network network = container.getNode().getNetwork(); + if (network == null) { + throw new IllegalStateException("Cannot update node that has no network yet"); + } + + final Set containers = network.getComponent(GraphNetworkComponent.class).getContainers(); + + final Connections connections = connectionProvider.findConnections(container, containers); + splitNetworks(connectionProvider, connections.removedEntries(), container); + mergeNetworksOfNodes(connectionProvider, container, connections.foundEntries(), true); + } + + @Nullable + private NetworkNodeContainer findPivotNodeForRemove(final ConnectionProvider connectionProvider, + final NetworkNodeContainer removedContainer, + final Set containers) { + for (final NetworkNodeContainer entry : connectionProvider.sort(containers)) { + if (!entry.equals(removedContainer)) { + return entry; + } + } + return null; + } + + private void splitNetworks(final ConnectionProvider connectionProvider, + final Set removedEntries, + final NetworkNodeContainer removedEntry) { + final Network networkOfRemovedNode = removedEntry.getNode().getNetwork(); + if (networkOfRemovedNode == null) { + throw new IllegalStateException("Network of removed node cannot be empty"); + } + + removedEntries.forEach(e -> { + if (e.getNode().getNetwork() == null) { + throw new IllegalStateException("Network of resulting removed node cannot be empty"); + } + e.getNode().getNetwork().removeContainer(e); + e.getNode().setNetwork(null); + }); + + final Set networksResultingOfSplit = removedEntries + .stream() + .filter(e -> !e.equals(removedEntry)) + .map(e -> { + final boolean establishedNetwork = initialize(e, connectionProvider); + if (establishedNetwork) { + return e.getNode().getNetwork(); + } + return null; + }) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + + if (!networksResultingOfSplit.isEmpty()) { + networkOfRemovedNode.split(networksResultingOfSplit); + } + } +} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderImplTest.java similarity index 96% rename from refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderTest.java rename to refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderImplTest.java index 1fcfd2f12..12b3943a6 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/AbstractNetworkBuilderImplTest.java @@ -14,7 +14,7 @@ import org.junit.jupiter.api.BeforeEach; -abstract class AbstractNetworkBuilderTest { +abstract class AbstractNetworkBuilderImplTest { protected NetworkBuilder sut; private ComponentMapFactory componentMapFactory; @@ -23,7 +23,7 @@ void setUp() { componentMapFactory = NetworkTestFixtures.NETWORK_COMPONENT_MAP_FACTORY.copy(); componentMapFactory.addFactory(InterceptingNetworkComponent.class, network -> new InterceptingNetworkComponent()); - sut = new NetworkBuilder(new NetworkFactory(componentMapFactory)); + sut = new NetworkBuilderImpl(new NetworkFactory(componentMapFactory)); } protected void clearTracking(final Network network) { diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplInitializeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplInitializeTest.java new file mode 100644 index 000000000..b1a025f2f --- /dev/null +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplInitializeTest.java @@ -0,0 +1,184 @@ +package com.refinedmods.refinedstorage2.api.network; + +import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class NetworkBuilderImplInitializeTest extends AbstractNetworkBuilderImplTest { + @Test + void shouldFormNetwork() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container = createContainer(); + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider.with(container, unrelatedContainer); + + // Act + sut.initialize(container, connectionProvider); + + // Assert + assertThat(container.getNode().getNetwork()).isNotNull(); + assertThat(container.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(container); + + assertThat(getAddedContainers(container.getNode().getNetwork())).containsExactly(container); + assertThat(getRemovedContainers(container.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container.getNode().getNetwork())).isZero(); + assertThat(getNetworkMerges(container.getNode().getNetwork())).isEmpty(); + + assertThat(unrelatedContainer.getNode().getNetwork()) + .isNotNull() + .isNotEqualTo(container.getNode().getNetwork()); + assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(unrelatedContainer); + } + + @Test + void shouldJoinExistingNetwork() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer existingContainer1 = createContainerWithNetwork(); + final NetworkNodeContainer existingContainer2 = + createContainerWithNetwork(container -> existingContainer1.getNode().getNetwork()); + final NetworkNodeContainer newContainer = createContainer(); + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(existingContainer1) + .with(existingContainer2) + .with(newContainer) + .with(unrelatedContainer) + .connect(existingContainer1, existingContainer2) + .connect(existingContainer1, newContainer); + + // Act + sut.initialize(newContainer, connectionProvider); + + // Assert + final Network expectedNetwork = existingContainer1.getNode().getNetwork(); + assertThat(expectedNetwork).isNotNull(); + + assertThat(existingContainer1.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(existingContainer2.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(newContainer.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(expectedNetwork.getComponent(GraphNetworkComponent.class).getContainers()).containsExactlyInAnyOrder( + existingContainer1, + existingContainer2, + newContainer + ); + + assertThat(getAddedContainers(expectedNetwork)).containsExactly( + existingContainer1, + existingContainer2, + newContainer + ); + assertThat(getRemovedContainers(expectedNetwork)).isEmpty(); + assertThat(getAmountRemoved(expectedNetwork)).isZero(); + assertThat(getNetworkMerges(expectedNetwork)).isEmpty(); + + assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull().isNotEqualTo(expectedNetwork); + assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(unrelatedContainer); + } + + @Test + void shouldMergeWithExistingNetworks() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer existingContainer0 = createContainerWithNetwork(); + final NetworkNodeContainer existingContainer1 = + createContainerWithNetwork(container -> existingContainer0.getNode().getNetwork()); + final NetworkNodeContainer existingContainer2 = createContainerWithNetwork(); + final Network initialNetworkOfExistingContainer2 = existingContainer2.getNode().getNetwork(); + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + final NetworkNodeContainer newContainer = createContainer(); + + connectionProvider + .with(existingContainer0, existingContainer1, existingContainer2, unrelatedContainer, newContainer) + .connect(existingContainer0, existingContainer1) + .connect(existingContainer2, newContainer) + .connect(newContainer, existingContainer1); + + // Act + sut.initialize(newContainer, connectionProvider); + + // Assert + final Network expectedNetwork = existingContainer1.getNode().getNetwork(); + assertThat(expectedNetwork).isNotNull(); + + assertThat(initialNetworkOfExistingContainer2).isNotNull(); + assertThat(getNetworkMerges(initialNetworkOfExistingContainer2)).containsExactlyInAnyOrder(expectedNetwork); + + assertThat(existingContainer1.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(existingContainer2.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(existingContainer0.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(newContainer.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(expectedNetwork.getComponent(GraphNetworkComponent.class).getContainers()).containsExactlyInAnyOrder( + existingContainer1, + existingContainer2, + existingContainer0, + newContainer + ); + + assertThat(getAddedContainers(expectedNetwork)) + .containsExactlyInAnyOrder(existingContainer2, newContainer, existingContainer1, existingContainer0); + assertThat(getRemovedContainers(expectedNetwork)).isEmpty(); + assertThat(getAmountRemoved(expectedNetwork)).isZero(); + assertThat(getNetworkMerges(expectedNetwork)).isEmpty(); + + assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull().isNotEqualTo(expectedNetwork); + assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(unrelatedContainer); + } + + @Test + void shouldFormNetworkIfThereAreNeighborsWithoutNetwork() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + final NetworkNodeContainer container1 = createContainer(); + final NetworkNodeContainer container2 = createContainer(); + final NetworkNodeContainer container3 = createContainer(); + + connectionProvider.with(container1, container2, container3) + .connect(container1, container2) + .connect(container2, container3); + + // Act + sut.initialize(container1, connectionProvider); + sut.initialize(container2, connectionProvider); + sut.initialize(container3, connectionProvider); + + // Assert + final Network expectedNetwork = container1.getNode().getNetwork(); + assertThat(expectedNetwork).isNotNull(); + + assertThat(container1.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(container2.getNode().getNetwork()).isEqualTo(expectedNetwork); + assertThat(container3.getNode().getNetwork()).isEqualTo(expectedNetwork); + + assertThat(expectedNetwork.getComponent(GraphNetworkComponent.class).getContainers()).containsExactlyInAnyOrder( + container1, + container2, + container3 + ); + + assertThat(getNetworkMerges(expectedNetwork)).isEmpty(); + assertThat(getAddedContainers(expectedNetwork)).containsExactlyInAnyOrder(container1, container2, container3); + assertThat(getRemovedContainers(expectedNetwork)).isEmpty(); + assertThat(getAmountRemoved(expectedNetwork)).isZero(); + + assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull().isNotEqualTo(expectedNetwork); + assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(unrelatedContainer); + } +} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplRemoveTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplRemoveTest.java new file mode 100644 index 000000000..b3661cdf7 --- /dev/null +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplRemoveTest.java @@ -0,0 +1,246 @@ +package com.refinedmods.refinedstorage2.api.network; + +import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; + +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NetworkBuilderImplRemoveTest extends AbstractNetworkBuilderImplTest { + @Test + void shouldNotBeAbleToRemoveWithoutNetworkAssigned() { + // Arrange + final NetworkNodeContainer container = createContainer(); + + // Act + final Executable action = () -> sut.remove(container, new FakeConnectionProvider()); + + // Assert + assertThrows(IllegalStateException.class, action); + } + + @Test + void shouldSplitNetwork() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(container1, container2, container3, unrelatedContainer) + .connect(container2, container3); + + // Act + sut.remove(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()).isNull(); + + assertThat(container2.getNode().getNetwork()) + .isSameAs(container3.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container2, container3); + + assertThat(getNetworkSplits(container2.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactly( + container1, + container2, + container3 + ); + assertThat(getRemovedContainers(container2.getNode().getNetwork())).containsExactly(container1); + assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); + } + + @Test + void shouldSplitNetworkInTwo() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container5 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(container5, container4, container3, container2, container1, unrelatedContainer) + .connect(container1, container2) + .connect(container4, container5); + + // Act + sut.remove(container3, connectionProvider); + + // Assert + assertThat(container3.getNode().getNetwork()).isNull(); + + assertThat(container1.getNode().getNetwork()) + .isSameAs(container2.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container4.getNode().getNetwork()) + .isNotSameAs(container5.getNode().getNetwork()); + + assertThat(container1.getNode().getNetwork()).isNotNull(); + assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container1.getNode().getNetwork())) + .containsExactlyInAnyOrder(container1, container2); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container1, container2); + + assertThat(container4.getNode().getNetwork()) + .isSameAs(container5.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container1.getNode().getNetwork()) + .isNotSameAs(container2.getNode().getNetwork()) + .isNotNull(); + + final List> splits = getNetworkSplits(container4.getNode().getNetwork()); + assertThat(splits).hasSize(1); + assertThat(splits.get(0)).containsExactlyInAnyOrder(container1.getNode().getNetwork()); + + assertThat(getAddedContainers(container4.getNode().getNetwork())) + .containsExactlyInAnyOrder(container1, container2, container3, container4, container5); + assertThat(getRemovedContainers(container4.getNode().getNetwork())) + .containsExactlyInAnyOrder(container1, container2, container3); + assertThat(getAmountRemoved(container4.getNode().getNetwork())).isZero(); + + assertThat(container4.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container4, container5); + } + + @Test + void shouldSplitNetworkInThree() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container5 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(unrelatedContainer, container5, container4, container3, container2, container1) + .connect(container4, container5); + + // Act + sut.remove(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()).isNull(); + + assertThat(container2.getNode().getNetwork()) + .isNotSameAs(container3.getNode().getNetwork()) + .isNotSameAs(container4.getNode().getNetwork()) + .isNotSameAs(container5.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(getNetworkSplits(container2.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder(container2); + assertThat(getRemovedContainers(container2.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); + + assertThat(container3.getNode().getNetwork()) + .isNotSameAs(container2.getNode().getNetwork()) + .isNotSameAs(container4.getNode().getNetwork()) + .isNotSameAs(container5.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder(container3); + assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); + + assertThat(container4.getNode().getNetwork()) + .isNotSameAs(container2.getNode().getNetwork()) + .isNotSameAs(container3.getNode().getNetwork()) + .isSameAs(container5.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + final List> splits = getNetworkSplits(container4.getNode().getNetwork()); + assertThat(splits).hasSize(1); + assertThat(splits.get(0)) + .containsExactlyInAnyOrder(container2.getNode().getNetwork(), container3.getNode().getNetwork()); + + assertThat(getAddedContainers(container4.getNode().getNetwork())) + .containsExactlyInAnyOrder(container1, container2, container3, container4, container5); + assertThat(getRemovedContainers(container4.getNode().getNetwork())) + .containsExactlyInAnyOrder(container1, container2, container3); + assertThat(getAmountRemoved(container4.getNode().getNetwork())).isZero(); + + assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(container2); + + assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(container3); + + assertThat(container4.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container4, container5); + } + + @Test + void shouldRemoveNetwork() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container = createContainerWithNetwork(); + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider.with(container, unrelatedContainer); + + final Network network = container.getNode().getNetwork(); + + // Act + sut.remove(container, connectionProvider); + + // Assert + assertThat(container.getNode().getNetwork()).isNull(); + + assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull(); + assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(unrelatedContainer); + + assertThat(network).isNotNull(); + assertThat(getNetworkSplits(network)).isEmpty(); + assertThat(getAddedContainers(network)).containsExactly(container); + assertThat(getRemovedContainers(network)).isEmpty(); + assertThat(getAmountRemoved(network)).isEqualTo(1); + } +} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplUpdateTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplUpdateTest.java new file mode 100644 index 000000000..f1752cd56 --- /dev/null +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderImplUpdateTest.java @@ -0,0 +1,316 @@ +package com.refinedmods.refinedstorage2.api.network; + +import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; + +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NetworkBuilderImplUpdateTest extends AbstractNetworkBuilderImplTest { + @Test + void shouldNotBeAbleToUpdateWithoutNetworkAssigned() { + // Arrange + final NetworkNodeContainer container = createContainer(); + + // Act + final Executable action = () -> sut.update(container, new FakeConnectionProvider()); + + // Assert + assertThrows(IllegalStateException.class, action); + } + + @Test + void shouldUpdateWithSoleContainer() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + + final Network originalNetwork = container1.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider.with(container1, unrelatedContainer); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(originalNetwork) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(container1); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + } + + @Test + void shouldSplitNetworkWhenUpdatingWithSoleContainerOnLeftSide() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final Network originalNetwork = container1.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + // Note: container 1 is no longer connected. + connectionProvider + .with(container1, container2, container3, unrelatedContainer) + .connect(container2, container3); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(originalNetwork) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(container2.getNode().getNetwork()) + .isSameAs(container3.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container1.getNode().getNetwork()) + .isNotSameAs(originalNetwork) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactly(container1); + assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container2, container3); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).containsExactly( + Set.of(container2.getNode().getNetwork()) + ); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).containsExactlyInAnyOrder( + container2, container3 + ); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container2.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder( + container2, container3 + ); + assertThat(getRemovedContainers(container2.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); + } + + @Test + void shouldSplitNetworkWhenUpdatingWithTwoContainersOnBothSides() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final Network originalNetwork = container1.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(container1, container2, container3, container4, unrelatedContainer) + .connect(container1, container2) + .connect(container3, container4); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(container2.getNode().getNetwork()) + .isSameAs(originalNetwork) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotNull(); + + assertThat(container3.getNode().getNetwork()) + .isSameAs(container4.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container1.getNode().getNetwork()) + .isNotSameAs(originalNetwork) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container1, container2); + assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container3, container4); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).containsExactly( + Set.of(container3.getNode().getNetwork()) + ); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); + } + + @Test + void shouldSplitNetworkAndMergeAdditionalContainerWhenUpdating() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = createContainerWithNetwork(); + final NetworkNodeContainer container3 = + createContainerWithNetwork(container -> container2.getNode().getNetwork()); + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container2.getNode().getNetwork()); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + // Previous state: [[container1], [container2, container3, container4]] + + connectionProvider + .with(container1, container2, container3, container4, unrelatedContainer) + .connect(container1, container2) + .connect(container3, container4); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + clearTracking(container2.getNode().getNetwork()); + + final Network originalNetworkContainer1 = container1.getNode().getNetwork(); + final Network originalNetworkContainer2 = container2.getNode().getNetwork(); + + // Act + sut.update(container2, connectionProvider); + + // Assert + assertThat(container2.getNode().getNetwork()) + .isSameAs(container1.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isSameAs(originalNetworkContainer2) + .isNotSameAs(originalNetworkContainer1) + .isNotNull(); + + assertThat(container3.getNode().getNetwork()) + .isSameAs(container4.getNode().getNetwork()) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(container2.getNode().getNetwork()) + .isNotSameAs(originalNetworkContainer2) + .isNotNull(); + + assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container1, container2); + assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container3, container4); + + assertThat(getNetworkSplits(container2.getNode().getNetwork())).containsExactly( + Set.of(container3.getNode().getNetwork()) + ); + assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactly( + container1 + ); + assertThat(getRemovedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder( + container3, container4 + ); + assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); + } + + @Test + void shouldNotUpdateAnythingWhenStateIsTheSame() { + // Arrange + final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); + + final NetworkNodeContainer container1 = createContainerWithNetwork(); + final NetworkNodeContainer container2 = + createContainerWithNetwork(container -> container1.getNode().getNetwork()); + + final NetworkNodeContainer container3 = createContainerWithNetwork(); + final NetworkNodeContainer container4 = + createContainerWithNetwork(container -> container3.getNode().getNetwork()); + + final Network originalNetworkContainer1 = container1.getNode().getNetwork(); + final Network originalNetworkContainer3 = container3.getNode().getNetwork(); + + final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); + + connectionProvider + .with(container1, container2, container3, container4, unrelatedContainer) + .connect(container1, container2) + .connect(container3, container4); + + // Reset the state so that we can track the update properly. + clearTracking(container1.getNode().getNetwork()); + clearTracking(container3.getNode().getNetwork()); + + // Act + sut.update(container1, connectionProvider); + + // Assert + assertThat(container1.getNode().getNetwork()) + .isSameAs(container2.getNode().getNetwork()) + .isSameAs(originalNetworkContainer1) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(originalNetworkContainer3) + .isNotNull(); + + assertThat(container3.getNode().getNetwork()) + .isSameAs(container4.getNode().getNetwork()) + .isSameAs(originalNetworkContainer3) + .isNotSameAs(unrelatedContainer.getNode().getNetwork()) + .isNotSameAs(originalNetworkContainer1) + .isNotNull(); + + assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container1, container2); + assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) + .containsExactlyInAnyOrder(container3, container4); + + assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); + + assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAddedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); + assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); + } +} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java deleted file mode 100644 index 8fe84cedc..000000000 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilderTest.java +++ /dev/null @@ -1,722 +0,0 @@ -package com.refinedmods.refinedstorage2.api.network; - -import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; -import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; - -import java.util.List; -import java.util.Set; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class NetworkBuilderTest extends AbstractNetworkBuilderTest { - @Test - void shouldFormNetwork() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container = createContainer(); - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider.with(container, unrelatedContainer); - - // Act - sut.initialize(container, connectionProvider); - - // Assert - assertThat(container.getNode().getNetwork()).isNotNull(); - assertThat(container.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(container); - - assertThat(getAddedContainers(container.getNode().getNetwork())).containsExactly(container); - assertThat(getRemovedContainers(container.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container.getNode().getNetwork())).isZero(); - assertThat(getNetworkMerges(container.getNode().getNetwork())).isEmpty(); - - assertThat(unrelatedContainer.getNode().getNetwork()) - .isNotNull() - .isNotEqualTo(container.getNode().getNetwork()); - assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(unrelatedContainer); - } - - @Test - void shouldJoinExistingNetwork() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer existingContainer1 = createContainerWithNetwork(); - final NetworkNodeContainer existingContainer2 = - createContainerWithNetwork(container -> existingContainer1.getNode().getNetwork()); - final NetworkNodeContainer newContainer = createContainer(); - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider - .with(existingContainer1) - .with(existingContainer2) - .with(newContainer) - .with(unrelatedContainer) - .connect(existingContainer1, existingContainer2) - .connect(existingContainer1, newContainer); - - // Act - sut.initialize(newContainer, connectionProvider); - - // Assert - final Network expectedNetwork = existingContainer1.getNode().getNetwork(); - assertThat(expectedNetwork).isNotNull(); - - assertThat(existingContainer1.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(existingContainer2.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(newContainer.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(expectedNetwork.getComponent(GraphNetworkComponent.class).getContainers()).containsExactlyInAnyOrder( - existingContainer1, - existingContainer2, - newContainer - ); - - assertThat(getAddedContainers(expectedNetwork)).containsExactly( - existingContainer1, - existingContainer2, - newContainer - ); - assertThat(getRemovedContainers(expectedNetwork)).isEmpty(); - assertThat(getAmountRemoved(expectedNetwork)).isZero(); - assertThat(getNetworkMerges(expectedNetwork)).isEmpty(); - - assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull().isNotEqualTo(expectedNetwork); - assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(unrelatedContainer); - } - - @Test - void shouldMergeWithExistingNetworks() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer existingContainer0 = createContainerWithNetwork(); - final NetworkNodeContainer existingContainer1 = - createContainerWithNetwork(container -> existingContainer0.getNode().getNetwork()); - final NetworkNodeContainer existingContainer2 = createContainerWithNetwork(); - final Network initialNetworkOfExistingContainer2 = existingContainer2.getNode().getNetwork(); - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - final NetworkNodeContainer newContainer = createContainer(); - - connectionProvider - .with(existingContainer0, existingContainer1, existingContainer2, unrelatedContainer, newContainer) - .connect(existingContainer0, existingContainer1) - .connect(existingContainer2, newContainer) - .connect(newContainer, existingContainer1); - - // Act - sut.initialize(newContainer, connectionProvider); - - // Assert - final Network expectedNetwork = existingContainer1.getNode().getNetwork(); - assertThat(expectedNetwork).isNotNull(); - - assertThat(initialNetworkOfExistingContainer2).isNotNull(); - assertThat(getNetworkMerges(initialNetworkOfExistingContainer2)).containsExactlyInAnyOrder(expectedNetwork); - - assertThat(existingContainer1.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(existingContainer2.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(existingContainer0.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(newContainer.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(expectedNetwork.getComponent(GraphNetworkComponent.class).getContainers()).containsExactlyInAnyOrder( - existingContainer1, - existingContainer2, - existingContainer0, - newContainer - ); - - assertThat(getAddedContainers(expectedNetwork)) - .containsExactlyInAnyOrder(existingContainer2, newContainer, existingContainer1, existingContainer0); - assertThat(getRemovedContainers(expectedNetwork)).isEmpty(); - assertThat(getAmountRemoved(expectedNetwork)).isZero(); - assertThat(getNetworkMerges(expectedNetwork)).isEmpty(); - - assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull().isNotEqualTo(expectedNetwork); - assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(unrelatedContainer); - } - - @Test - void shouldFormNetworkIfThereAreNeighborsWithoutNetwork() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - final NetworkNodeContainer container1 = createContainer(); - final NetworkNodeContainer container2 = createContainer(); - final NetworkNodeContainer container3 = createContainer(); - - connectionProvider.with(container1, container2, container3) - .connect(container1, container2) - .connect(container2, container3); - - // Act - sut.initialize(container1, connectionProvider); - sut.initialize(container2, connectionProvider); - sut.initialize(container3, connectionProvider); - - // Assert - final Network expectedNetwork = container1.getNode().getNetwork(); - assertThat(expectedNetwork).isNotNull(); - - assertThat(container1.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(container2.getNode().getNetwork()).isEqualTo(expectedNetwork); - assertThat(container3.getNode().getNetwork()).isEqualTo(expectedNetwork); - - assertThat(expectedNetwork.getComponent(GraphNetworkComponent.class).getContainers()).containsExactlyInAnyOrder( - container1, - container2, - container3 - ); - - assertThat(getNetworkMerges(expectedNetwork)).isEmpty(); - assertThat(getAddedContainers(expectedNetwork)).containsExactlyInAnyOrder(container1, container2, container3); - assertThat(getRemovedContainers(expectedNetwork)).isEmpty(); - assertThat(getAmountRemoved(expectedNetwork)).isZero(); - - assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull().isNotEqualTo(expectedNetwork); - assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(unrelatedContainer); - } - - @Test - void shouldNotBeAbleToRemoveWithoutNetworkAssigned() { - // Arrange - final NetworkNodeContainer container = createContainer(); - - // Act - final Executable action = () -> sut.remove(container, new FakeConnectionProvider()); - - // Assert - assertThrows(IllegalStateException.class, action); - } - - @Test - void shouldSplitNetwork() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - final NetworkNodeContainer container2 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - final NetworkNodeContainer container3 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider - .with(container1, container2, container3, unrelatedContainer) - .connect(container2, container3); - - // Act - sut.remove(container1, connectionProvider); - - // Assert - assertThat(container1.getNode().getNetwork()).isNull(); - - assertThat(container2.getNode().getNetwork()) - .isSameAs(container3.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotNull(); - - assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container2, container3); - - assertThat(getNetworkSplits(container2.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactly( - container1, - container2, - container3 - ); - assertThat(getRemovedContainers(container2.getNode().getNetwork())).containsExactly(container1); - assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); - } - - @Test - void shouldSplitNetworkInTwo() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - final NetworkNodeContainer container2 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer container3 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer container4 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - final NetworkNodeContainer container5 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider - .with(container5, container4, container3, container2, container1, unrelatedContainer) - .connect(container1, container2) - .connect(container4, container5); - - // Act - sut.remove(container3, connectionProvider); - - // Assert - assertThat(container3.getNode().getNetwork()).isNull(); - - assertThat(container1.getNode().getNetwork()) - .isSameAs(container2.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotSameAs(container4.getNode().getNetwork()) - .isNotSameAs(container5.getNode().getNetwork()); - - assertThat(container1.getNode().getNetwork()).isNotNull(); - assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container1.getNode().getNetwork())) - .containsExactlyInAnyOrder(container1, container2); - assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); - - assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container1, container2); - - assertThat(container4.getNode().getNetwork()) - .isSameAs(container5.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotSameAs(container1.getNode().getNetwork()) - .isNotSameAs(container2.getNode().getNetwork()) - .isNotNull(); - - final List> splits = getNetworkSplits(container4.getNode().getNetwork()); - assertThat(splits).hasSize(1); - assertThat(splits.get(0)).containsExactlyInAnyOrder(container1.getNode().getNetwork()); - - assertThat(getAddedContainers(container4.getNode().getNetwork())) - .containsExactlyInAnyOrder(container1, container2, container3, container4, container5); - assertThat(getRemovedContainers(container4.getNode().getNetwork())) - .containsExactlyInAnyOrder(container1, container2, container3); - assertThat(getAmountRemoved(container4.getNode().getNetwork())).isZero(); - - assertThat(container4.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container4, container5); - } - - @Test - void shouldSplitNetworkInThree() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - - final NetworkNodeContainer container2 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer container3 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer container4 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - final NetworkNodeContainer container5 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider - .with(unrelatedContainer, container5, container4, container3, container2, container1) - .connect(container4, container5); - - // Act - sut.remove(container1, connectionProvider); - - // Assert - assertThat(container1.getNode().getNetwork()).isNull(); - - assertThat(container2.getNode().getNetwork()) - .isNotSameAs(container3.getNode().getNetwork()) - .isNotSameAs(container4.getNode().getNetwork()) - .isNotSameAs(container5.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotNull(); - - assertThat(getNetworkSplits(container2.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder(container2); - assertThat(getRemovedContainers(container2.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); - - assertThat(container3.getNode().getNetwork()) - .isNotSameAs(container2.getNode().getNetwork()) - .isNotSameAs(container4.getNode().getNetwork()) - .isNotSameAs(container5.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotNull(); - - assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder(container3); - assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); - - assertThat(container4.getNode().getNetwork()) - .isNotSameAs(container2.getNode().getNetwork()) - .isNotSameAs(container3.getNode().getNetwork()) - .isSameAs(container5.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotNull(); - - final List> splits = getNetworkSplits(container4.getNode().getNetwork()); - assertThat(splits).hasSize(1); - assertThat(splits.get(0)) - .containsExactlyInAnyOrder(container2.getNode().getNetwork(), container3.getNode().getNetwork()); - - assertThat(getAddedContainers(container4.getNode().getNetwork())) - .containsExactlyInAnyOrder(container1, container2, container3, container4, container5); - assertThat(getRemovedContainers(container4.getNode().getNetwork())) - .containsExactlyInAnyOrder(container1, container2, container3); - assertThat(getAmountRemoved(container4.getNode().getNetwork())).isZero(); - - assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(container2); - - assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(container3); - - assertThat(container4.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container4, container5); - } - - @Test - void shouldRemoveNetwork() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container = createContainerWithNetwork(); - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider.with(container, unrelatedContainer); - - final Network network = container.getNode().getNetwork(); - - // Act - sut.remove(container, connectionProvider); - - // Assert - assertThat(container.getNode().getNetwork()).isNull(); - - assertThat(unrelatedContainer.getNode().getNetwork()).isNotNull(); - assertThat(unrelatedContainer.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(unrelatedContainer); - - assertThat(network).isNotNull(); - assertThat(getNetworkSplits(network)).isEmpty(); - assertThat(getAddedContainers(network)).containsExactly(container); - assertThat(getRemovedContainers(network)).isEmpty(); - assertThat(getAmountRemoved(network)).isEqualTo(1); - } - - @Test - void shouldNotBeAbleToUpdateWithoutNetworkAssigned() { - // Arrange - final NetworkNodeContainer container = createContainer(); - - // Act - final Executable action = () -> sut.update(container, new FakeConnectionProvider()); - - // Assert - assertThrows(IllegalStateException.class, action); - } - - @Test - void shouldUpdateWithSoleContainer() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - - final Network originalNetwork = container1.getNode().getNetwork(); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider.with(container1, unrelatedContainer); - - // Reset the state so that we can track the update properly. - clearTracking(container1.getNode().getNetwork()); - - // Act - sut.update(container1, connectionProvider); - - // Assert - assertThat(container1.getNode().getNetwork()) - .isSameAs(originalNetwork) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotNull(); - - assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(container1); - - assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); - assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); - } - - @Test - void shouldSplitNetworkWhenUpdatingWithSoleContainerOnLeftSide() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - final NetworkNodeContainer container2 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - final NetworkNodeContainer container3 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final Network originalNetwork = container1.getNode().getNetwork(); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - // Note: container 1 is no longer connected. - connectionProvider - .with(container1, container2, container3, unrelatedContainer) - .connect(container2, container3); - - // Reset the state so that we can track the update properly. - clearTracking(container1.getNode().getNetwork()); - - // Act - sut.update(container1, connectionProvider); - - // Assert - assertThat(container1.getNode().getNetwork()) - .isSameAs(originalNetwork) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotNull(); - - assertThat(container2.getNode().getNetwork()) - .isSameAs(container3.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotSameAs(container1.getNode().getNetwork()) - .isNotSameAs(originalNetwork) - .isNotNull(); - - assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactly(container1); - assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container2, container3); - - assertThat(getNetworkSplits(container1.getNode().getNetwork())).containsExactly( - Set.of(container2.getNode().getNetwork()) - ); - assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); - assertThat(getRemovedContainers(container1.getNode().getNetwork())).containsExactlyInAnyOrder( - container2, container3 - ); - assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); - - assertThat(getNetworkSplits(container2.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder( - container2, container3 - ); - assertThat(getRemovedContainers(container2.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); - } - - @Test - void shouldSplitNetworkWhenUpdatingWithTwoContainersOnBothSides() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - final NetworkNodeContainer container2 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - final NetworkNodeContainer container3 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - final NetworkNodeContainer container4 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final Network originalNetwork = container1.getNode().getNetwork(); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider - .with(container1, container2, container3, container4, unrelatedContainer) - .connect(container1, container2) - .connect(container3, container4); - - // Reset the state so that we can track the update properly. - clearTracking(container1.getNode().getNetwork()); - - // Act - sut.update(container1, connectionProvider); - - // Assert - assertThat(container1.getNode().getNetwork()) - .isSameAs(container2.getNode().getNetwork()) - .isSameAs(originalNetwork) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotNull(); - - assertThat(container3.getNode().getNetwork()) - .isSameAs(container4.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotSameAs(container1.getNode().getNetwork()) - .isNotSameAs(originalNetwork) - .isNotNull(); - - assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container1, container2); - assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container3, container4); - - assertThat(getNetworkSplits(container1.getNode().getNetwork())).containsExactly( - Set.of(container3.getNode().getNetwork()) - ); - assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); - assertThat(getRemovedContainers(container1.getNode().getNetwork())).containsExactlyInAnyOrder( - container3, container4 - ); - assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); - - assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder( - container3, container4 - ); - assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); - } - - @Test - void shouldSplitNetworkAndMergeAdditionalContainerWhenUpdating() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - final NetworkNodeContainer container2 = createContainerWithNetwork(); - final NetworkNodeContainer container3 = - createContainerWithNetwork(container -> container2.getNode().getNetwork()); - final NetworkNodeContainer container4 = - createContainerWithNetwork(container -> container2.getNode().getNetwork()); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - // Previous state: [[container1], [container2, container3, container4]] - - connectionProvider - .with(container1, container2, container3, container4, unrelatedContainer) - .connect(container1, container2) - .connect(container3, container4); - - // Reset the state so that we can track the update properly. - clearTracking(container1.getNode().getNetwork()); - clearTracking(container2.getNode().getNetwork()); - - final Network originalNetworkContainer1 = container1.getNode().getNetwork(); - final Network originalNetworkContainer2 = container2.getNode().getNetwork(); - - // Act - sut.update(container2, connectionProvider); - - // Assert - assertThat(container2.getNode().getNetwork()) - .isSameAs(container1.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isSameAs(originalNetworkContainer2) - .isNotSameAs(originalNetworkContainer1) - .isNotNull(); - - assertThat(container3.getNode().getNetwork()) - .isSameAs(container4.getNode().getNetwork()) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotSameAs(container2.getNode().getNetwork()) - .isNotSameAs(originalNetworkContainer2) - .isNotNull(); - - assertThat(container2.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container1, container2); - assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container3, container4); - - assertThat(getNetworkSplits(container2.getNode().getNetwork())).containsExactly( - Set.of(container3.getNode().getNetwork()) - ); - assertThat(getAddedContainers(container2.getNode().getNetwork())).containsExactly( - container1 - ); - assertThat(getRemovedContainers(container2.getNode().getNetwork())).containsExactlyInAnyOrder( - container3, container4 - ); - assertThat(getAmountRemoved(container2.getNode().getNetwork())).isZero(); - - assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container3.getNode().getNetwork())).containsExactlyInAnyOrder( - container3, container4 - ); - assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); - } - - @Test - void shouldNotUpdateAnythingWhenStateIsTheSame() { - // Arrange - final FakeConnectionProvider connectionProvider = new FakeConnectionProvider(); - - final NetworkNodeContainer container1 = createContainerWithNetwork(); - final NetworkNodeContainer container2 = - createContainerWithNetwork(container -> container1.getNode().getNetwork()); - - final NetworkNodeContainer container3 = createContainerWithNetwork(); - final NetworkNodeContainer container4 = - createContainerWithNetwork(container -> container3.getNode().getNetwork()); - - final Network originalNetworkContainer1 = container1.getNode().getNetwork(); - final Network originalNetworkContainer3 = container3.getNode().getNetwork(); - - final NetworkNodeContainer unrelatedContainer = createContainerWithNetwork(); - - connectionProvider - .with(container1, container2, container3, container4, unrelatedContainer) - .connect(container1, container2) - .connect(container3, container4); - - // Reset the state so that we can track the update properly. - clearTracking(container1.getNode().getNetwork()); - clearTracking(container3.getNode().getNetwork()); - - // Act - sut.update(container1, connectionProvider); - - // Assert - assertThat(container1.getNode().getNetwork()) - .isSameAs(container2.getNode().getNetwork()) - .isSameAs(originalNetworkContainer1) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotSameAs(originalNetworkContainer3) - .isNotNull(); - - assertThat(container3.getNode().getNetwork()) - .isSameAs(container4.getNode().getNetwork()) - .isSameAs(originalNetworkContainer3) - .isNotSameAs(unrelatedContainer.getNode().getNetwork()) - .isNotSameAs(originalNetworkContainer1) - .isNotNull(); - - assertThat(container1.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container1, container2); - assertThat(container3.getNode().getNetwork().getComponent(GraphNetworkComponent.class).getContainers()) - .containsExactlyInAnyOrder(container3, container4); - - assertThat(getNetworkSplits(container1.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container1.getNode().getNetwork())).isEmpty(); - assertThat(getRemovedContainers(container1.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container1.getNode().getNetwork())).isZero(); - - assertThat(getNetworkSplits(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAddedContainers(container3.getNode().getNetwork())).isEmpty(); - assertThat(getRemovedContainers(container3.getNode().getNetwork())).isEmpty(); - assertThat(getAmountRemoved(container3.getNode().getNetwork())).isZero(); - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 3e7b919e6..72955b30c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -5,6 +5,7 @@ import com.refinedmods.refinedstorage2.api.core.registry.OrderedRegistryImpl; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.NetworkBuilder; +import com.refinedmods.refinedstorage2.api.network.NetworkBuilderImpl; import com.refinedmods.refinedstorage2.api.network.NetworkFactory; import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; @@ -45,7 +46,8 @@ public class PlatformApiImpl implements PlatformApi { new OrderedRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), ItemResourceType.INSTANCE); private final ComponentMapFactory networkComponentMapFactory = new ComponentMapFactory<>(); - private final NetworkBuilder networkBuilder = new NetworkBuilder(new NetworkFactory(networkComponentMapFactory)); + private final NetworkBuilder networkBuilder = + new NetworkBuilderImpl(new NetworkFactory(networkComponentMapFactory)); private final OrderedRegistry> storageTypeRegistry = new OrderedRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), ItemStorageType.INSTANCE); private final OrderedRegistry> storageChannelTypeRegistry = From dd21a8da308d1084e3db906f39d3f34ef0b7d650 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sun, 31 Jul 2022 00:02:04 +0200 Subject: [PATCH 04/23] Some cleanup. --- .../refinedstorage2/api/network/NetworkBuilder.java | 8 ++++++-- .../AbstractNetworkNodeContainerBlockEntity.java | 10 ++++++++++ .../platform/common/block/CableBlockSupport.java | 2 +- ...stractInternalNetworkNodeContainerBlockEntity.java | 11 +---------- .../internal/network/LevelConnectionProvider.java | 2 +- 5 files changed, 19 insertions(+), 14 deletions(-) diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java index d6e1cccb7..e4bedcf21 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/NetworkBuilder.java @@ -4,10 +4,14 @@ import org.apiguardian.api.API; +/** + * Manages the network state of a {@link com.refinedmods.refinedstorage2.api.network.node.NetworkNode}. + * Performs merge, split and remove operations as necessary. + */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") public interface NetworkBuilder { /** - * Initialized a not yet connected network node container. + * Initializes a not yet connected network node container. * If the network node already has an associated {@link Network}, calling this will do nothing. * This will perform a merge operation. * @@ -30,7 +34,7 @@ public interface NetworkBuilder { /** * Updates the network associated with the given container. Makes the network state adapt to connection changes * of an already connected container. - * Will perform split and/or merge operations. + * Will perform a split and/or a merge operation. * * @param container the container * @param connectionProvider the connection provider diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/AbstractNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/AbstractNetworkNodeContainerBlockEntity.java index f64b331d2..da430c033 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/AbstractNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/AbstractNetworkNodeContainerBlockEntity.java @@ -43,6 +43,16 @@ public void setRemoved() { PlatformApi.INSTANCE.requestNetworkNodeRemoval(this, level); } + @Override + @SuppressWarnings("deprecation") + public void setBlockState(final BlockState newBlockState) { + super.setBlockState(newBlockState); + if (level == null || level.isClientSide || node.getNetwork() == null) { + return; + } + PlatformApi.INSTANCE.requestNetworkNodeUpdate(this, level); + } + @Override public T getNode() { return node; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java index dc6f87842..4d034d25f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java @@ -104,6 +104,6 @@ private static boolean hasVisualConnection(final LevelAccessor world, if (!(world.getBlockEntity(offsetPos) instanceof PlatformNetworkNodeContainer container)) { return false; } - return container.canAcceptIncomingConnection(direction.getOpposite()); + return container.canAcceptIncomingConnection(direction); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java index 857f2bec2..d1b5026c3 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java @@ -1,7 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.block.entity; import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; -import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.blockentity.AbstractNetworkNodeContainerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.AbstractDirectionalBlock; import com.refinedmods.refinedstorage2.platform.common.util.RedstoneMode; @@ -123,15 +122,7 @@ public boolean canAcceptIncomingConnection(final Direction direction) { if (myDirection == null) { return true; } - return myDirection != direction; - } - - @Override - public void setBlockState(final BlockState newBlockState) { - super.setBlockState(newBlockState); - if (getNode().getNetwork() != null && level != null && !level.isClientSide()) { - PlatformApi.INSTANCE.requestNetworkNodeUpdate(this, level); - } + return myDirection != direction.getOpposite(); } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/network/LevelConnectionProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/network/LevelConnectionProvider.java index 1cdab0975..3e7e8bb11 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/network/LevelConnectionProvider.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/network/LevelConnectionProvider.java @@ -100,7 +100,7 @@ private Set findConnectionsAt(final AbstractNetworkNodeCon } final BlockPos offsetPos = container.getBlockPos().relative(direction); if (getBlockEntity(offsetPos) instanceof AbstractNetworkNodeContainerBlockEntity neighborContainer - && neighborContainer.canAcceptIncomingConnection(direction.getOpposite())) { + && neighborContainer.canAcceptIncomingConnection(direction)) { containers.add(neighborContainer); } } From 15deb160022daee8aaea666b00938bb7521e8363 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sun, 24 Jul 2022 16:31:11 +0200 Subject: [PATCH 05/23] Add upgrades. --- .../platform/api/PlatformApi.java | 3 + .../platform/api/PlatformApiProxy.java | 6 + .../api/item/AbstractUpgradeItem.java | 50 +++++++ .../api/upgrade/ApplicableUpgrade.java | 8 + .../api/upgrade/UpgradeDestination.java | 7 + .../api/upgrade/UpgradeInDestination.java | 5 + .../platform/api/upgrade/UpgradeRegistry.java | 14 ++ .../common/AbstractModInitializer.java | 13 ++ .../platform/common/PlatformApiImpl.java | 8 + .../block/entity/ImporterBlockEntity.java | 16 +- .../common/block/entity/UpgradeContainer.java | 49 ++++++ .../containermenu/ImporterContainerMenu.java | 41 ++++- .../platform/common/content/ContentIds.java | 2 + .../internal/upgrade/UpgradeDestinations.java | 22 +++ .../internal/upgrade/UpgradeRegistryImpl.java | 46 ++++++ .../common/item/SimpleUpgradeItem.java | 14 ++ .../common/screen/ImporterScreen.java | 4 +- .../assets/refinedstorage2/lang/en_us.json | 7 +- .../models/item/speed_upgrade.json | 6 + .../refinedstorage2/models/item/upgrade.json | 6 + .../refinedstorage2/textures/gui/importer.png | Bin 775 -> 970 bytes .../textures/item/speed_upgrade.png | Bin 0 -> 1480 bytes .../refinedstorage2/textures/item/upgrade.png | Bin 0 -> 1451 bytes .../advancements/upgrading.json | 28 ++++ .../recipes/speed_upgrade.json | 22 +++ .../data/refinedstorage2/recipes/upgrade.json | 22 +++ .../upgrade/UpgradeRegistryImplTest.java | 141 ++++++++++++++++++ .../platform/fabric/ModInitializerImpl.java | 18 +++ .../platform/forge/ModInitializer.java | 18 +++ 29 files changed, 568 insertions(+), 8 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractUpgradeItem.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/ApplicableUpgrade.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeDestination.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeInDestination.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeRegistry.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeDestinations.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImpl.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/SimpleUpgradeItem.java create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/speed_upgrade.json create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/upgrade.json create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/item/speed_upgrade.png create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/item/upgrade.png create mode 100644 refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/upgrading.json create mode 100644 refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/speed_upgrade.json create mode 100644 refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/upgrade.json create mode 100644 refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index 8e134ddbb..cc8907f0b 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -11,6 +11,7 @@ import com.refinedmods.refinedstorage2.platform.api.resource.filter.ResourceType; import com.refinedmods.refinedstorage2.platform.api.storage.PlatformStorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.type.StorageType; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; @@ -35,6 +36,8 @@ public interface PlatformApi { OrderedRegistry getGridSynchronizerRegistry(); + UpgradeRegistry getUpgradeRegistry(); + void requestNetworkNodeInitialization(NetworkNodeContainer container, Level level, Runnable callback); void requestNetworkNodeRemoval(NetworkNodeContainer container, Level level); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index 6c2e7b09d..c5bb371d0 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -11,6 +11,7 @@ import com.refinedmods.refinedstorage2.platform.api.resource.filter.ResourceType; import com.refinedmods.refinedstorage2.platform.api.storage.PlatformStorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.type.StorageType; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import javax.annotation.Nullable; @@ -69,6 +70,11 @@ public OrderedRegistry getGridSynchronizerRe return ensureLoaded().getGridSynchronizerRegistry(); } + @Override + public UpgradeRegistry getUpgradeRegistry() { + return ensureLoaded().getUpgradeRegistry(); + } + @Override public void requestNetworkNodeInitialization(final NetworkNodeContainer container, final Level level, diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractUpgradeItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractUpgradeItem.java new file mode 100644 index 000000000..acb0d0fe4 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractUpgradeItem.java @@ -0,0 +1,50 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeInDestination; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; + +import java.util.List; +import java.util.Set; +import javax.annotation.Nullable; + +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; + +public abstract class AbstractUpgradeItem extends Item { + private final UpgradeRegistry registry; + + protected AbstractUpgradeItem(final Properties properties, final UpgradeRegistry registry) { + super(properties); + this.registry = registry; + } + + @Override + public void appendHoverText(final ItemStack stack, + @Nullable final Level level, + final List lines, + final TooltipFlag flag) { + super.appendHoverText(stack, level, lines, flag); + final Set destinations = registry.getDestinations(this); + if (destinations.isEmpty()) { + return; + } + lines.add(PlatformApi.INSTANCE.createTranslation( + "item", + "upgrade.supported_by" + ).withStyle(ChatFormatting.WHITE)); + for (final UpgradeInDestination upgradeInDestination : destinations) { + final MutableComponent name = + upgradeInDestination.destination().getName().copy().withStyle(ChatFormatting.GRAY); + final MutableComponent amount = + Component.literal("(" + upgradeInDestination.maxAmount() + ")").withStyle(ChatFormatting.YELLOW); + lines.add(name.append(" ").append(amount)); + } + } +} + diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/ApplicableUpgrade.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/ApplicableUpgrade.java new file mode 100644 index 000000000..131e0239b --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/ApplicableUpgrade.java @@ -0,0 +1,8 @@ +package com.refinedmods.refinedstorage2.platform.api.upgrade; + +import java.util.function.Supplier; + +import net.minecraft.world.item.Item; + +public record ApplicableUpgrade(Supplier itemSupplier, int maxAmount) { +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeDestination.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeDestination.java new file mode 100644 index 000000000..aacc66a01 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeDestination.java @@ -0,0 +1,7 @@ +package com.refinedmods.refinedstorage2.platform.api.upgrade; + +import net.minecraft.network.chat.Component; + +public interface UpgradeDestination { + Component getName(); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeInDestination.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeInDestination.java new file mode 100644 index 000000000..a80090d33 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeInDestination.java @@ -0,0 +1,5 @@ +package com.refinedmods.refinedstorage2.platform.api.upgrade; + +public record UpgradeInDestination(UpgradeDestination destination, + int maxAmount) { +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeRegistry.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeRegistry.java new file mode 100644 index 000000000..81ec3ec04 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/upgrade/UpgradeRegistry.java @@ -0,0 +1,14 @@ +package com.refinedmods.refinedstorage2.platform.api.upgrade; + +import java.util.Set; +import java.util.function.Supplier; + +import net.minecraft.world.item.Item; + +public interface UpgradeRegistry { + void addApplicableUpgrade(UpgradeDestination destination, Supplier itemSupplier, int maxAmount); + + Set getApplicableUpgrades(UpgradeDestination destination); + + Set getDestinations(Item item); +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java index 0133c1a80..2e7e6aac2 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java @@ -8,6 +8,11 @@ import com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.fluid.FluidResourceType; import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.FluidStorageType; +import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; + +import java.util.function.Supplier; + +import net.minecraft.world.item.Item; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; @@ -57,4 +62,12 @@ protected void registerAdditionalResourceTypes() { FluidResourceType.INSTANCE ); } + + protected void addApplicableUpgrades(final Supplier speedUpgrade) { + PlatformApi.INSTANCE.getUpgradeRegistry().addApplicableUpgrade( + UpgradeDestinations.IMPORTER, + speedUpgrade, + 3 + ); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 72955b30c..428980060 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -17,6 +17,7 @@ import com.refinedmods.refinedstorage2.platform.api.resource.filter.ResourceType; import com.refinedmods.refinedstorage2.platform.api.storage.PlatformStorageRepository; import com.refinedmods.refinedstorage2.platform.api.storage.type.StorageType; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import com.refinedmods.refinedstorage2.platform.common.internal.grid.NoOpGridSynchronizer; import com.refinedmods.refinedstorage2.platform.common.internal.network.LevelConnectionProvider; import com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.item.ItemResourceType; @@ -24,6 +25,7 @@ import com.refinedmods.refinedstorage2.platform.common.internal.storage.PlatformStorageRepositoryImpl; import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.ItemStorageType; +import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeRegistryImpl; import com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil; import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; @@ -57,6 +59,7 @@ public class PlatformApiImpl implements PlatformApi { private final OrderedRegistry importerTransferStrategyRegistry = new OrderedRegistryImpl<>(createIdentifier("noop"), (level, pos, direction) -> (filter, actor, network) -> false); + private final UpgradeRegistry upgradeRegistry = new UpgradeRegistryImpl(); @Override public OrderedRegistry> getStorageTypeRegistry() { @@ -118,6 +121,11 @@ public OrderedRegistry getGridSynchronizerRe return gridSynchronizerRegistry; } + @Override + public UpgradeRegistry getUpgradeRegistry() { + return upgradeRegistry; + } + @Override public void requestNetworkNodeInitialization(final NetworkNodeContainer container, final Level level, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index e8c5f500d..3f159bac3 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -11,6 +11,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.ImporterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; import com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.ResourceFilterContainer; +import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; import java.util.List; @@ -19,6 +20,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; @@ -40,8 +42,10 @@ public class ImporterBlockEntity extends AbstractInternalNetworkNodeContainerBlo private static final String TAG_FILTER_MODE = "fim"; private static final String TAG_EXACT_MODE = "em"; private static final String TAG_RESOURCE_FILTER = "rf"; + private static final String TAG_UPGRADES = "u"; private final ResourceFilterContainer resourceFilterContainer; + private final UpgradeContainer upgradeContainer; private boolean exactMode; public ImporterBlockEntity(final BlockPos pos, final BlockState state) { @@ -57,6 +61,11 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { 9, this::resourceFilterContainerChanged ); + this.upgradeContainer = new UpgradeContainer( + UpgradeDestinations.IMPORTER, + PlatformApi.INSTANCE.getUpgradeRegistry(), + this::setChanged + ); } private Object normalize(final Object value) { @@ -120,6 +129,7 @@ private CompositeImporterTransferStrategy createStrategy(final ServerLevel serve public void saveAdditional(final CompoundTag tag) { super.saveAdditional(tag); tag.put(TAG_RESOURCE_FILTER, resourceFilterContainer.toTag()); + tag.put(TAG_UPGRADES, upgradeContainer.createTag()); tag.putInt(TAG_FILTER_MODE, FilterModeSettings.getFilterMode(getNode().getFilterMode())); tag.putBoolean(TAG_EXACT_MODE, exactMode); } @@ -138,6 +148,10 @@ public void load(final CompoundTag tag) { resourceFilterContainer.load(tag.getCompound(TAG_RESOURCE_FILTER)); } + if (tag.contains(TAG_UPGRADES)) { + upgradeContainer.fromTag(tag.getList(TAG_UPGRADES, Tag.TAG_COMPOUND)); + } + initializeResourceFilter(); super.load(tag); @@ -184,6 +198,6 @@ public Component getDisplayName() { @Nullable @Override public AbstractContainerMenu createMenu(final int syncId, final Inventory inventory, final Player player) { - return new ImporterContainerMenu(syncId, player, this, resourceFilterContainer); + return new ImporterContainerMenu(syncId, player, this, resourceFilterContainer, upgradeContainer); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java new file mode 100644 index 000000000..06b95c530 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java @@ -0,0 +1,49 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity; + +import com.refinedmods.refinedstorage2.platform.api.upgrade.ApplicableUpgrade; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeDestination; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; + +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.item.ItemStack; + +public class UpgradeContainer extends SimpleContainer { + private final UpgradeDestination destination; + private final UpgradeRegistry registry; + + public UpgradeContainer(final UpgradeDestination destination, final UpgradeRegistry registry) { + this(destination, registry, () -> { + }); + } + + public UpgradeContainer(final UpgradeDestination destination, + final UpgradeRegistry registry, + final Runnable listener) { + super(4); + this.destination = destination; + this.registry = registry; + this.addListener(container -> listener.run()); + } + + @Override + public int getMaxStackSize() { + return 1; + } + + @Override + public boolean canPlaceItem(final int slot, final ItemStack stack) { + final ApplicableUpgrade upgrade = registry.getApplicableUpgrades(destination) + .stream() + .filter(applicableUpgrade -> applicableUpgrade.itemSupplier().get() == stack.getItem()) + .findFirst() + .orElse(null); + if (upgrade == null) { + return false; + } + final int currentCount = countItem(stack.getItem()); + if (currentCount >= upgrade.maxAmount()) { + return false; + } + return super.canPlaceItem(slot, stack); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java index 992a9e940..69440225e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java @@ -3,18 +3,21 @@ import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.common.block.entity.ImporterBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.block.entity.UpgradeContainer; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ClientProperty; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyTypes; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ServerProperty; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.ResourceFilterSlot; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.ResourceFilterContainer; +import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; import com.refinedmods.refinedstorage2.platform.common.util.RedstoneMode; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; public class ImporterContainerMenu extends AbstractResourceFilterContainerMenu implements ResourceTypeAccessor { private static final int FILTER_SLOT_X = 8; @@ -25,7 +28,8 @@ public ImporterContainerMenu(final int syncId, final Inventory playerInventory, addSlots( playerInventory.player, - new ResourceFilterContainer(PlatformApi.INSTANCE.getResourceTypeRegistry(), 9) + new ResourceFilterContainer(PlatformApi.INSTANCE.getResourceTypeRegistry(), 9), + new UpgradeContainer(UpgradeDestinations.IMPORTER, PlatformApi.INSTANCE.getUpgradeRegistry()) ); initializeResourceFilterSlots(buf); @@ -38,7 +42,8 @@ public ImporterContainerMenu(final int syncId, final Inventory playerInventory, public ImporterContainerMenu(final int syncId, final Player player, final ImporterBlockEntity importer, - final ResourceFilterContainer resourceFilterContainer) { + final ResourceFilterContainer resourceFilterContainer, + final UpgradeContainer upgradeContainer) { super( Menus.INSTANCE.getImporter(), syncId, @@ -46,7 +51,7 @@ public ImporterContainerMenu(final int syncId, player, resourceFilterContainer ); - addSlots(player, resourceFilterContainer); + addSlots(player, resourceFilterContainer, upgradeContainer); registerProperty(new ServerProperty<>( PropertyTypes.FILTER_MODE, @@ -65,10 +70,15 @@ public ImporterContainerMenu(final int syncId, )); } - private void addSlots(final Player player, final ResourceFilterContainer resourceFilterContainer) { + private void addSlots(final Player player, + final ResourceFilterContainer resourceFilterContainer, + final UpgradeContainer upgradeContainer) { for (int i = 0; i < 9; ++i) { addSlot(createFilterSlot(resourceFilterContainer, i)); } + for (int i = 0; i < 4; ++i) { + addSlot(new Slot(upgradeContainer, i, 187, 6 + (i * 18))); + } addPlayerInventory(player.getInventory(), 8, 55); } @@ -76,4 +86,27 @@ private Slot createFilterSlot(final ResourceFilterContainer resourceFilterContai final int x = FILTER_SLOT_X + (18 * i); return new ResourceFilterSlot(resourceFilterContainer, i, x, FILTER_SLOT_Y); } + + @Override + public ItemStack quickMoveStack(final Player player, final int index) { + ItemStack originalStack = ItemStack.EMPTY; + final Slot slot = this.slots.get(index); + if (slot.hasItem()) { + final ItemStack stackInSlot = slot.getItem(); + originalStack = stackInSlot.copy(); + + if (index >= 9 && index < 9 + 4 && !moveItemStackTo(stackInSlot, 9 + 4, slots.size(), true)) { + return ItemStack.EMPTY; + } else if (index >= 9 + 4 && !moveItemStackTo(stackInSlot, 9, 9 + 4, false)) { + return ItemStack.EMPTY; + } + + if (stackInSlot.isEmpty()) { + slot.set(ItemStack.EMPTY); + } else { + slot.setChanged(); + } + } + return originalStack; + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java index ff961243c..a4bf069d7 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java @@ -28,6 +28,8 @@ public final class ContentIds { public static final ResourceLocation FLUID_STORAGE_BLOCK = createIdentifier("fluid_storage_block"); public static final ResourceLocation STORAGE_BLOCK = createIdentifier("storage_block"); public static final ResourceLocation IMPORTER = createIdentifier("importer"); + public static final ResourceLocation UPGRADE = createIdentifier("upgrade"); + public static final ResourceLocation SPEED_UPGRADE = createIdentifier("speed_upgrade"); private ContentIds() { } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeDestinations.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeDestinations.java new file mode 100644 index 000000000..0cecd2ba0 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeDestinations.java @@ -0,0 +1,22 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.upgrade; + +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeDestination; + +import net.minecraft.network.chat.Component; + +import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; + +public enum UpgradeDestinations implements UpgradeDestination { + IMPORTER(createTranslation("block", "importer")); + + private final Component name; + + UpgradeDestinations(final Component name) { + this.name = name; + } + + @Override + public Component getName() { + return name; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImpl.java new file mode 100644 index 000000000..7e01fadc9 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImpl.java @@ -0,0 +1,46 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.upgrade; + +import com.refinedmods.refinedstorage2.platform.api.upgrade.ApplicableUpgrade; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeDestination; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeInDestination; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +import net.minecraft.world.item.Item; + +public class UpgradeRegistryImpl implements UpgradeRegistry { + private final Map> destinationMap = new HashMap<>(); + + @Override + public void addApplicableUpgrade(final UpgradeDestination destination, + final Supplier itemSupplier, + final int maxAmount) { + destinationMap.computeIfAbsent(destination, key -> new HashSet<>()) + .add(new ApplicableUpgrade(itemSupplier, maxAmount)); + } + + @Override + public Set getApplicableUpgrades(final UpgradeDestination destination) { + return destinationMap.getOrDefault(destination, Collections.emptySet()); + } + + @Override + public Set getDestinations(final Item item) { + final Set result = new HashSet<>(); + for (final var entry : destinationMap.entrySet()) { + final UpgradeDestination destination = entry.getKey(); + for (final ApplicableUpgrade applicableUpgrade : entry.getValue()) { + if (applicableUpgrade.itemSupplier().get() == item) { + result.add(new UpgradeInDestination(destination, applicableUpgrade.maxAmount())); + } + } + } + return result; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/SimpleUpgradeItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/SimpleUpgradeItem.java new file mode 100644 index 000000000..518c3c144 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/SimpleUpgradeItem.java @@ -0,0 +1,14 @@ +package com.refinedmods.refinedstorage2.platform.common.item; + + +import com.refinedmods.refinedstorage2.platform.api.item.AbstractUpgradeItem; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; + +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; + +public final class SimpleUpgradeItem extends AbstractUpgradeItem { + public SimpleUpgradeItem(final CreativeModeTab tab, final UpgradeRegistry registry) { + super(new Item.Properties().tab(tab), registry); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/ImporterScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/ImporterScreen.java index 847be6b67..6996e1688 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/ImporterScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/ImporterScreen.java @@ -26,7 +26,7 @@ public ImporterScreen(final ImporterContainerMenu menu, final Inventory playerIn this.titleLabelY = 7; this.inventoryLabelX = 7; this.inventoryLabelY = 42; - this.imageWidth = 176; + this.imageWidth = 210; this.imageHeight = 137; } @@ -48,7 +48,7 @@ protected void init() { )); final ResourceFilterButtonWidget resourceFilterButton = new ResourceFilterButtonWidget( - leftPos + imageWidth - ResourceFilterButtonWidget.WIDTH - 7, + leftPos + imageWidth - ResourceFilterButtonWidget.WIDTH - 7 - 34, topPos + 4, menu ); diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json index 710a60612..dee73514c 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json @@ -89,6 +89,9 @@ "item.refinedstorage2.construction_core": "Construction Core", "item.refinedstorage2.destruction_core": "Destruction Core", "item.refinedstorage2.wrench": "Wrench", + "item.refinedstorage2.upgrade": "Upgrade", + "item.refinedstorage2.speed_upgrade": "Speed Upgrade", + "item.refinedstorage2.upgrade.supported_by": "Supported by:", "misc.refinedstorage2.stored": "Stored: %s", "misc.refinedstorage2.stored_with_capacity": "Stored: %s / %s", "misc.refinedstorage2.stacks": "Stacks: %s", @@ -150,5 +153,7 @@ "advancements.refinedstorage2.viewing_fluids": "Viewing fluids", "advancements.refinedstorage2.viewing_fluids.description": "Craft a Fluid Grid to interact with your fluid storage", "advancements.refinedstorage2.importing": "Importing", - "advancements.refinedstorage2.importing.description": "Get resources into the storage network with an Importer" + "advancements.refinedstorage2.importing.description": "Get resources into the storage network with an Importer", + "advancements.refinedstorage2.upgrading": "Upgrading", + "advancements.refinedstorage2.upgrading.description": "Craft an Upgrade to improve various devices" } diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/speed_upgrade.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/speed_upgrade.json new file mode 100644 index 000000000..f88a1a127 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/speed_upgrade.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "refinedstorage2:item/speed_upgrade" + } +} diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/upgrade.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/upgrade.json new file mode 100644 index 000000000..8d9fe8284 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/upgrade.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "refinedstorage2:item/upgrade" + } +} diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/gui/importer.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/gui/importer.png index 10b03d40322b8bd23ed59510bc9a545e4511ea16..3fd28b4b234df7bbaad472ea267bc377f708b73b 100644 GIT binary patch literal 970 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K58911MRQ8&P5D>38$lZxy-8q?;Kn_c~qpu?a z!^VE@KZ&eBzG#3?h%1o(|NsB7W5+^6L(R?2ySuxABB`6FO9LtPk|4iepeztDNO?26 z0fjgVJR*x382I*pFyqucMV<@{%-WtVjv*CsZ|8L99WoGLan}6#-(N3%n#7^SYCodZ z%ne*B>YlaMT~Ji4WY+UcnP_(`PNeYcc2h_Z^>4vn`wWZU1kpx9>gEV=wv% zelX?wU3>HXwkOU-)AE84dtBM&6H@(4CCuuQ2nZDwFmU|>vr ztLVVMBoN@GykI}W-i51VrcAA$=W^PIF)AhTd*iRy*<@9Uo1m5|AtHQTHJhQQ6{j5r`n-vyJabsY5 z7q%{ZOR?C7x5?V|mOzur56n8USvGZPrjV{NYsSRZBeN@St3)XQ9jCF>`}ywmll_?9 zJ8g&|sjdKTQf3)2eJaKifRTT@Rl12&+s+Z%rPO{pqRuKFdq<^1CP z4UhY;$u(ZzFZxY-38$lZxy-8q?;Kn_c~qpu?a z!^VE@KZ&eBzG#3?h%1o(|NsB7W5+^6L(R?2ySuxABB`6FO9LtPk|4iepeztDNO?26 z0fjgVJR*x382I*rFr)kL32PY`m@+(F978JN-rl;Hb=yIrCD3x+-+%pgtY${3h97(5 zzxm8h4W2ix0sKt|9zCwJ|MqgSqbp6@Q2l88RS@mok&}ks8yBOCgGaP@s^Y#|G2j}c-mj#PnPRIHZt82`Ti~3Uk?B!Ylp0*+7m{3+ootz+WN)WnQ(*-(AUCxn zQK2F?C$HG5!d3}vt`(3C64qBz04piUwpD^SD#ABF!8yMuRl!uxOgGuk&``nLQqR!T z!q~`EN5ROz&{W^RQs2-(*TB%q(7?*bKmiJrfVLH-q*(>IxIyg#@@$ndN=gc>^!3Zj z%k|2Q_413-^$jg8E%gnI^o@*kfhu&1EAvVcD|GXUm0>2hq!uR^WfqiV=I1GZOiWD5 zFD#PU%0_}#n6BP2AO_EVu8M)o`HUDF34YC)x{-2sR(CaRb3oXS&*t9 zlvEeuVQbq#?b3Jgypvt&bam^s+=o0^z8TAH}JnmW4zW5dk1m-nRzMs<;9wyXoC3KCABECEH%ZgC_h&L9L`pmSlnP}k(Op; zVrisnYHn42&;4T^vIyZY`N?n-LW#a{Rw}Aj`tyPK%HY-s-G^ zYn-(?`WCUocCVY+yH#LiguPkeMMsflK0z13?OaV$6s#;dH!EoIwYp@BPPtvKr(tqF zz>apJoiy5P$uq7+Gd}XSF>1ajb?6GzAJ9M`nk=|Po&87AD`&AynjJ( zQCZiT>#r+~X1c5mJDj!E$wW$YLi2TT#=Pyb+Ycv(tPW*qcD(Ysbj|hb7AM7p)q)Oj zNgHQ;@HzIjEPBq`Fz*+C>-O8ozGAY~o8H~;rhIDlWRHiRK31Hup4<0h*?*x4-+$No zmGhS!=eUw(8lojC!^bYv$x>n^Ya+#~BgWl!SkXp~f7e|-v2NBWUQ2CQk4Z2!GJN}O z`=-pgXs1lsZdnno)`n0mQ3)P4k?y0H8{U?2U;iz)f=z|Rb7|0x9J57J-4+YZ^kEBI z9V!ya_T$GlaXtIL$8sMTulWD@r;OTUPlpr5D?^$tzZ7Bp`m@G|t>TAr@6&eCcklBi z?0a21N-9Q5Bz(|m@ilVXznKMR{?s{AAYU6 zm|@bAp1H>VJ(H>Vyg7m`_FkHL=X8I3{434Y+&H8AWy!Dk&yzp$-~LfDldF~KYLotS lZ(z`;Pw(7YHupcL0R!v4ulDS1ZxcXetEa1<%Q~loCIF1v5uyM9 literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/item/upgrade.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/item/upgrade.png new file mode 100644 index 0000000000000000000000000000000000000000..ba66433f4a8822789a3510407a4a0865e9bb913f GIT binary patch literal 1451 zcmbVMeNYr-7+;c*7?DfKuPnAjCq?)6<8JR`hlAkufKwpgu7QjR_I4NUg4;cJ7w#a` zLi?a>kQ~241|4k3m_(yyaIhG|GKR*XDFz8s$@oVi6`VoKqW6HK{$Tv0o!NcAp5OEQ z-rw^)TbGla9v!tN3WA_$dj^vSMosXIi~!%b$!Qi0t5sWp>X1rQKPwAR3NN_?*zRRZ zg*<`ftG4$Fi4e4?(&H>p3$ik4PV#Empp7=*^#L>lB_;=aELSF|uuCZQh!*5lS2qHC zcngwGW#L&qtKjxzRLg>+I@`%rmvLquNlt zgwA8q=3;@B1#zpYkH#>+->>!Sw31wk5oWU)!%2)JQDA{8RierUP*I5wd0+&ElRZAw zBZ+X(BkPhXR0{%_&R)Um%gUN}EGlzC0m-lc>%#~wj(NSod(BuYYM$^fjRmb0XO&OD z@&rYykU5Z#lK2o9X!r0yK|{cXeqQ!~q_E|T#8r3&QMEG`1e|Dj4^QijX2FHKaMWO+ zcvR=o>roRyaVP;41$vSOjxdJ&EQF`5HX}nZRxpBW*bFH;J!MNX8>~9gW;GB*2x}J= zl@&Q56x#!0&tX#^ilwcxz^an$l%(=d738=jRZ`rN54KuovJP*^_lUgYS2hOIG<$1C zkUfz}`{Iu2 z)35gzZ{5A&?VP3SBSrhN&W}E^mHjzw#+2S9NP_SLD5sE2kgJb#K}=3b*@X z5;tB`Zfd8lDyD1xFDG}~-`_L6wrRq5wlJafYu7V(M||HJcKo%oS!ACiV^-K6zhAR6 z`b0%I%C`+9jLPQEwxOA=4xU{7NNxeOe#5hxNR84l#I$@5Hx7>35)L5E4}_O=*EbK9 zA3R)jyWG&yH8|Fg{B(WWuaS-C$159aSG@b^l8Bx-O~+8?kp~ekZpDve;%nZ!eZS^z z`@k!j@G!b*Y2WCw16$ts&CnQK{l&{oVce2lep%bVJNk5_;q#`&OiS+N@k(dg3ts4w zy#4axL&syau~DzbY%{HWvuEVF<2kPlkAG8>lD(>(W|(uqRzA zY#$t%`txL39aDRfymz$Mo$feiNrrdDA1~B8K2Gc`*!(w`hWeJ`S` z>*u$o{#f2sgqixgTbv2Gi)+urfTZips{I$Yy}B<@bm7Y3-5EunUZ`*45-nFbd{uwp z-n5qF@5X-FG~9VM^PG2r*|NVk{KlQY7Z2(bVF literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/upgrading.json b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/upgrading.json new file mode 100644 index 000000000..73939a392 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/upgrading.json @@ -0,0 +1,28 @@ +{ + "display": { + "icon": { + "item": "refinedstorage2:upgrade" + }, + "title": { + "translate": "advancements.refinedstorage2.upgrading" + }, + "description": { + "translate": "advancements.refinedstorage2.upgrading.description" + } + }, + "parent": "refinedstorage2:root", + "criteria": { + "upgrade_in_inventory": { + "trigger": "minecraft:inventory_changed", + "conditions": { + "items": [ + { + "items": [ + "refinedstorage2:upgrade" + ] + } + ] + } + } + } +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/speed_upgrade.json b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/speed_upgrade.json new file mode 100644 index 000000000..bcc314348 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/speed_upgrade.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "ESE", + "SUS", + "EEE" + ], + "key": { + "E": { + "item": "refinedstorage2:quartz_enriched_iron" + }, + "S": { + "item": "minecraft:sugar" + }, + "U": { + "item": "refinedstorage2:upgrade" + } + }, + "result": { + "item": "refinedstorage2:speed_upgrade" + } +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/upgrade.json b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/upgrade.json new file mode 100644 index 000000000..550ee76f2 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/upgrade.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "EGE", + "EPE", + "EGE" + ], + "key": { + "E": { + "item": "refinedstorage2:quartz_enriched_iron" + }, + "G": { + "item": "minecraft:glass" + }, + "P": { + "item": "refinedstorage2:improved_processor" + } + }, + "result": { + "item": "refinedstorage2:upgrade" + } +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java new file mode 100644 index 000000000..b14fc2742 --- /dev/null +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java @@ -0,0 +1,141 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.upgrade; + +import com.refinedmods.refinedstorage2.platform.api.upgrade.ApplicableUpgrade; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeDestination; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeInDestination; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; +import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; + +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Items; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +@SetupMinecraft +class UpgradeRegistryImplTest { + + UpgradeRegistry sut; + + @BeforeEach + void setUp() { + sut = new UpgradeRegistryImpl(); + } + + @Test + void testAddingSingleApplicableUpgrade() { + // Arrange + final UpgradeDestination dest = new UpgradeDestinationImpl(null); + + // Act + sut.addApplicableUpgrade(dest, () -> Items.DIRT, 1); + + // Assert + assertThat(sut.getApplicableUpgrades(dest)) + .usingRecursiveFieldByFieldElementComparator() + .containsExactlyInAnyOrder( + new ApplicableUpgrade(() -> Items.DIRT, 1) + ); + } + + @Test + void testAddingDifferentApplicableUpgradesToTheSameDestination() { + // Arrange + final UpgradeDestination dest = new UpgradeDestinationImpl(null); + + // Act + sut.addApplicableUpgrade(dest, () -> Items.DIRT, 1); + sut.addApplicableUpgrade(dest, () -> Items.GLASS, 5); + + // Assert + assertThat(sut.getApplicableUpgrades(dest)) + .usingRecursiveFieldByFieldElementComparator() + .containsExactlyInAnyOrder( + new ApplicableUpgrade(() -> Items.DIRT, 1), + new ApplicableUpgrade(() -> Items.GLASS, 5) + ); + } + + @Test + void testRetrievingApplicableUpgradesFromUnknownDestination() { + // Arrange + final UpgradeDestination dest = new UpgradeDestinationImpl(null); + + // Assert + assertThat(sut.getApplicableUpgrades(dest)).isEmpty(); + } + + @Test + void testRetrievingSingleDestinationForItem() { + // Arrange + final UpgradeDestination dest = new UpgradeDestinationImpl(null); + + // Act + sut.addApplicableUpgrade(dest, () -> Items.DIRT, 1); + + // Assert + assertThat(sut.getDestinations(Items.DIRT)) + .usingRecursiveFieldByFieldElementComparator() + .containsExactlyInAnyOrder( + new UpgradeInDestination(dest, 1) + ); + } + + @Test + void testRetrievingMultipleDestinationsForItem() { + // Arrange + final UpgradeDestination dest1 = new UpgradeDestinationImpl(Component.literal("A")); + final UpgradeDestination dest2 = new UpgradeDestinationImpl(Component.literal("B")); + + // Act + sut.addApplicableUpgrade(dest1, () -> Items.DIRT, 1); + sut.addApplicableUpgrade(dest2, () -> Items.DIRT, 2); + + // Assert + assertThat(sut.getDestinations(Items.DIRT)) + .usingRecursiveFieldByFieldElementComparator() + .containsExactlyInAnyOrder( + new UpgradeInDestination(dest1, 1), + new UpgradeInDestination(dest2, 2) + ); + } + + @Test + void testRetrievingMultipleDestinationsForDifferentItems() { + // Arrange + final UpgradeDestination dest1 = new UpgradeDestinationImpl(Component.literal("A")); + final UpgradeDestination dest2 = new UpgradeDestinationImpl(Component.literal("B")); + + // Act + sut.addApplicableUpgrade(dest1, () -> Items.DIRT, 1); + sut.addApplicableUpgrade(dest2, () -> Items.DIRT, 2); + sut.addApplicableUpgrade(dest2, () -> Items.GLASS, 3); + + // Assert + assertThat(sut.getDestinations(Items.DIRT)) + .usingRecursiveFieldByFieldElementComparator() + .containsExactlyInAnyOrder( + new UpgradeInDestination(dest1, 1), + new UpgradeInDestination(dest2, 2) + ); + + assertThat(sut.getDestinations(Items.GLASS)) + .usingRecursiveFieldByFieldElementComparator() + .containsExactly( + new UpgradeInDestination(dest2, 3) + ); + } + + @Test + void testRetrievingDestinationForUnknownItem() { + // Arrange + final UpgradeDestination dest = new UpgradeDestinationImpl(null); + + // Act + sut.addApplicableUpgrade(dest, () -> Items.DIRT, 1); + + // Assert + assertThat(sut.getDestinations(Items.GLASS)).isEmpty(); + } +} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java index e7a34f8c7..06376dbf1 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java @@ -32,6 +32,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.storage.diskdrive.DiskDriveContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; import com.refinedmods.refinedstorage2.platform.common.content.Blocks; +import com.refinedmods.refinedstorage2.platform.common.content.ContentIds; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.content.LootFunctions; import com.refinedmods.refinedstorage2.platform.common.content.Menus; @@ -43,6 +44,7 @@ import com.refinedmods.refinedstorage2.platform.common.item.ItemStorageDiskItem; import com.refinedmods.refinedstorage2.platform.common.item.ProcessorItem; import com.refinedmods.refinedstorage2.platform.common.item.SimpleItem; +import com.refinedmods.refinedstorage2.platform.common.item.SimpleUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.item.WrenchItem; import com.refinedmods.refinedstorage2.platform.common.item.block.ControllerBlockItem; import com.refinedmods.refinedstorage2.platform.common.item.block.CreativeControllerBlockItem; @@ -83,6 +85,7 @@ import net.minecraft.sounds.SoundEvent; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -287,6 +290,7 @@ private void registerItems() { registerGridItems(); registerControllerItems(); registerStorageItems(); + registerUpgrades(); } private void registerSimpleItems() { @@ -446,6 +450,20 @@ private void registerStorageItems() { } } + private void registerUpgrades() { + register( + Registry.ITEM, + ContentIds.UPGRADE, + new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) + ); + final Supplier speedUpgrade = register( + Registry.ITEM, + ContentIds.SPEED_UPGRADE, + new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) + ); + addApplicableUpgrades(speedUpgrade); + } + private void registerBlockEntities() { BlockEntities.INSTANCE.setCable(register( Registry.BLOCK_ENTITY_TYPE, diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java index ea5009fdf..b2e6a19e8 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java @@ -41,6 +41,7 @@ import com.refinedmods.refinedstorage2.platform.common.item.ItemStorageDiskItem; import com.refinedmods.refinedstorage2.platform.common.item.ProcessorItem; import com.refinedmods.refinedstorage2.platform.common.item.SimpleItem; +import com.refinedmods.refinedstorage2.platform.common.item.SimpleUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.item.WrenchItem; import com.refinedmods.refinedstorage2.platform.common.item.block.ControllerBlockItem; import com.refinedmods.refinedstorage2.platform.common.item.block.CreativeControllerBlockItem; @@ -55,6 +56,8 @@ import com.refinedmods.refinedstorage2.platform.forge.internal.network.node.importer.ItemHandlerImporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.forge.packet.NetworkManager; +import java.util.function.Supplier; + import net.minecraft.core.Direction; import net.minecraft.core.Registry; import net.minecraft.sounds.SoundEvent; @@ -103,8 +106,10 @@ import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.QUARTZ_ENRICHED_IRON; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.QUARTZ_ENRICHED_IRON_BLOCK; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.SILICON; +import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.SPEED_UPGRADE; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STORAGE_BLOCK; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STORAGE_HOUSING; +import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.UPGRADE; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.WRENCH; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.forFluidStorageBlock; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.forFluidStorageDisk; @@ -255,6 +260,7 @@ private void registerItems() { registerGridItems(); registerControllerItems(); registerStorageItems(); + registerUpgrades(); itemRegistry.register(FMLJavaModLoadingContext.get().getModEventBus()); } @@ -417,6 +423,18 @@ private void registerStorageItems() { } } + private void registerUpgrades() { + itemRegistry.register( + UPGRADE.getPath(), + () -> new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) + ); + final Supplier speedUpgrade = itemRegistry.register( + SPEED_UPGRADE.getPath(), + () -> new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) + ); + addApplicableUpgrades(speedUpgrade); + } + private void registerBlockEntities() { BlockEntities.INSTANCE.setCable(blockEntityTypeRegistry.register( CABLE.getPath(), From cd0be17ce6492ec2765e4f9a7cd058604bf3ba86 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sun, 31 Jul 2022 14:32:26 +0200 Subject: [PATCH 06/23] Add SHIFT + CLICK transfer framework from RS 1. --- CHANGELOG.md | 6 ++ refinedstorage2-platform-common/build.gradle | 1 + .../common/AbstractModInitializer.java | 2 +- .../platform/common/Platform.java | 3 + .../platform/common/PlatformProxy.java | 6 ++ .../AbstractBaseContainerMenu.java | 5 ++ .../AbstractResourceFilterContainerMenu.java | 16 ++++ .../containermenu/ImporterContainerMenu.java | 27 +----- .../slot/ResourceFilterSlot.java | 20 ++++- .../AbstractStorageBlockContainerMenu.java | 2 + .../block/ItemStorageBlockContainerMenu.java | 3 +- .../diskdrive/DiskDriveContainerMenu.java | 26 +----- .../transfer/FilterInventoryDestination.java | 14 +++ .../transfer/TransferDestination.java | 10 +++ .../transfer/TransferManager.java | 90 +++++++++++++++++++ .../filter/fluid/FluidFilteredResource.java | 8 +- .../filter/item/ItemFilteredResource.java | 8 +- .../item/FluidFilteredResourceTest.java | 19 ++++ .../filter/item/ItemFilteredResourceTest.java | 18 ++++ .../upgrade/UpgradeRegistryImplTest.java | 8 +- .../platform/fabric/PlatformImpl.java | 7 ++ .../ContainerTransferDestination.java | 29 ++++++ .../platform/forge/PlatformImpl.java | 7 ++ .../ContainerTransferDestination.java | 16 ++++ 24 files changed, 285 insertions(+), 66 deletions(-) create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/FilterInventoryDestination.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferDestination.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java create mode 100644 refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/FluidFilteredResourceTest.java create mode 100644 refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResourceTest.java create mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/containermenu/ContainerTransferDestination.java create mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/containermenu/ContainerTransferDestination.java diff --git a/CHANGELOG.md b/CHANGELOG.md index a1fc73ca7..16be468a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,12 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Fixed network connection state not rebuilding after using Wrench on a directional block. +### Added + +- Upgrade +- Speed Upgrade +- You can now SHIFT + CLICK transfer resources in the filter slots. + ## [2.0.0-milestone.2.1] - 2022-07-30 ### Changed diff --git a/refinedstorage2-platform-common/build.gradle b/refinedstorage2-platform-common/build.gradle index a0765b1ff..973cb618e 100644 --- a/refinedstorage2-platform-common/build.gradle +++ b/refinedstorage2-platform-common/build.gradle @@ -27,6 +27,7 @@ dependencies { testImplementation "org.junit.jupiter:junit-jupiter-params:${project.junitVersion}" testImplementation "org.assertj:assertj-core:${project.assertJVersion}" testImplementation project(':refinedstorage2-platform-test') + testImplementation "nl.jqno.equalsverifier:equalsverifier:${project.equalsverifierVersion}" } test { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java index 2e7e6aac2..6ed773de4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java @@ -67,7 +67,7 @@ protected void addApplicableUpgrades(final Supplier speedUpgrade) { PlatformApi.INSTANCE.getUpgradeRegistry().addApplicableUpgrade( UpgradeDestinations.IMPORTER, speedUpgrade, - 3 + 4 ); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java index 350231fdf..d73e15cf0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java @@ -10,6 +10,7 @@ import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; +import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.menu.MenuOpener; import com.refinedmods.refinedstorage2.platform.common.packet.ClientToServerCommunications; import com.refinedmods.refinedstorage2.platform.common.packet.ServerToClientCommunications; @@ -68,4 +69,6 @@ FluidGridEventHandler createFluidGridEventHandler(AbstractContainerMenu containe EnergyStorage createEnergyStorage(ControllerType controllerType, Runnable listener); void setEnergy(EnergyStorage energyStorage, long stored); + + TransferManager createTransferManager(AbstractContainerMenu containerMenu); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java index 060b18264..e80631701 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java @@ -10,6 +10,7 @@ import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; +import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.menu.MenuOpener; import com.refinedmods.refinedstorage2.platform.common.packet.ClientToServerCommunications; import com.refinedmods.refinedstorage2.platform.common.packet.ServerToClientCommunications; @@ -129,6 +130,11 @@ public void setEnergy(final EnergyStorage energyStorage, final long stored) { ensureLoaded().setEnergy(energyStorage, stored); } + @Override + public TransferManager createTransferManager(final AbstractContainerMenu containerMenu) { + return ensureLoaded().createTransferManager(containerMenu); + } + private Platform ensureLoaded() { if (platform == null) { throw new IllegalStateException("Platform not loaded yet"); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java index 44e7d9a20..56f273a38 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java @@ -1,9 +1,11 @@ package com.refinedmods.refinedstorage2.platform.common.containermenu; +import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ClientProperty; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.Property; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyType; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ServerProperty; +import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import java.util.HashMap; import java.util.Map; @@ -17,10 +19,12 @@ import net.minecraft.world.item.ItemStack; public abstract class AbstractBaseContainerMenu extends AbstractContainerMenu { + protected final TransferManager transferManager; private final Map, Property> propertyMap = new HashMap<>(); protected AbstractBaseContainerMenu(final MenuType type, final int syncId) { super(type, syncId); + this.transferManager = Platform.INSTANCE.createTransferManager(this); } @SuppressWarnings("unchecked") @@ -71,6 +75,7 @@ public boolean stillValid(final Player player) { @Override public ItemStack quickMoveStack(final Player player, final int index) { + transferManager.transfer(index); return ItemStack.EMPTY; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractResourceFilterContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractResourceFilterContainerMenu.java index 0e655e1f8..ee10c3bdd 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractResourceFilterContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractResourceFilterContainerMenu.java @@ -99,6 +99,22 @@ public void clicked(final int id, final int dragType, final ClickType actionType } } + public void addToFilterIfNotExisting(final ItemStack stack) { + if (currentResourceType == null) { + return; + } + for (final ResourceFilterSlot resourceFilterSlot : resourceFilterSlots) { + if (resourceFilterSlot.contains(stack, currentResourceType)) { + return; + } + } + for (final ResourceFilterSlot resourceFilterSlot : resourceFilterSlots) { + if (resourceFilterSlot.changeIfEmpty(stack, currentResourceType)) { + return; + } + } + } + @Override public Component getCurrentResourceTypeName() { return currentResourceType != null ? currentResourceType.getName() : Component.empty(); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java index 69440225e..330ec104a 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java @@ -17,7 +17,6 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; -import net.minecraft.world.item.ItemStack; public class ImporterContainerMenu extends AbstractResourceFilterContainerMenu implements ResourceTypeAccessor { private static final int FILTER_SLOT_X = 8; @@ -80,33 +79,13 @@ private void addSlots(final Player player, addSlot(new Slot(upgradeContainer, i, 187, 6 + (i * 18))); } addPlayerInventory(player.getInventory(), 8, 55); + + transferManager.addBiTransfer(player.getInventory(), upgradeContainer); + transferManager.addFilterTransfer(player.getInventory()); } private Slot createFilterSlot(final ResourceFilterContainer resourceFilterContainer, final int i) { final int x = FILTER_SLOT_X + (18 * i); return new ResourceFilterSlot(resourceFilterContainer, i, x, FILTER_SLOT_Y); } - - @Override - public ItemStack quickMoveStack(final Player player, final int index) { - ItemStack originalStack = ItemStack.EMPTY; - final Slot slot = this.slots.get(index); - if (slot.hasItem()) { - final ItemStack stackInSlot = slot.getItem(); - originalStack = stackInSlot.copy(); - - if (index >= 9 && index < 9 + 4 && !moveItemStackTo(stackInSlot, 9 + 4, slots.size(), true)) { - return ItemStack.EMPTY; - } else if (index >= 9 + 4 && !moveItemStackTo(stackInSlot, 9, 9 + 4, false)) { - return ItemStack.EMPTY; - } - - if (stackInSlot.isEmpty()) { - slot.set(ItemStack.EMPTY); - } else { - slot.setChanged(); - } - } - return originalStack; - } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/ResourceFilterSlot.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/ResourceFilterSlot.java index 5c1d885df..608b43bed 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/ResourceFilterSlot.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/ResourceFilterSlot.java @@ -8,6 +8,7 @@ import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.Optional; import javax.annotation.Nullable; import com.mojang.blaze3d.vertex.PoseStack; @@ -43,13 +44,28 @@ private static SimpleContainer createDummyContainer() { return new SimpleContainer(1); } - public void change(final ItemStack carried, final ResourceType type) { - type.translate(carried).ifPresentOrElse( + public void change(final ItemStack stack, final ResourceType type) { + type.translate(stack).ifPresentOrElse( resource -> resourceFilterContainer.set(containerIndex, resource), () -> resourceFilterContainer.remove(containerIndex) ); } + public boolean changeIfEmpty(final ItemStack stack, final ResourceType type) { + final FilteredResource existing = resourceFilterContainer.get(containerIndex); + if (existing != null) { + return false; + } + change(stack, type); + return true; + } + + public boolean contains(final ItemStack stack, final ResourceType type) { + final Optional translated = type.translate(stack); + final Optional current = Optional.ofNullable(resourceFilterContainer.get(containerIndex)); + return translated.equals(current); + } + public void broadcastChanges(final Player player) { final FilteredResource currentResource = resourceFilterContainer.get(containerIndex); if (!Objects.equals(currentResource, cachedResource)) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java index ca49b9787..3c1c39cbd 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java @@ -56,6 +56,8 @@ private void addSlots(final Player player, final ResourceFilterContainer resourc addSlot(createFilterSlot(resourceFilterContainer, i)); } addPlayerInventory(player.getInventory(), 8, 141); + + transferManager.addFilterTransfer(player.getInventory()); } private Slot createFilterSlot(final ResourceFilterContainer resourceFilterContainer, final int i) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/ItemStorageBlockContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/ItemStorageBlockContainerMenu.java index 4d834e322..f37584e40 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/ItemStorageBlockContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/ItemStorageBlockContainerMenu.java @@ -29,7 +29,8 @@ public ItemStorageBlockContainerMenu(final int syncId, final Inventory playerInv PlatformApi.INSTANCE.getResourceTypeRegistry(), playerInventory.player, buf, - ItemResourceType.INSTANCE); + ItemResourceType.INSTANCE + ); } public ItemStorageBlockContainerMenu(final int syncId, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java index 6eb8461c9..ac74fff5d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java @@ -79,6 +79,9 @@ private void addSlots(final Player player, addSlot(createFilterSlot(resourceFilterContainer, i)); } addPlayerInventory(player.getInventory(), 8, 141); + + transferManager.addBiTransfer(player.getInventory(), diskInventory); + transferManager.addFilterTransfer(player.getInventory()); } private Slot createFilterSlot(final ResourceFilterContainer resourceFilterContainer, final int i) { @@ -139,27 +142,4 @@ private Stream getStorageDiskInfo() { .map(storageInfoAccessor::getInfo) .flatMap(Optional::stream); } - - @Override - public ItemStack quickMoveStack(final Player player, final int index) { - ItemStack originalStack = ItemStack.EMPTY; - final Slot slot = this.slots.get(index); - if (slot.hasItem()) { - final ItemStack stackInSlot = slot.getItem(); - originalStack = stackInSlot.copy(); - - if (index < 8 && !moveItemStackTo(stackInSlot, 8, slots.size(), true)) { - return ItemStack.EMPTY; - } else if (index >= 8 && !moveItemStackTo(stackInSlot, 0, 8, false)) { - return ItemStack.EMPTY; - } - - if (stackInSlot.isEmpty()) { - slot.set(ItemStack.EMPTY); - } else { - slot.setChanged(); - } - } - return originalStack; - } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/FilterInventoryDestination.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/FilterInventoryDestination.java new file mode 100644 index 000000000..5c7a9511c --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/FilterInventoryDestination.java @@ -0,0 +1,14 @@ +package com.refinedmods.refinedstorage2.platform.common.containermenu.transfer; + +import com.refinedmods.refinedstorage2.platform.common.containermenu.AbstractResourceFilterContainerMenu; + +import net.minecraft.world.item.ItemStack; + +public record FilterInventoryDestination(AbstractResourceFilterContainerMenu destination) + implements TransferDestination { + @Override + public ItemStack transfer(final ItemStack stack) { + destination.addToFilterIfNotExisting(stack); + return null; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferDestination.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferDestination.java new file mode 100644 index 000000000..6d169e36d --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferDestination.java @@ -0,0 +1,10 @@ +package com.refinedmods.refinedstorage2.platform.common.containermenu.transfer; + +import javax.annotation.Nullable; + +import net.minecraft.world.item.ItemStack; + +public interface TransferDestination { + @Nullable + ItemStack transfer(ItemStack stack); +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java new file mode 100644 index 000000000..a897b3150 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java @@ -0,0 +1,90 @@ +package com.refinedmods.refinedstorage2.platform.common.containermenu.transfer; + +import com.refinedmods.refinedstorage2.platform.common.containermenu.AbstractResourceFilterContainerMenu; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import net.minecraft.world.Container; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; + +public class TransferManager { + private final Map> destinationMap = new HashMap<>(); + private final AbstractContainerMenu containerMenu; + private final Function destinationFactory; + + public TransferManager(final AbstractContainerMenu containerMenu, + final Function destinationFactory) { + this.containerMenu = containerMenu; + this.destinationFactory = destinationFactory; + } + + + public void addTransfer(final Container from, final Container to) { + addTransfer( + destinationFactory.apply(from), + destinationFactory.apply(to) + ); + } + + private void addTransfer(final TransferDestination from, final TransferDestination to) { + final List destinationList = destinationMap.computeIfAbsent(from, k -> new LinkedList<>()); + destinationList.add(to); + } + + public void addFilterTransfer(final Container from) { + if (!(containerMenu instanceof AbstractResourceFilterContainerMenu resourceFilterContainer)) { + throw new UnsupportedOperationException( + "Cannot add filter transfer if container menu isn't resource filterable" + ); + } + addTransfer( + destinationFactory.apply(from), + new FilterInventoryDestination(resourceFilterContainer) + ); + } + + public void addBiTransfer(final Container from, final Container to) { + addTransfer(from, to); + addTransfer(to, from); + } + + public void transfer(final int index) { + final Slot slot = containerMenu.getSlot(index); + if (slot.getItem().isEmpty()) { + return; + } + final TransferDestination key = destinationFactory.apply(slot.container); + final List destinations = destinationMap.get(key); + if (destinations != null) { + transfer(slot, destinations); + } + } + + private void transfer(final Slot slot, final List destinations) { + final ItemStack initial = slot.getItem().copy(); + final ItemStack remainder = doTransfer(initial, destinations); + slot.set(remainder); + slot.setChanged(); + } + + private ItemStack doTransfer(final ItemStack initial, final List destinations) { + ItemStack remainder = initial.copy(); + for (final TransferDestination destination : destinations) { + final ItemStack destinationRemainder = destination.transfer(remainder); + if (destinationRemainder == null) { + break; + } + remainder = destinationRemainder; + if (remainder.isEmpty()) { + break; + } + } + return remainder; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/fluid/FluidFilteredResource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/fluid/FluidFilteredResource.java index 9231f5823..654ed8479 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/fluid/FluidFilteredResource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/fluid/FluidFilteredResource.java @@ -15,13 +15,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Player; -public class FluidFilteredResource implements FilteredResource { - private final FluidResource value; - - public FluidFilteredResource(final FluidResource value) { - this.value = value; - } - +public record FluidFilteredResource(FluidResource value) implements FilteredResource { @Override public void writeToPacket(final FriendlyByteBuf buf) { PacketUtil.writeFluidResource(buf, value); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResource.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResource.java index 6710e2a1a..972c677fe 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResource.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResource.java @@ -16,13 +16,7 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.TooltipFlag; -public class ItemFilteredResource implements FilteredResource { - private final ItemResource value; - - public ItemFilteredResource(final ItemResource value) { - this.value = value; - } - +public record ItemFilteredResource(ItemResource value) implements FilteredResource { @Override public void writeToPacket(final FriendlyByteBuf buf) { PacketUtil.writeItemResource(buf, value); diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/FluidFilteredResourceTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/FluidFilteredResourceTest.java new file mode 100644 index 000000000..8056ed874 --- /dev/null +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/FluidFilteredResourceTest.java @@ -0,0 +1,19 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.item; + +import com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.fluid.FluidFilteredResource; +import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; + +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Fluids; +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + +@SetupMinecraft +class FluidFilteredResourceTest { + @Test + void testEqualsHashcode() { + EqualsVerifier.forClass(FluidFilteredResource.class) + .withPrefabValues(Fluid.class, Fluids.LAVA, Fluids.WATER) + .verify(); + } +} diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResourceTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResourceTest.java new file mode 100644 index 000000000..7a911b0cd --- /dev/null +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/filter/item/ItemFilteredResourceTest.java @@ -0,0 +1,18 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.item; + +import com.refinedmods.refinedstorage2.platform.test.SetupMinecraft; + +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + +@SetupMinecraft +class ItemFilteredResourceTest { + @Test + void testEqualsHashcode() { + EqualsVerifier.forClass(ItemFilteredResource.class) + .withPrefabValues(Item.class, Items.DIRT, Items.GLASS) + .verify(); + } +} diff --git a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java index b14fc2742..58b3de2e5 100644 --- a/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java +++ b/refinedstorage2-platform-common/src/test/java/com/refinedmods/refinedstorage2/platform/common/internal/upgrade/UpgradeRegistryImplTest.java @@ -15,7 +15,6 @@ @SetupMinecraft class UpgradeRegistryImplTest { - UpgradeRegistry sut; @BeforeEach @@ -138,4 +137,11 @@ void testRetrievingDestinationForUnknownItem() { // Assert assertThat(sut.getDestinations(Items.GLASS)).isEmpty(); } + + private record UpgradeDestinationImpl(Component name) implements UpgradeDestination { + @Override + public Component getName() { + return name(); + } + } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java index 1d7edc295..b187e6b55 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java @@ -13,7 +13,9 @@ import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; +import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.util.BucketQuantityFormatter; +import com.refinedmods.refinedstorage2.platform.fabric.containermenu.ContainerTransferDestination; import com.refinedmods.refinedstorage2.platform.fabric.integration.energy.ControllerTeamRebornEnergy; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.FluidGridEventHandlerImpl; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.ItemGridEventHandlerImpl; @@ -141,6 +143,11 @@ public void setEnergy(final EnergyStorage energyStorage, final long stored) { } } + @Override + public TransferManager createTransferManager(final AbstractContainerMenu containerMenu) { + return new TransferManager(containerMenu, ContainerTransferDestination::new); + } + private Optional convertNonEmptyToFluid(final ItemStack stack) { final Storage storage = FluidStorage.ITEM.find( stack, diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/containermenu/ContainerTransferDestination.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/containermenu/ContainerTransferDestination.java new file mode 100644 index 000000000..38af9e26c --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/containermenu/ContainerTransferDestination.java @@ -0,0 +1,29 @@ +package com.refinedmods.refinedstorage2.platform.fabric.containermenu; + +import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferDestination; + +import net.fabricmc.fabric.api.transfer.v1.item.InventoryStorage; +import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant; +import net.fabricmc.fabric.api.transfer.v1.storage.Storage; +import net.fabricmc.fabric.api.transfer.v1.transaction.Transaction; +import net.minecraft.world.Container; +import net.minecraft.world.item.ItemStack; + +public record ContainerTransferDestination(Container destination) implements TransferDestination { + @Override + public ItemStack transfer(final ItemStack stack) { + final Storage storage = InventoryStorage.of(destination, null); + try (Transaction tx = Transaction.openOuter()) { + final long inserted = storage.insert( + ItemVariant.of(stack), + stack.getCount(), + tx + ); + tx.commit(); + final long remainder = stack.getCount() - inserted; + final ItemStack remainderStack = stack.copy(); + remainderStack.setCount((int) remainder); + return remainderStack; + } + } +} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java index dcd27c1ed..c52890410 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java @@ -13,7 +13,9 @@ import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; +import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.util.BucketQuantityFormatter; +import com.refinedmods.refinedstorage2.platform.forge.containermenu.ContainerTransferDestination; import com.refinedmods.refinedstorage2.platform.forge.integration.energy.ControllerForgeEnergy; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.FluidGridEventHandlerImpl; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.ItemGridEventHandlerImpl; @@ -138,4 +140,9 @@ public void setEnergy(final EnergyStorage energyStorage, final long stored) { controllerForgeEnergy.setSilently(stored); } } + + @Override + public TransferManager createTransferManager(final AbstractContainerMenu containerMenu) { + return new TransferManager(containerMenu, ContainerTransferDestination::new); + } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/containermenu/ContainerTransferDestination.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/containermenu/ContainerTransferDestination.java new file mode 100644 index 000000000..7740bba7c --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/containermenu/ContainerTransferDestination.java @@ -0,0 +1,16 @@ +package com.refinedmods.refinedstorage2.platform.forge.containermenu; + +import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferDestination; + +import net.minecraft.world.Container; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.items.ItemHandlerHelper; +import net.minecraftforge.items.wrapper.InvWrapper; + +public record ContainerTransferDestination(Container destination) implements TransferDestination { + @Override + public ItemStack transfer(final ItemStack stack) { + final InvWrapper destinationInv = new InvWrapper(destination); + return ItemHandlerHelper.insertItem(destinationInv, stack, false); + } +} From ce8566657495bc519000afdad8650f01d2e8004d Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sun, 31 Jul 2022 15:20:59 +0200 Subject: [PATCH 07/23] Speed Upgrade now changes the cooldown time of the Importer. --- CHANGELOG.md | 4 ++- .../node/importer/ImporterNetworkNode.java | 13 ++++++++-- .../platform/common/Config.java | 6 +++++ .../block/entity/ImporterBlockEntity.java | 25 +++++++++++++++++-- .../common/block/entity/UpgradeConstants.java | 14 +++++++++++ .../common/block/entity/UpgradeContainer.java | 2 +- .../platform/common/content/Items.java | 14 +++++++++-- .../platform/fabric/ConfigImpl.java | 17 +++++++++++++ .../platform/fabric/ModInitializerImpl.java | 1 + .../platform/forge/ConfigImpl.java | 24 ++++++++++++++++++ .../platform/forge/ModInitializer.java | 1 + 11 files changed, 113 insertions(+), 8 deletions(-) create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 16be468a0..c00986f56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - All directional blocks no longer transmit a network signal out of the direction. - All directional blocks no longer accept a network signal from the facing direction. +- Upgrade items now state the applicable destinations in the tooltip. +- Upgrade items can now have a maximum of 1 type per upgrade inventory. +- You can now SHIFT + CLICK transfer resources in the filter slots again. ### Fixed @@ -20,7 +23,6 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Upgrade - Speed Upgrade -- You can now SHIFT + CLICK transfer resources in the filter slots. ## [2.0.0-milestone.2.1] - 2022-07-30 diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java index bb42630e6..4ed1d54c2 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java @@ -13,10 +13,10 @@ // TODO: Write a gametest. public class ImporterNetworkNode extends AbstractNetworkNode { - private final long energyUsage; + private long energyUsage; private final Filter filter = new Filter(); private final Actor actor = new NetworkNodeActor(this); - private final long coolDownTime; + private long coolDownTime; private long coolDownTimer; @Nullable @@ -63,6 +63,15 @@ public void setFilterTemplates(final Set templates) { filter.setTemplates(templates); } + public void setCoolDownTime(final long coolDownTime) { + this.coolDownTime = coolDownTime; + this.coolDownTimer = coolDownTime; + } + + public void setEnergyUsage(final long energyUsage) { + this.energyUsage = energyUsage; + } + @Override public long getEnergyUsage() { return energyUsage; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java index a816458fa..23eeccfee 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java @@ -23,6 +23,8 @@ public interface Config { Importer getImporter(); + Upgrade getUpgrade(); + interface Grid { boolean isLargeFont(); @@ -102,4 +104,8 @@ interface FluidStorageBlock { interface Importer { long getEnergyUsage(); } + + interface Upgrade { + long getSpeedUpgradeEnergyUsage(); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index 3f159bac3..dda9c70d8 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -10,6 +10,7 @@ import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.ImporterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.internal.resource.filter.ResourceFilterContainer; import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -53,7 +54,10 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { BlockEntities.INSTANCE.getImporter(), pos, state, - new ImporterNetworkNode(Platform.INSTANCE.getConfig().getImporter().getEnergyUsage(), 8) + new ImporterNetworkNode( + calculateEnergyUsage(0), + UpgradeConstants.DEFAULT_COOL_DOWN_TIMER + ) ); getNode().setNormalizer(this::normalize); this.resourceFilterContainer = new ResourceFilterContainer( @@ -64,7 +68,7 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { this.upgradeContainer = new UpgradeContainer( UpgradeDestinations.IMPORTER, PlatformApi.INSTANCE.getUpgradeRegistry(), - this::setChanged + this::upgradeContainerChanged ); } @@ -153,6 +157,7 @@ public void load(final CompoundTag tag) { } initializeResourceFilter(); + initializeUpgrades(); super.load(tag); } @@ -185,6 +190,22 @@ private void initializeResourceFilter() { getNode().setFilterTemplates(resourceFilterContainer.getTemplates()); } + private void upgradeContainerChanged() { + initializeUpgrades(); + setChanged(); + } + + private void initializeUpgrades() { + final int amountOfSpeedUpgrades = upgradeContainer.countItem(Items.INSTANCE.getSpeedUpgrade()); + getNode().setCoolDownTime(UpgradeConstants.calculateCoolDownTime(amountOfSpeedUpgrades)); + getNode().setEnergyUsage(calculateEnergyUsage(amountOfSpeedUpgrades)); + } + + private static long calculateEnergyUsage(final int amountOfSpeedUpgrades) { + return Platform.INSTANCE.getConfig().getImporter().getEnergyUsage() + + (Platform.INSTANCE.getConfig().getUpgrade().getSpeedUpgradeEnergyUsage() * amountOfSpeedUpgrades); + } + @Override public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByteBuf buf) { resourceFilterContainer.writeToUpdatePacket(buf); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java new file mode 100644 index 000000000..41b97b332 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java @@ -0,0 +1,14 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity; + +public final class UpgradeConstants { + public static final int UPGRADE_SLOTS = 4; + public static final long DEFAULT_COOL_DOWN_TIMER = 8; + + private UpgradeConstants() { + } + + public static long calculateCoolDownTime(final long amountOfSpeedUpgrades) { + return DEFAULT_COOL_DOWN_TIMER + - (long) ((double) amountOfSpeedUpgrades / (double) UPGRADE_SLOTS * (double) DEFAULT_COOL_DOWN_TIMER); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java index 06b95c530..5fab7dcbf 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java @@ -19,7 +19,7 @@ public UpgradeContainer(final UpgradeDestination destination, final UpgradeRegis public UpgradeContainer(final UpgradeDestination destination, final UpgradeRegistry registry, final Runnable listener) { - super(4); + super(UpgradeConstants.UPGRADE_SLOTS); this.destination = destination; this.registry = registry; this.addListener(container -> listener.run()); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java index abd1adae2..61ef4d426 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java @@ -24,6 +24,8 @@ public final class Items { private final List> controllers = new ArrayList<>(); @Nullable private Supplier storageHousing; + @Nullable + private Supplier speedUpgrade; private Items() { } @@ -52,7 +54,15 @@ public Item getStorageHousing() { return Objects.requireNonNull(storageHousing).get(); } - public void setStorageHousing(final Supplier storageHousingSupplier) { - this.storageHousing = storageHousingSupplier; + public void setStorageHousing(final Supplier supplier) { + this.storageHousing = supplier; + } + + public Item getSpeedUpgrade() { + return Objects.requireNonNull(speedUpgrade).get(); + } + + public void setSpeedUpgrade(final Supplier supplier) { + this.speedUpgrade = supplier; } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java index b5f604a32..40f3dde51 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java @@ -36,6 +36,9 @@ public class ConfigImpl implements ConfigData, com.refinedmods.refinedstorage2.p @ConfigEntry.Gui.CollapsibleObject private ImporterImpl importer = new ImporterImpl(); + @ConfigEntry.Gui.CollapsibleObject + private UpgradeImpl upgrade = new UpgradeImpl(); + public static ConfigImpl get() { return AutoConfig.getConfigHolder(ConfigImpl.class).getConfig(); } @@ -75,6 +78,11 @@ public Importer getImporter() { return importer; } + @Override + public Upgrade getUpgrade() { + return upgrade; + } + private static class GridImpl implements Grid { private boolean largeFont = false; @@ -312,4 +320,13 @@ public long getEnergyUsage() { return energyUsage; } } + + private static class UpgradeImpl implements Upgrade { + private long speedUpgradeEnergyUsage = 4; + + @Override + public long getSpeedUpgradeEnergyUsage() { + return speedUpgradeEnergyUsage; + } + } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java index 06376dbf1..efafd70fb 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java @@ -461,6 +461,7 @@ private void registerUpgrades() { ContentIds.SPEED_UPGRADE, new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) ); + Items.INSTANCE.setSpeedUpgrade(speedUpgrade); addApplicableUpgrades(speedUpgrade); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java index 146750646..52f8fdef8 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java @@ -23,6 +23,7 @@ public class ConfigImpl implements Config { private final StorageBlock storageBlock; private final FluidStorageBlock fluidStorageBlock; private final Importer importer; + private final Upgrade upgrade; public ConfigImpl() { cable = new CableImpl(); @@ -32,6 +33,7 @@ public ConfigImpl() { storageBlock = new StorageBlockImpl(); fluidStorageBlock = new FluidStorageBlockImpl(); importer = new ImporterImpl(); + upgrade = new UpgradeImpl(); spec = builder.build(); } @@ -74,6 +76,11 @@ public Importer getImporter() { return importer; } + @Override + public Upgrade getUpgrade() { + return upgrade; + } + private class CableImpl implements Cable { private final ForgeConfigSpec.LongValue energyUsage; @@ -401,4 +408,21 @@ public long getEnergyUsage() { return energyUsage.get(); } } + + private class UpgradeImpl implements Upgrade { + private final ForgeConfigSpec.LongValue speedUpgradeEnergyUsage; + + UpgradeImpl() { + builder.push("upgrade"); + speedUpgradeEnergyUsage = builder + .comment("The additional energy used per Speed Upgrade") + .defineInRange(ENERGY_USAGE, 4, 0, Long.MAX_VALUE); + builder.pop(); + } + + @Override + public long getSpeedUpgradeEnergyUsage() { + return speedUpgradeEnergyUsage.get(); + } + } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java index b2e6a19e8..3dfc2b760 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java @@ -432,6 +432,7 @@ private void registerUpgrades() { SPEED_UPGRADE.getPath(), () -> new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) ); + Items.INSTANCE.setSpeedUpgrade(speedUpgrade); addApplicableUpgrades(speedUpgrade); } From fa38812a92001f72ddc720d97fa897ba08ff4c1d Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sun, 31 Jul 2022 18:10:32 +0200 Subject: [PATCH 08/23] Added Stack Upgrade. --- CHANGELOG.md | 1 + .../ImporterTransferStrategyFactory.java | 2 +- .../common/AbstractModInitializer.java | 8 +++++- .../platform/common/Config.java | 2 ++ .../platform/common/PlatformApiImpl.java | 2 +- .../block/entity/ImporterBlockEntity.java | 26 +++++++++++++----- .../platform/common/content/ContentIds.java | 1 + .../platform/common/content/Items.java | 10 +++++++ .../assets/refinedstorage2/lang/en_us.json | 1 + .../models/item/stack_upgrade.json | 6 ++++ .../textures/item/stack_upgrade.png | Bin 0 -> 1510 bytes .../recipes/stack_upgrade.json | 19 +++++++++++++ .../platform/fabric/ConfigImpl.java | 7 +++++ .../platform/fabric/ModInitializerImpl.java | 8 +++++- ...torageImporterTransferStrategyFactory.java | 11 ++++---- .../platform/forge/ConfigImpl.java | 9 ++++++ .../platform/forge/ModInitializer.java | 8 +++++- ...andlerImporterTransferStrategyFactory.java | 5 ++-- ...andlerImporterTransferStrategyFactory.java | 5 ++-- 19 files changed, 110 insertions(+), 21 deletions(-) create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/stack_upgrade.json create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/item/stack_upgrade.png create mode 100644 refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/stack_upgrade.json diff --git a/CHANGELOG.md b/CHANGELOG.md index c00986f56..e95e9fb3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Upgrade - Speed Upgrade +- Stack Upgrade ## [2.0.0-milestone.2.1] - 2022-07-30 diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/importer/ImporterTransferStrategyFactory.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/importer/ImporterTransferStrategyFactory.java index db73d6ef3..503a7e294 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/importer/ImporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/network/node/importer/ImporterTransferStrategyFactory.java @@ -10,5 +10,5 @@ @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.1") @FunctionalInterface public interface ImporterTransferStrategyFactory { - ImporterTransferStrategy create(ServerLevel level, BlockPos pos, Direction direction); + ImporterTransferStrategy create(ServerLevel level, BlockPos pos, Direction direction, boolean hasStackUpgrade); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java index 6ed773de4..aa1df29e0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java @@ -63,11 +63,17 @@ protected void registerAdditionalResourceTypes() { ); } - protected void addApplicableUpgrades(final Supplier speedUpgrade) { + protected void addApplicableUpgrades(final Supplier speedUpgrade, + final Supplier stackUpgrade) { PlatformApi.INSTANCE.getUpgradeRegistry().addApplicableUpgrade( UpgradeDestinations.IMPORTER, speedUpgrade, 4 ); + PlatformApi.INSTANCE.getUpgradeRegistry().addApplicableUpgrade( + UpgradeDestinations.IMPORTER, + stackUpgrade, + 1 + ); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java index 23eeccfee..21bbb30d4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java @@ -107,5 +107,7 @@ interface Importer { interface Upgrade { long getSpeedUpgradeEnergyUsage(); + + long getStackUpgradeEnergyUsage(); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 428980060..13953a138 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -58,7 +58,7 @@ public class PlatformApiImpl implements PlatformApi { new OrderedRegistryImpl<>(createIdentifier("off"), new NoOpGridSynchronizer()); private final OrderedRegistry importerTransferStrategyRegistry = new OrderedRegistryImpl<>(createIdentifier("noop"), - (level, pos, direction) -> (filter, actor, network) -> false); + (level, pos, direction, hasStackUpgrade) -> (filter, actor, network) -> false); private final UpgradeRegistry upgradeRegistry = new UpgradeRegistryImpl(); @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index dda9c70d8..25112c7a7 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -16,6 +16,7 @@ import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; import java.util.List; +import java.util.Set; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; @@ -55,7 +56,7 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { pos, state, new ImporterNetworkNode( - calculateEnergyUsage(0), + calculateEnergyUsage(0, false), UpgradeConstants.DEFAULT_COOL_DOWN_TIMER ) ); @@ -87,9 +88,10 @@ private Object normalize(final Object value) { @SuppressWarnings("deprecation") public void setBlockState(final BlockState newBlockState) { super.setBlockState(newBlockState); - if (level instanceof ServerLevel serverLevel) { - updateTransferStrategy(serverLevel); + if (!(level instanceof ServerLevel serverLevel)) { + return; } + updateTransferStrategy(serverLevel); } @Override @@ -118,13 +120,14 @@ private void updateTransferStrategy(final ServerLevel serverLevel) { private CompositeImporterTransferStrategy createStrategy(final ServerLevel serverLevel, final Direction direction) { + final boolean hasStackUpgrade = hasStackUpgrade(); final Direction incomingDirection = direction.getOpposite(); final BlockPos sourcePosition = worldPosition.offset(direction.getNormal()); final List factories = PlatformApi.INSTANCE.getImporterTransferStrategyRegistry().getAll(); final List strategies = factories .stream() - .map(factory -> factory.create(serverLevel, sourcePosition, incomingDirection)) + .map(factory -> factory.create(serverLevel, sourcePosition, incomingDirection, hasStackUpgrade)) .toList(); return new CompositeImporterTransferStrategy(strategies); } @@ -192,18 +195,27 @@ private void initializeResourceFilter() { private void upgradeContainerChanged() { initializeUpgrades(); + if (level instanceof ServerLevel serverLevel) { + updateTransferStrategy(serverLevel); + } setChanged(); } private void initializeUpgrades() { final int amountOfSpeedUpgrades = upgradeContainer.countItem(Items.INSTANCE.getSpeedUpgrade()); + final boolean hasStackUpgrade = hasStackUpgrade(); getNode().setCoolDownTime(UpgradeConstants.calculateCoolDownTime(amountOfSpeedUpgrades)); - getNode().setEnergyUsage(calculateEnergyUsage(amountOfSpeedUpgrades)); + getNode().setEnergyUsage(calculateEnergyUsage(amountOfSpeedUpgrades, hasStackUpgrade)); + } + + private boolean hasStackUpgrade() { + return upgradeContainer.hasAnyOf(Set.of(Items.INSTANCE.getStackUpgrade())); } - private static long calculateEnergyUsage(final int amountOfSpeedUpgrades) { + private static long calculateEnergyUsage(final int amountOfSpeedUpgrades, final boolean hasStackUpgrade) { return Platform.INSTANCE.getConfig().getImporter().getEnergyUsage() - + (Platform.INSTANCE.getConfig().getUpgrade().getSpeedUpgradeEnergyUsage() * amountOfSpeedUpgrades); + + (Platform.INSTANCE.getConfig().getUpgrade().getSpeedUpgradeEnergyUsage() * amountOfSpeedUpgrades) + + (hasStackUpgrade ? Platform.INSTANCE.getConfig().getUpgrade().getStackUpgradeEnergyUsage() : 0L); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java index a4bf069d7..bacaf430b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java @@ -30,6 +30,7 @@ public final class ContentIds { public static final ResourceLocation IMPORTER = createIdentifier("importer"); public static final ResourceLocation UPGRADE = createIdentifier("upgrade"); public static final ResourceLocation SPEED_UPGRADE = createIdentifier("speed_upgrade"); + public static final ResourceLocation STACK_UPGRADE = createIdentifier("stack_upgrade"); private ContentIds() { } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java index 61ef4d426..8361e47ec 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Items.java @@ -26,6 +26,8 @@ public final class Items { private Supplier storageHousing; @Nullable private Supplier speedUpgrade; + @Nullable + private Supplier stackUpgrade; private Items() { } @@ -65,4 +67,12 @@ public Item getSpeedUpgrade() { public void setSpeedUpgrade(final Supplier supplier) { this.speedUpgrade = supplier; } + + public Item getStackUpgrade() { + return Objects.requireNonNull(stackUpgrade).get(); + } + + public void setStackUpgrade(final Supplier supplier) { + this.stackUpgrade = supplier; + } } diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json index dee73514c..4ecc0f11a 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json @@ -91,6 +91,7 @@ "item.refinedstorage2.wrench": "Wrench", "item.refinedstorage2.upgrade": "Upgrade", "item.refinedstorage2.speed_upgrade": "Speed Upgrade", + "item.refinedstorage2.stack_upgrade": "Stack Upgrade", "item.refinedstorage2.upgrade.supported_by": "Supported by:", "misc.refinedstorage2.stored": "Stored: %s", "misc.refinedstorage2.stored_with_capacity": "Stored: %s / %s", diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/stack_upgrade.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/stack_upgrade.json new file mode 100644 index 000000000..5adf4a82d --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/stack_upgrade.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "refinedstorage2:item/stack_upgrade" + } +} diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/item/stack_upgrade.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/item/stack_upgrade.png new file mode 100644 index 0000000000000000000000000000000000000000..4809b9831d7c7290f5683b59736896558106541c GIT binary patch literal 1510 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`k|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*9U+n9DLlB1$5BeXNr6bM+EIYV;~{3xK*A7;Nk-3KEmEQ%e+* zQqwc@Y?a>c-mj#PnPRIHZt82`Ti~3Uk?B!Ylp0*+7m{3+ootz+WN)WnQ(*-(AUCxn zQK2F?C$HG5!d3}vt`(3C64qBz04piUwpD^SD#ABF!8yMuRl!uxOgGuk&``nLQqR!T z!q~`EN5ROz&{W^RQs2-(*TB%q(7?*bKmiJrfVLH-q*(>IxIyg#@@$ndN=gc>^!3Zj z%k|2Q_413-^$jg8E%gnI^o@*kfhu&1EAvVcD|GXUm0>2hq!uR^WfqiV=I1GZOiWD5 zFD#PU%0_}#n6BP2AO_EVu8M)o`HUDF34YC)x{-2sR(CaRb3oXS&*t9 zlvEeuVQbq#?b3Jgypvt&bam^s+=8#=qWS{fKynmW5085+8p zS(+PLTDX}wnwq*gnj1Ts!t{FP6_+IDC8xsd&IH;G)oX!Qua$FAYGO%#QAmD%4lES} zWaO9R7iZ)bC^$QVV_iWbJTosPzr0uz6ipCcyQCInmZhe+73JqDfWz4;6Pp_>($b7f zERA$c&5aFo6O&C$buE$%EOmjwVqs`*oMdilV4?)opF(c<=>r|54@xXZi3cVGOpzca zJSzY>@XVB&2h2f5z^tOW?q@Os0~4F4i(^Q|t&++99YTd7$M**t`|QY;wQ6~$7`?0H zlE6VeQPm0_MV9X(bFFu~21-vncgc0n3rCT|V%JW`?P2BGbi}}Ep36ryk5e*DVc{ZE z;y>5T4u0LkUw3By_uBdQ%kSmSJ0QXAY9Mi>s=`KYo(vD$p(?-2CUtvTcpZ$t8AGz_$@zt>#bS0+u}2R*_Dom^0uGu)_id*$L!~(=7_G$d@K&a}`HYY5a_*Dg>- stackUpgrade = register( + Registry.ITEM, + ContentIds.STACK_UPGRADE, + new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) + ); + Items.INSTANCE.setStackUpgrade(stackUpgrade); + addApplicableUpgrades(speedUpgrade, stackUpgrade); } private void registerBlockEntities() { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/network/node/importer/StorageImporterTransferStrategyFactory.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/network/node/importer/StorageImporterTransferStrategyFactory.java index 74c0d217c..1480b0997 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/network/node/importer/StorageImporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/network/node/importer/StorageImporterTransferStrategyFactory.java @@ -19,24 +19,25 @@ public class StorageImporterTransferStrategyFactory implements ImporterTra private final StorageChannelType storageChannelType; private final Function fromPlatformMapper; private final Function toPlatformMapper; - private final long transferQuota; + private final long singleAmount; public StorageImporterTransferStrategyFactory(final BlockApiLookup, Direction> lookup, final StorageChannelType storageChannelType, final Function fromPlatformMapper, final Function toPlatformMapper, - final long transferQuota) { + final long singleAmount) { this.lookup = lookup; this.storageChannelType = storageChannelType; this.fromPlatformMapper = fromPlatformMapper; this.toPlatformMapper = toPlatformMapper; - this.transferQuota = transferQuota; + this.singleAmount = singleAmount; } @Override public ImporterTransferStrategy create(final ServerLevel level, final BlockPos pos, - final Direction direction) { + final Direction direction, + final boolean hasStackUpgrade) { final ImporterSource source = new StorageImporterSource<>( lookup, fromPlatformMapper, @@ -48,7 +49,7 @@ public ImporterTransferStrategy create(final ServerLevel level, return new ImporterTransferStrategyImpl<>( source, storageChannelType, - transferQuota + hasStackUpgrade ? singleAmount * 64 : singleAmount ); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java index 52f8fdef8..86ccc8adb 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java @@ -411,12 +411,16 @@ public long getEnergyUsage() { private class UpgradeImpl implements Upgrade { private final ForgeConfigSpec.LongValue speedUpgradeEnergyUsage; + private final ForgeConfigSpec.LongValue stackUpgradeEnergyUsage; UpgradeImpl() { builder.push("upgrade"); speedUpgradeEnergyUsage = builder .comment("The additional energy used per Speed Upgrade") .defineInRange(ENERGY_USAGE, 4, 0, Long.MAX_VALUE); + stackUpgradeEnergyUsage = builder + .comment("The additional energy used by the Stack Upgrade") + .defineInRange(ENERGY_USAGE, 16, 0, Long.MAX_VALUE); builder.pop(); } @@ -424,5 +428,10 @@ private class UpgradeImpl implements Upgrade { public long getSpeedUpgradeEnergyUsage() { return speedUpgradeEnergyUsage.get(); } + + @Override + public long getStackUpgradeEnergyUsage() { + return stackUpgradeEnergyUsage.get(); + } } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java index 3dfc2b760..4202d1580 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java @@ -107,6 +107,7 @@ import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.QUARTZ_ENRICHED_IRON_BLOCK; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.SILICON; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.SPEED_UPGRADE; +import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STACK_UPGRADE; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STORAGE_BLOCK; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STORAGE_HOUSING; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.UPGRADE; @@ -433,7 +434,12 @@ private void registerUpgrades() { () -> new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) ); Items.INSTANCE.setSpeedUpgrade(speedUpgrade); - addApplicableUpgrades(speedUpgrade); + final Supplier stackUpgrade = itemRegistry.register( + STACK_UPGRADE.getPath(), + () -> new SimpleUpgradeItem(CREATIVE_MODE_TAB, PlatformApi.INSTANCE.getUpgradeRegistry()) + ); + Items.INSTANCE.setStackUpgrade(stackUpgrade); + addApplicableUpgrades(speedUpgrade, stackUpgrade); } private void registerBlockEntities() { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/FluidHandlerImporterTransferStrategyFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/FluidHandlerImporterTransferStrategyFactory.java index 5e7c67113..c180f91c0 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/FluidHandlerImporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/FluidHandlerImporterTransferStrategyFactory.java @@ -16,7 +16,8 @@ public class FluidHandlerImporterTransferStrategyFactory implements ImporterTran @Override public ImporterTransferStrategy create(final ServerLevel level, final BlockPos pos, - final Direction direction) { + final Direction direction, + final boolean hasStackUpgrade) { final ImporterSource source = new FluidHandlerImporterSource( level, pos, @@ -25,7 +26,7 @@ public ImporterTransferStrategy create(final ServerLevel level, return new ImporterTransferStrategyImpl<>( source, StorageChannelTypes.FLUID, - FluidType.BUCKET_VOLUME + hasStackUpgrade ? FluidType.BUCKET_VOLUME * 64 : FluidType.BUCKET_VOLUME ); } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/ItemHandlerImporterTransferStrategyFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/ItemHandlerImporterTransferStrategyFactory.java index d30fb9052..e7ebd9d72 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/ItemHandlerImporterTransferStrategyFactory.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/network/node/importer/ItemHandlerImporterTransferStrategyFactory.java @@ -15,7 +15,8 @@ public class ItemHandlerImporterTransferStrategyFactory implements ImporterTrans @Override public ImporterTransferStrategy create(final ServerLevel level, final BlockPos pos, - final Direction direction) { + final Direction direction, + final boolean hasStackUpgrade) { final ImporterSource source = new ItemHandlerImporterSource( level, pos, @@ -24,7 +25,7 @@ public ImporterTransferStrategy create(final ServerLevel level, return new ImporterTransferStrategyImpl<>( source, StorageChannelTypes.ITEM, - 1 + hasStackUpgrade ? 64 : 1 ); } } From f9e3044792912627341be4db8265c1eb8a86cef6 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Mon, 1 Aug 2022 14:12:31 +0200 Subject: [PATCH 09/23] Fix Sonar issues. --- .../node/importer/ImporterNetworkNode.java | 1 - .../importer/ImporterNetworkNodeTest.java | 26 ++++++++++--------- .../network/test/extension/AddImporter.java | 16 ------------ .../test/extension/NetworkTestExtension.java | 15 ++--------- .../block/entity/ImporterBlockEntity.java | 4 +-- .../common/block/entity/UpgradeConstants.java | 4 +-- .../transfer/TransferManager.java | 4 +-- 7 files changed, 22 insertions(+), 48 deletions(-) delete mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddImporter.java diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java index 4ed1d54c2..cf765ca16 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java @@ -65,7 +65,6 @@ public void setFilterTemplates(final Set templates) { public void setCoolDownTime(final long coolDownTime) { this.coolDownTime = coolDownTime; - this.coolDownTimer = coolDownTime; } public void setEnergyUsage(final long energyUsage) { diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java index b792e9449..59652497f 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java @@ -3,7 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; import com.refinedmods.refinedstorage2.api.network.test.NetworkTestFixtures; -import com.refinedmods.refinedstorage2.api.network.test.extension.AddImporter; +import com.refinedmods.refinedstorage2.api.network.test.extension.AddNetworkNode; import com.refinedmods.refinedstorage2.api.network.test.extension.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.api.network.test.extension.NetworkTestExtension; import com.refinedmods.refinedstorage2.api.network.test.extension.SetupNetwork; @@ -16,6 +16,7 @@ import java.util.Set; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,9 +25,14 @@ @ExtendWith(NetworkTestExtension.class) @SetupNetwork class ImporterNetworkNodeTest { - @AddImporter(energyUsage = 5, coolDownTime = 3) + @AddNetworkNode ImporterNetworkNode sut; + @BeforeEach + void setUp() { + sut.setEnergyUsage(5); + } + @Test void testInitialState() { // Assert @@ -230,9 +236,10 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor 1 ); sut.setTransferStrategy(strategy); + sut.setCoolDownTime(3); // Act & assert - sut.update(); // do it once, cooldown is now = 3 + sut.update(); // Do it once, cooldown is now = 3 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -241,7 +248,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // cooldown is now = 2 + sut.update(); // Cooldown is now = 2 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -250,7 +257,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // cooldown is now = 1 + sut.update(); // Cooldown is now = 1 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -259,7 +266,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // cooldown is now = 0 + sut.update(); // Cooldown is now = 0 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -268,7 +275,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // do it another time, cooldown is now = 3 + sut.update(); // Do it another time, cooldown is now = 3 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 2) ); @@ -335,11 +342,6 @@ void shouldRespectAllowlistWithNormalizer( // Act sut.update(); - // cooldown - sut.update(); - sut.update(); - sut.update(); - // Act 2 sut.update(); // Assert diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddImporter.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddImporter.java deleted file mode 100644 index 821b19fb1..000000000 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddImporter.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.refinedmods.refinedstorage2.api.network.test.extension; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface AddImporter { - long energyUsage() default 0L; - - long coolDownTime() default 0L; - - String networkId() default "default"; -} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java index 02c617a34..0fb69532a 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java @@ -86,7 +86,6 @@ private void addNetworkNodes(final Object testInstance) { for (final Field field : fields) { tryAddSimpleNetworkNode(testInstance, field); tryAddDiskDrive(testInstance, field); - tryAddImporter(testInstance, field); } } @@ -103,18 +102,6 @@ private void tryAddDiskDrive(final Object testInstance, final Field field) { } } - private void tryAddImporter(final Object testInstance, final Field field) { - final AddImporter annotation = field.getAnnotation(AddImporter.class); - if (annotation != null) { - final NetworkNode resolvedNode = new ImporterNetworkNode( - annotation.energyUsage(), - annotation.coolDownTime() - ); - final Network network = networkMap.get(annotation.networkId()); - registerNetworkNode(testInstance, field, resolvedNode, network); - } - } - private void tryAddSimpleNetworkNode(final Object testInstance, final Field field) { final AddNetworkNode annotation = field.getAnnotation(AddNetworkNode.class); if (annotation != null) { @@ -131,6 +118,8 @@ private NetworkNode resolveSimpleNetworkNode(final Class type, final long ene return new SpyingNetworkNode(energyUsage); } else if (type == GridNetworkNode.class) { return new GridNetworkNode<>(energyUsage, NetworkTestFixtures.STORAGE_CHANNEL_TYPE); + } else if (type == ImporterNetworkNode.class) { + return new ImporterNetworkNode(energyUsage, 0); } throw new RuntimeException(type.getName()); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index 25112c7a7..c7cdffd2b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -57,7 +57,7 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { state, new ImporterNetworkNode( calculateEnergyUsage(0, false), - UpgradeConstants.DEFAULT_COOL_DOWN_TIMER + UpgradeConstants.calculateCoolDownTime(0) ) ); getNode().setNormalizer(this::normalize); @@ -195,10 +195,10 @@ private void initializeResourceFilter() { private void upgradeContainerChanged() { initializeUpgrades(); + setChanged(); if (level instanceof ServerLevel serverLevel) { updateTransferStrategy(serverLevel); } - setChanged(); } private void initializeUpgrades() { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java index 41b97b332..88b596204 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java @@ -2,13 +2,13 @@ public final class UpgradeConstants { public static final int UPGRADE_SLOTS = 4; - public static final long DEFAULT_COOL_DOWN_TIMER = 8; + private static final long DEFAULT_COOL_DOWN_TIMER = 8; private UpgradeConstants() { } public static long calculateCoolDownTime(final long amountOfSpeedUpgrades) { return DEFAULT_COOL_DOWN_TIMER - - (long) ((double) amountOfSpeedUpgrades / (double) UPGRADE_SLOTS * (double) DEFAULT_COOL_DOWN_TIMER); + - (long) (amountOfSpeedUpgrades / (double) UPGRADE_SLOTS * DEFAULT_COOL_DOWN_TIMER); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java index a897b3150..83d619c42 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/transfer/TransferManager.java @@ -74,7 +74,7 @@ private void transfer(final Slot slot, final List destinati } private ItemStack doTransfer(final ItemStack initial, final List destinations) { - ItemStack remainder = initial.copy(); + ItemStack remainder = initial; for (final TransferDestination destination : destinations) { final ItemStack destinationRemainder = destination.transfer(remainder); if (destinationRemainder == null) { @@ -82,7 +82,7 @@ private ItemStack doTransfer(final ItemStack initial, final List Date: Mon, 1 Aug 2022 20:55:18 +0200 Subject: [PATCH 10/23] Simplify activeness code and node updating. --- .../api/network/node/AbstractNetworkNode.java | 36 ++-------- .../api/network/node/NetworkNode.java | 4 -- ...etworkNode.java => SimpleNetworkNode.java} | 4 +- .../controller/ControllerNetworkNode.java | 5 -- .../node/diskdrive/DiskDriveNetworkNode.java | 2 +- .../network/node/grid/GridNetworkNode.java | 2 +- .../node/importer/ImporterNetworkNode.java | 6 +- .../node/storage/StorageNetworkNode.java | 2 +- .../component/EnergyNetworkComponentTest.java | 2 + .../StorageNetworkComponentTest.java | 4 +- .../api/network/node/NetworkNodeImplTest.java | 66 ------------------- .../network/node/SimpleNetworkNodeTest.java | 48 ++++++++++++++ .../controller/ControllerNetworkNodeTest.java | 44 +++---------- .../diskdrive/DiskDriveNetworkNodeTest.java | 20 +++--- .../node/grid/GridNetworkNodeTest.java | 8 +-- .../importer/ImporterNetworkNodeTest.java | 42 ++++++------ .../node/storage/StorageNetworkNodeTest.java | 14 ++-- .../network/test/extension/AddDiskDrive.java | 2 + .../test/extension/AddNetworkNode.java | 2 + .../test/extension/NetworkTestExtension.java | 35 +++++----- .../extension/NetworkTestExtensionTest.java | 9 ++- ...ternalNetworkNodeContainerBlockEntity.java | 46 ++++++------- .../common/block/entity/CableBlockEntity.java | 6 +- .../block/entity/ControllerBlockEntity.java | 7 +- .../AbstractDiskDriveBlockEntity.java | 9 ++- .../ticker/NetworkNodeBlockEntityTicker.java | 4 +- 26 files changed, 188 insertions(+), 241 deletions(-) rename refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/{CableNetworkNode.java => SimpleNetworkNode.java} (65%) delete mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNodeImplTest.java create mode 100644 refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractNetworkNode.java index de93178d1..c14f895ef 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/AbstractNetworkNode.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; -import java.util.function.BooleanSupplier; import javax.annotation.Nullable; import org.apiguardian.api.API; @@ -12,15 +11,8 @@ public abstract class AbstractNetworkNode implements NetworkNode { @Nullable protected Network network; - @Nullable - protected BooleanSupplier activenessProvider; - private boolean active; - public void setActivenessProvider(@Nullable final BooleanSupplier activenessProvider) { - this.activenessProvider = activenessProvider; - } - @Override @Nullable public Network getNetwork() { @@ -32,31 +24,17 @@ public void setNetwork(@Nullable final Network network) { this.network = network; } - @Override - public boolean isActive() { - if (network == null || (activenessProvider != null && !activenessProvider.getAsBoolean())) { - return false; - } - final long stored = network.getComponent(EnergyNetworkComponent.class).getStored(); - return stored >= getEnergyUsage(); - } - - @Override - public void update() { - updateActiveness(); - extractEnergy(); + public void setActive(final boolean active) { + this.active = active; + onActiveChanged(active); } - private void updateActiveness() { - final boolean newActive = isActive(); - if (active != newActive) { - active = newActive; - onActiveChanged(active); - } + public boolean isActive() { + return active; } - private void extractEnergy() { - if (!active || network == null) { + public void doWork() { + if (network == null || !active) { return; } network.getComponent(EnergyNetworkComponent.class).extract(getEnergyUsage()); diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNode.java index 4a684820f..04caca23a 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNode.java @@ -12,8 +12,4 @@ public interface NetworkNode { Network getNetwork(); void setNetwork(@Nullable Network network); - - boolean isActive(); - - void update(); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/CableNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNode.java similarity index 65% rename from refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/CableNetworkNode.java rename to refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNode.java index 7e28df850..17eba93bd 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/CableNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNode.java @@ -1,9 +1,9 @@ package com.refinedmods.refinedstorage2.api.network.node; -public class CableNetworkNode extends AbstractNetworkNode { +public final class SimpleNetworkNode extends AbstractNetworkNode { private final long energyUsage; - public CableNetworkNode(final long energyUsage) { + public SimpleNetworkNode(final long energyUsage) { this.energyUsage = energyUsage; } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNode.java index 636b15cb2..692ef3ba3 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNode.java @@ -35,11 +35,6 @@ private ControllerEnergyState getState(final double pct) { return ControllerEnergyState.OFF; } - @Override - public boolean isActive() { - return activenessProvider == null || activenessProvider.getAsBoolean(); - } - @Override public long getStored() { if (!isActive()) { diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java index b12389588..65aa01639 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java @@ -137,7 +137,7 @@ private void updateDiskCount() { } @Override - public void onActiveChanged(final boolean newActive) { + protected void onActiveChanged(final boolean newActive) { super.onActiveChanged(newActive); if (network == null) { return; diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java index 668823709..aa23e08cf 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java @@ -65,7 +65,7 @@ public void removeWatcher(final GridWatcher watcher) { } @Override - public void onActiveChanged(final boolean newActive) { + protected void onActiveChanged(final boolean newActive) { super.onActiveChanged(newActive); watchers.forEach(watcher -> watcher.onActiveChanged(newActive)); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java index cf765ca16..7540a607c 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java @@ -32,14 +32,14 @@ public void setTransferStrategy(@Nullable final ImporterTransferStrategy transfe } @Override - public void update() { - super.update(); - if (transferStrategy != null && isActive()) { + public void doWork() { + if (isActive() && transferStrategy != null) { tryTransfer(transferStrategy); } } private void tryTransfer(final ImporterTransferStrategy strategy) { + // TODO: Remove timer from this crap. --coolDownTimer; if (coolDownTimer < 0) { strategy.transfer(filter, actor, Objects.requireNonNull(network)); diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/storage/StorageNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/storage/StorageNetworkNode.java index c784ab729..dcb87cb40 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/storage/StorageNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/storage/StorageNetworkNode.java @@ -57,7 +57,7 @@ public void initializeNewStorage(final StorageRepository storageRepository, } @Override - public void onActiveChanged(final boolean newActive) { + protected void onActiveChanged(final boolean newActive) { super.onActiveChanged(newActive); if (network == null || internalStorage == null) { return; diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/EnergyNetworkComponentTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/EnergyNetworkComponentTest.java index e83dccca2..256ee4ad7 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/EnergyNetworkComponentTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/EnergyNetworkComponentTest.java @@ -26,6 +26,7 @@ void shouldUpdateEnergyStorageAfterAddingNode() { final EnergyNetworkComponent sut = new EnergyNetworkComponent(); final ControllerNetworkNode controller = new ControllerNetworkNode(); + controller.setActive(true); controller.setEnergyStorage(new EnergyStorageImpl(1000)); controller.receive(100, Action.EXECUTE); final NetworkNodeContainer container = () -> controller; @@ -55,6 +56,7 @@ void shouldUpdateEnergyStorageAfterRemovingNode() { final ControllerNetworkNode controller = new ControllerNetworkNode(); controller.setEnergyStorage(new EnergyStorageImpl(1000)); controller.receive(100, Action.EXECUTE); + controller.setActive(true); final NetworkNodeContainer container = () -> controller; sut.onContainerAdded(container); diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java index 57898054c..f6bc0680d 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java @@ -43,13 +43,13 @@ void setUp() { diskDrive.setListener(mock(DiskDriveListener.class)); diskDrive.setDiskProvider(storageProviderRepository); diskDrive.initialize(storageProviderRepository); - diskDrive.onActiveChanged(true); + diskDrive.setActive(true); diskDriveContainer = () -> diskDrive; storage = new StorageNetworkNode<>(0, NetworkTestFixtures.STORAGE_CHANNEL_TYPE); storage.setNetwork(new NetworkImpl(NetworkTestFixtures.NETWORK_COMPONENT_MAP_FACTORY)); storage.initializeNewStorage(storageProviderRepository, new LimitedStorageImpl<>(100), UUID.randomUUID()); - storage.onActiveChanged(true); + storage.setActive(true); storageContainer = () -> storage; } diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNodeImplTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNodeImplTest.java deleted file mode 100644 index 78045203c..000000000 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/NetworkNodeImplTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.refinedmods.refinedstorage2.api.network.node; - -import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; -import com.refinedmods.refinedstorage2.api.network.test.SpyingNetworkNode; -import com.refinedmods.refinedstorage2.api.network.test.extension.AddNetworkNode; -import com.refinedmods.refinedstorage2.api.network.test.extension.InjectNetworkEnergyComponent; -import com.refinedmods.refinedstorage2.api.network.test.extension.NetworkTestExtension; -import com.refinedmods.refinedstorage2.api.network.test.extension.SetupNetwork; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import static org.assertj.core.api.Assertions.assertThat; - -@ExtendWith(NetworkTestExtension.class) -@SetupNetwork(energyStored = 10, energyCapacity = 100) -class NetworkNodeImplTest { - @AddNetworkNode(energyUsage = 10) - SpyingNetworkNode sut; - - @AddNetworkNode(energyUsage = 11) - SpyingNetworkNode insufficientEnergyNetworkNode; - - @Test - void shouldBeActiveWithSufficientEnergy() { - // Act - final boolean active = sut.isActive(); - - // Assert - assertThat(active).isTrue(); - } - - @Test - void shouldBeInactiveWithInsufficientEnergy() { - // Act - final boolean active = insufficientEnergyNetworkNode.isActive(); - - // Assert - assertThat(active).isFalse(); - } - - @Test - void shouldExtractEnergyWhenUpdating(@InjectNetworkEnergyComponent final EnergyNetworkComponent energy) { - // Act - sut.update(); - - // Assert - assertThat(energy.getStored()).isZero(); - } - - @Test - void shouldNotifyOnActivenessChange() { - // Act - // Energy stored now: 20 - Call 1 - false -> true - sut.update(); - // Energy stored now: 10 - No call - sut.update(); - // Energy stored now: 0 - Call 2 - true -> false - sut.update(); - // Energy stored now: 0 - No call - sut.update(); - - // Assert - assertThat(sut.getActivenessChanges()).isEqualTo(2); - } -} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java new file mode 100644 index 000000000..e3d621448 --- /dev/null +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java @@ -0,0 +1,48 @@ +package com.refinedmods.refinedstorage2.api.network.node; + +import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.test.extension.AddNetworkNode; +import com.refinedmods.refinedstorage2.api.network.test.extension.InjectNetworkEnergyComponent; +import com.refinedmods.refinedstorage2.api.network.test.extension.NetworkTestExtension; +import com.refinedmods.refinedstorage2.api.network.test.extension.SetupNetwork; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(NetworkTestExtension.class) +@SetupNetwork(energyStored = 10, energyCapacity = 100) +class SimpleNetworkNodeTest { + @AddNetworkNode(energyUsage = 10, active = false) + SimpleNetworkNode sut; + + @Test + void testInitialState() { + // Assert + assertThat(sut.isActive()).isFalse(); + assertThat(sut.getNetwork()).isNotNull(); + assertThat(sut.getEnergyUsage()).isEqualTo(10); + } + + @Test + void shouldNotExtractEnergyWhenInactive(@InjectNetworkEnergyComponent final EnergyNetworkComponent energy) { + // Act + sut.doWork(); + + // Assert + assertThat(energy.getStored()).isEqualTo(10); + } + + @Test + void shouldExtractEnergy(@InjectNetworkEnergyComponent final EnergyNetworkComponent energy) { + // Arrange + sut.setActive(true); + + // Act + sut.doWork(); + + // Assert + assertThat(energy.getStored()).isZero(); + } +} diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNodeTest.java index c7326de32..e8b4cd8ff 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/controller/ControllerNetworkNodeTest.java @@ -2,53 +2,33 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorageImpl; +import com.refinedmods.refinedstorage2.api.network.test.extension.AddNetworkNode; +import com.refinedmods.refinedstorage2.api.network.test.extension.NetworkTestExtension; +import com.refinedmods.refinedstorage2.api.network.test.extension.SetupNetwork; import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; import static org.assertj.core.api.Assertions.assertThat; +@ExtendWith(NetworkTestExtension.class) +@SetupNetwork class ControllerNetworkNodeTest { - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void shouldAlwaysBeActive(final boolean explicitlyActive) { - // Arrange - final ControllerNetworkNode sut = new ControllerNetworkNode(); - sut.setEnergyStorage(new EnergyStorageImpl(100)); - if (explicitlyActive) { - sut.setActivenessProvider(() -> true); - } - - // Assert - assertThat(sut.isActive()).isTrue(); - assertThat(sut.getEnergyUsage()).isZero(); - } - - @Test - void shouldAlwaysBeActiveUnlessToldNotTo() { - // Arrange - final ControllerNetworkNode sut = new ControllerNetworkNode(); - sut.setEnergyStorage(new EnergyStorageImpl(100)); - sut.setActivenessProvider(() -> false); - - // Assert - assertThat(sut.isActive()).isFalse(); - assertThat(sut.getEnergyUsage()).isZero(); - } + @AddNetworkNode + ControllerNetworkNode sut; @Test void testStoredAndCapacityWhenInactive() { // Arrange - final ControllerNetworkNode sut = new ControllerNetworkNode(); sut.setEnergyStorage(new EnergyStorageImpl(100)); sut.receive(10, Action.EXECUTE); - sut.setActivenessProvider(() -> false); + sut.setActive(false); // Act final long stored = sut.getStored(); @@ -80,7 +60,6 @@ private static Stream getStoredAndExpectedState() { @MethodSource("getStoredAndExpectedState") void testCalculatingStates(final long stored, final ControllerEnergyState expectedState) { // Arrange - final ControllerNetworkNode sut = new ControllerNetworkNode(); sut.setEnergyStorage(new EnergyStorageImpl(100)); sut.receive(stored, Action.EXECUTE); @@ -94,10 +73,9 @@ void testCalculatingStates(final long stored, final ControllerEnergyState expect @Test void testEnergyStateShouldBeOffWhenInactive() { // Arrange - final ControllerNetworkNode sut = new ControllerNetworkNode(); sut.setEnergyStorage(new EnergyStorageImpl(100)); sut.receive(50, Action.EXECUTE); - sut.setActivenessProvider(() -> false); + sut.setActive(false); // Act final ControllerEnergyState state = sut.getState(); @@ -109,7 +87,6 @@ void testEnergyStateShouldBeOffWhenInactive() { @Test void shouldReceiveEnergy() { // Arrange - final ControllerNetworkNode sut = new ControllerNetworkNode(); sut.setEnergyStorage(new EnergyStorageImpl(100)); // Act @@ -126,7 +103,6 @@ void shouldReceiveEnergy() { @Test void shouldExtractEnergy() { // Arrange - final ControllerNetworkNode sut = new ControllerNetworkNode(); sut.setEnergyStorage(new EnergyStorageImpl(100)); // Act diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java index 50ffc600f..bf921a976 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java @@ -115,10 +115,7 @@ void testDiskState(final boolean active) { // Act sut.initialize(storageProviderRepository); - sut.setActivenessProvider(() -> active); - if (active) { - sut.onActiveChanged(true); - } + sut.setActive(active); final DiskDriveState state = sut.createState(); @@ -230,8 +227,7 @@ void shouldNotUpdateNetworkStorageWhenChangingDiskWhenInactive( // Act final Collection> preInactiveness = new HashSet<>(networkStorage.getAll()); - sut.onActiveChanged(false); - sut.setActivenessProvider(() -> false); + sut.setActive(false); sut.onDiskChanged(1); final Collection> postInactiveness = networkStorage.getAll(); @@ -491,7 +487,7 @@ void shouldNotAllowInsertsWhenInactive( storageProviderRepository.setInSlot(1, storage); initializeDiskDriveAndActivate(); - sut.setActivenessProvider(() -> false); + sut.setActive(false); // Act final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); @@ -509,7 +505,7 @@ void shouldNotAllowExtractsWhenInactive( storageProviderRepository.setInSlot(1, storage); initializeDiskDriveAndActivate(); - sut.setActivenessProvider(() -> false); + sut.setActive(false); // Act final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); @@ -530,7 +526,7 @@ void shouldHideFromNetworkWhenInactive( // Act final Collection> preInactiveness = new HashSet<>(networkStorage.getAll()); - sut.onActiveChanged(false); + sut.setActive(false); final Collection> postInactiveness = networkStorage.getAll(); // Assert @@ -548,7 +544,7 @@ void shouldShowOnNetworkWhenActive(@InjectNetworkStorageChannel final StorageCha sut.initialize(storageProviderRepository); // Act - sut.onActiveChanged(true); + sut.setActive(true); // Assert assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( @@ -647,7 +643,7 @@ void shouldTrackChanges(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Act - sut.update(); + sut.doWork(); // Assert assertThat(storageChannel.getAll()).isEmpty(); @@ -63,10 +63,10 @@ void testWithoutActiveness(@InjectNetworkStorageChannel final StorageChannel false); + sut.setActive(false); // Act - sut.update(); + sut.doWork(); // Assert assertThat(storageChannel.getAll()).isEmpty(); @@ -92,7 +92,7 @@ void testTransfer(@InjectNetworkStorageChannel final StorageChannel stor sut.setTransferStrategy(strategy); // Act - sut.update(); + sut.doWork(); // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( @@ -122,7 +122,7 @@ void testTransferWithoutSpaceInNetwork( sut.setTransferStrategy(strategy); // Act - sut.update(); + sut.doWork(); // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( @@ -151,7 +151,7 @@ void testTransferOverMultipleSlots( sut.setTransferStrategy(strategy); // Act - sut.update(); + sut.doWork(); // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( @@ -187,7 +187,7 @@ public long insert(final String resource, final long amount, final Action action sut.setTransferStrategy(strategy); // Act - sut.update(); + sut.doWork(); // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( @@ -215,7 +215,7 @@ void testTransferWithoutAnyResourcesInSource( sut.setTransferStrategy(strategy); // Act - sut.update(); + sut.doWork(); // Assert assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().isEmpty(); @@ -239,7 +239,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor sut.setCoolDownTime(3); // Act & assert - sut.update(); // Do it once, cooldown is now = 3 + sut.doWork(); // Do it once, cooldown is now = 3 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -248,7 +248,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // Cooldown is now = 2 + sut.doWork(); // Cooldown is now = 2 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -257,7 +257,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // Cooldown is now = 1 + sut.doWork(); // Cooldown is now = 1 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -266,7 +266,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // Cooldown is now = 0 + sut.doWork(); // Cooldown is now = 0 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 1) ); @@ -275,7 +275,7 @@ void testCoolDown(@InjectNetworkStorageChannel final StorageChannel stor new ResourceAmount<>("B", 5) ); - sut.update(); // Do it another time, cooldown is now = 3 + sut.doWork(); // Do it another time, cooldown is now = 3 assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( new ResourceAmount<>("A", 2) ); @@ -305,7 +305,7 @@ void shouldRespectAllowlist(@InjectNetworkStorageChannel final StorageChannel false); + sut.setActive(false); // Act final long inserted = networkStorage.insert("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); @@ -307,7 +307,7 @@ void shouldNotExtractWhenInactive(@InjectNetworkStorageChannel final StorageChan sut.initializeNewStorage(storageRepository, storage, UUID.randomUUID()); activateStorage(); - sut.setActivenessProvider(() -> false); + sut.setActive(false); // Act final long extracted = networkStorage.extract("A", 5, Action.EXECUTE, EmptyActor.INSTANCE); @@ -327,7 +327,7 @@ void shouldHideStorageContentsWhenInactive( activateStorage(); // Act - sut.onActiveChanged(false); + sut.setActive(false); // Assert assertThat(networkStorage.getAll()).isEmpty(); @@ -342,7 +342,7 @@ void shouldShowStorageContentsWhenActive(@InjectNetworkStorageChannel final Stor sut.initializeNewStorage(storageRepository, storage, UUID.randomUUID()); // Act - sut.onActiveChanged(true); + sut.setActive(true); // Assert assertThat(networkStorage.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( @@ -370,7 +370,7 @@ void shouldTrackChanges(@InjectNetworkStorageChannel final StorageChannel storage1 = new LimitedStorageImpl<>(100); sut.initializeNewStorage(storageRepository, storage1, UUID.randomUUID()); - sut.onActiveChanged(true); + sut.setActive(true); final LimitedStorageImpl storage2 = new LimitedStorageImpl<>(100); otherStorage.initializeNewStorage(storageRepository, storage2, UUID.randomUUID()); - otherStorage.onActiveChanged(true); + otherStorage.setActive(true); if (oneHasPriority) { sut.setPriority(5); diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java index 3953e2625..b57a99b6b 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java @@ -12,5 +12,7 @@ long energyUsagePerDisk() default 0L; + boolean active() default true; + String networkId() default "default"; } diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddNetworkNode.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddNetworkNode.java index b0f3be18e..ec0c687cd 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddNetworkNode.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddNetworkNode.java @@ -12,5 +12,7 @@ public @interface AddNetworkNode { long energyUsage() default 0L; + boolean active() default true; + String networkId() default "default"; } diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java index 0fb69532a..3e8c3a56e 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java @@ -7,19 +7,21 @@ import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorageImpl; +import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.NetworkNode; +import com.refinedmods.refinedstorage2.api.network.node.SimpleNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.controller.ControllerNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.diskdrive.DiskDriveNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.grid.GridNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.importer.ImporterNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.storage.StorageNetworkNode; import com.refinedmods.refinedstorage2.api.network.test.NetworkTestFixtures; -import com.refinedmods.refinedstorage2.api.network.test.SpyingNetworkNode; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; +import java.util.function.Function; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; @@ -29,6 +31,17 @@ import org.junit.jupiter.api.extension.ParameterResolver; public class NetworkTestExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver { + private static final Map, Function> SIMPLE_FACTORIES = Map.of( + StorageNetworkNode.class, a -> new StorageNetworkNode<>( + a.energyUsage(), + NetworkTestFixtures.STORAGE_CHANNEL_TYPE + ), + SimpleNetworkNode.class, a -> new SimpleNetworkNode(a.energyUsage()), + GridNetworkNode.class, a -> new GridNetworkNode<>(a.energyUsage(), NetworkTestFixtures.STORAGE_CHANNEL_TYPE), + ImporterNetworkNode.class, a -> new ImporterNetworkNode(a.energyUsage(), 0), + ControllerNetworkNode.class, a -> new ControllerNetworkNode() + ); + private final Map networkMap = new HashMap<>(); public NetworkTestExtension() { @@ -67,6 +80,7 @@ private void setupNetworkEnergy(final long capacity, final long stored, final Ne storage.receive(stored, Action.EXECUTE); final ControllerNetworkNode controller = new ControllerNetworkNode(); controller.setEnergyStorage(storage); + controller.setActive(true); component.onContainerAdded(() -> controller); } @@ -92,11 +106,12 @@ private void addNetworkNodes(final Object testInstance) { private void tryAddDiskDrive(final Object testInstance, final Field field) { final AddDiskDrive annotation = field.getAnnotation(AddDiskDrive.class); if (annotation != null) { - final NetworkNode resolvedNode = new DiskDriveNetworkNode( + final DiskDriveNetworkNode resolvedNode = new DiskDriveNetworkNode( annotation.baseEnergyUsage(), annotation.energyUsagePerDisk(), NetworkTestFixtures.STORAGE_CHANNEL_TYPE_REGISTRY ); + resolvedNode.setActive(annotation.active()); final Network network = networkMap.get(annotation.networkId()); registerNetworkNode(testInstance, field, resolvedNode, network); } @@ -105,25 +120,13 @@ private void tryAddDiskDrive(final Object testInstance, final Field field) { private void tryAddSimpleNetworkNode(final Object testInstance, final Field field) { final AddNetworkNode annotation = field.getAnnotation(AddNetworkNode.class); if (annotation != null) { - final NetworkNode resolvedNode = resolveSimpleNetworkNode(field.getType(), annotation.energyUsage()); + final AbstractNetworkNode resolvedNode = SIMPLE_FACTORIES.get(field.getType()).apply(annotation); + resolvedNode.setActive(annotation.active()); final Network network = networkMap.get(annotation.networkId()); registerNetworkNode(testInstance, field, resolvedNode, network); } } - private NetworkNode resolveSimpleNetworkNode(final Class type, final long energyUsage) { - if (type == StorageNetworkNode.class) { - return new StorageNetworkNode<>(energyUsage, NetworkTestFixtures.STORAGE_CHANNEL_TYPE); - } else if (type == SpyingNetworkNode.class) { - return new SpyingNetworkNode(energyUsage); - } else if (type == GridNetworkNode.class) { - return new GridNetworkNode<>(energyUsage, NetworkTestFixtures.STORAGE_CHANNEL_TYPE); - } else if (type == ImporterNetworkNode.class) { - return new ImporterNetworkNode(energyUsage, 0); - } - throw new RuntimeException(type.getName()); - } - private void registerNetworkNode(final Object testInstance, final Field field, final NetworkNode networkNode, diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java index 10fe0a4a7..86e80db02 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java @@ -29,7 +29,7 @@ class NetworkTestExtensionTest { @AddNetworkNode(networkId = "a") StorageNetworkNode storageInA; - @AddDiskDrive(networkId = "b") + @AddDiskDrive(networkId = "b", active = false) DiskDriveNetworkNode storageInB; @Test @@ -40,6 +40,13 @@ void shouldInjectNetwork() { assertThat(a).isNotSameAs(b); } + @Test + void shouldSetActivenessOfNetworkNode() { + // Assert + assertThat(storageInA.isActive()).isTrue(); + assertThat(storageInB.isActive()).isFalse(); + } + @Test void shouldSetEnergyComponent() { // Arrange diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java index d1b5026c3..4224e7933 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.block.entity; +import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; import com.refinedmods.refinedstorage2.platform.api.blockentity.AbstractNetworkNodeContainerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.AbstractDirectionalBlock; @@ -33,13 +34,15 @@ protected AbstractInternalNetworkNodeContainerBlockEntity(final BlockEntityType< final BlockState state, final T node) { super(type, pos, state, node); - getNode().setActivenessProvider(this::isActive); } private boolean isActive() { - return level != null - && level.isLoaded(worldPosition) - && redstoneMode.isActive(level.hasNeighborSignal(worldPosition)); + final long energyUsage = getNode().getEnergyUsage(); + final boolean hasLevel = level != null && level.isLoaded(worldPosition); + return hasLevel + && redstoneMode.isActive(level.hasNeighborSignal(worldPosition)) + && getNode().getNetwork() != null + && getNode().getNetwork().getComponent(EnergyNetworkComponent.class).getStored() >= energyUsage; } @Override @@ -56,35 +59,37 @@ public void load(final CompoundTag tag) { } } - public void updateActivenessInLevel(final BlockState state, - @Nullable final BooleanProperty activenessProperty) { + public void updateActiveness(final BlockState state, + @Nullable final BooleanProperty activenessProperty) { if (lastActive == null) { - lastActive = determineInitialActiveness(state, activenessProperty); + lastActive = getNode().isActive(); } - final boolean active = getNode().isActive(); + final boolean active = isActive(); final boolean inTime = System.currentTimeMillis() - lastActiveChanged > ACTIVE_CHANGE_MINIMUM_INTERVAL_MS; if (active != lastActive && (lastActiveChanged == 0 || inTime)) { - LOGGER.info("Activeness state change for block at {}: {} -> {}", getBlockPos(), lastActive, active); + LOGGER.info("Activeness change for node at {}: {} -> {}", getBlockPos(), lastActive, active); this.lastActive = active; this.lastActiveChanged = System.currentTimeMillis(); - activenessChanged(active); - - if (activenessProperty != null) { - updateActivenessState(state, activenessProperty, active); - } + activenessChanged(state, active, activenessProperty); } } - private boolean determineInitialActiveness(final BlockState state, - @Nullable final BooleanProperty activenessProperty) { - if (activenessProperty != null) { - return state.getValue(activenessProperty); + protected void activenessChanged(final BlockState state, + final boolean newActive, + @Nullable final BooleanProperty activenessProperty) { + getNode().setActive(newActive); + + final boolean needToUpdateBlockState = activenessProperty != null + && state.getValue(activenessProperty) != newActive; + + if (needToUpdateBlockState) { + LOGGER.info("Sending block update for block at {} due to state change to {}", getBlockPos(), newActive); + updateActivenessState(state, activenessProperty, newActive); } - return getNode().isActive(); } private void updateActivenessState(final BlockState state, @@ -95,9 +100,6 @@ private void updateActivenessState(final BlockState state, } } - protected void activenessChanged(final boolean active) { - } - public RedstoneMode getRedstoneMode() { return redstoneMode; } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/CableBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/CableBlockEntity.java index b5073e7fb..09bfa59a6 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/CableBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/CableBlockEntity.java @@ -1,19 +1,19 @@ package com.refinedmods.refinedstorage2.platform.common.block.entity; -import com.refinedmods.refinedstorage2.api.network.node.CableNetworkNode; +import com.refinedmods.refinedstorage2.api.network.node.SimpleNetworkNode; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; -public class CableBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity { +public class CableBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity { public CableBlockEntity(final BlockPos pos, final BlockState state) { super( BlockEntities.INSTANCE.getCable(), pos, state, - new CableNetworkNode(Platform.INSTANCE.getConfig().getCable().getEnergyUsage()) + new SimpleNetworkNode(Platform.INSTANCE.getConfig().getCable().getEnergyUsage()) ); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java index b4a7637b3..0ef5abcb4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java @@ -71,7 +71,7 @@ public void updateEnergyTypeInLevel(final BlockState state) { if (energyType != inLevelEnergyType && (lastTypeChanged == 0 || inTime)) { LOGGER.info( - "Energy type state change for block at {}: {} -> {}", + "Energy type state change for Controller at {}: {} -> {}", getBlockPos(), inLevelEnergyType, energyType @@ -91,7 +91,10 @@ private void updateEnergyTypeInLevel(final BlockState state, final ControllerEne public void saveAdditional(final CompoundTag tag) { super.saveAdditional(tag); tag.putLong(TAG_STORED, getNode().getActualStored()); - // this is not deserialized on purpose and is only here for rendering purposes + saveRenderingInfo(tag); + } + + private void saveRenderingInfo(final CompoundTag tag) { tag.putLong(TAG_CAPACITY, getNode().getActualCapacity()); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java index 36e60db35..9ced48f91 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java @@ -45,6 +45,7 @@ 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.level.block.state.properties.BooleanProperty; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -143,9 +144,11 @@ public void setLevel(final Level level) { } @Override - public void activenessChanged(final boolean active) { - super.activenessChanged(active); - LevelUtil.updateBlock(level, worldPosition, this.getBlockState()); + public void activenessChanged(final BlockState state, + final boolean newActive, + @Nullable final BooleanProperty activenessProperty) { + super.activenessChanged(state, newActive, activenessProperty); + LevelUtil.updateBlock(level, worldPosition, getBlockState()); } /** diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java index 5fd9a37fd..7c9b3eecb 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java @@ -32,7 +32,7 @@ public NetworkNodeBlockEntityTicker(final Supplier> allowedTy @Override public void tick(final Level level, final BlockPos pos, final BlockState state, final T blockEntity) { - blockEntity.getNode().update(); - blockEntity.updateActivenessInLevel(state, activenessProperty); + blockEntity.updateActiveness(state, activenessProperty); + blockEntity.getNode().doWork(); } } From 29fcf628616a6ea727a2bf788883b3231530f28a Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Mon, 1 Aug 2022 21:06:23 +0200 Subject: [PATCH 11/23] Remove usage of cooldown timer in network API. --- .../node/importer/ImporterNetworkNode.java | 21 +---- .../importer/ImporterNetworkNodeTest.java | 78 +++---------------- .../test/extension/NetworkTestExtension.java | 2 +- ...ternalNetworkNodeContainerBlockEntity.java | 4 + .../block/entity/ImporterBlockEntity.java | 17 ++-- .../common/block/entity/UpgradeConstants.java | 8 +- .../ticker/NetworkNodeBlockEntityTicker.java | 2 +- 7 files changed, 34 insertions(+), 98 deletions(-) diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java index 7540a607c..5a3e10e6c 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java @@ -16,15 +16,11 @@ public class ImporterNetworkNode extends AbstractNetworkNode { private long energyUsage; private final Filter filter = new Filter(); private final Actor actor = new NetworkNodeActor(this); - private long coolDownTime; - private long coolDownTimer; - @Nullable private ImporterTransferStrategy transferStrategy; - public ImporterNetworkNode(final long energyUsage, final long coolDownTime) { + public ImporterNetworkNode(final long energyUsage) { this.energyUsage = energyUsage; - this.coolDownTime = coolDownTime; } public void setTransferStrategy(@Nullable final ImporterTransferStrategy transferStrategy) { @@ -34,16 +30,7 @@ public void setTransferStrategy(@Nullable final ImporterTransferStrategy transfe @Override public void doWork() { if (isActive() && transferStrategy != null) { - tryTransfer(transferStrategy); - } - } - - private void tryTransfer(final ImporterTransferStrategy strategy) { - // TODO: Remove timer from this crap. - --coolDownTimer; - if (coolDownTimer < 0) { - strategy.transfer(filter, actor, Objects.requireNonNull(network)); - coolDownTimer = coolDownTime; + transferStrategy.transfer(filter, actor, Objects.requireNonNull(network)); } } @@ -63,10 +50,6 @@ public void setFilterTemplates(final Set templates) { filter.setTemplates(templates); } - public void setCoolDownTime(final long coolDownTime) { - this.coolDownTime = coolDownTime; - } - public void setEnergyUsage(final long energyUsage) { this.energyUsage = energyUsage; } diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java index 4a5cd9202..055984de9 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java @@ -41,7 +41,9 @@ void testInitialState() { } @Test - void testWithoutTransferStrategy(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldNotWorkWithoutTransferStrategy( + @InjectNetworkStorageChannel final StorageChannel storageChannel + ) { // Act sut.doWork(); @@ -50,7 +52,7 @@ void testWithoutTransferStrategy(@InjectNetworkStorageChannel final StorageChann } @Test - void testWithoutActiveness(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldNotWorkWithoutBeingActive(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange storageChannel.addSource(new InMemoryStorageImpl<>()); @@ -106,7 +108,8 @@ void testTransfer(@InjectNetworkStorageChannel final StorageChannel stor @Test void testTransferWithoutSpaceInNetwork( - @InjectNetworkStorageChannel final StorageChannel storageChannel) { + @InjectNetworkStorageChannel final StorageChannel storageChannel + ) { // Arrange storageChannel.addSource(new LimitedStorageImpl<>(100)); storageChannel.insert("C", 100, Action.EXECUTE, EmptyActor.INSTANCE); @@ -136,7 +139,8 @@ void testTransferWithoutSpaceInNetwork( @Test void testTransferOverMultipleSlots( - @InjectNetworkStorageChannel final StorageChannel storageChannel) { + @InjectNetworkStorageChannel final StorageChannel storageChannel + ) { // Arrange storageChannel.addSource(new InMemoryStorageImpl<>()); @@ -164,7 +168,8 @@ void testTransferOverMultipleSlots( @Test void testTransferWhereResourceIsNotAccepted( - @InjectNetworkStorageChannel final StorageChannel storageChannel) { + @InjectNetworkStorageChannel final StorageChannel storageChannel + ) { // Arrange storageChannel.addSource(new InMemoryStorageImpl<>() { @Override @@ -222,69 +227,6 @@ void testTransferWithoutAnyResourcesInSource( assertThat(source.getAll()).isEmpty(); } - @Test - void testCoolDown(@InjectNetworkStorageChannel final StorageChannel storageChannel) { - // Arrange - storageChannel.addSource(new InMemoryStorageImpl<>()); - - final FakeImporterSource source = new FakeImporterSource("A", "B") - .add("A", 5) - .add("B", 5); - final ImporterTransferStrategy strategy = new ImporterTransferStrategyImpl<>( - source, - NetworkTestFixtures.STORAGE_CHANNEL_TYPE, - 1 - ); - sut.setTransferStrategy(strategy); - sut.setCoolDownTime(3); - - // Act & assert - sut.doWork(); // Do it once, cooldown is now = 3 - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) - ); - assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 4), - new ResourceAmount<>("B", 5) - ); - - sut.doWork(); // Cooldown is now = 2 - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) - ); - assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 4), - new ResourceAmount<>("B", 5) - ); - - sut.doWork(); // Cooldown is now = 1 - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) - ); - assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 4), - new ResourceAmount<>("B", 5) - ); - - sut.doWork(); // Cooldown is now = 0 - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 1) - ); - assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 4), - new ResourceAmount<>("B", 5) - ); - - sut.doWork(); // Do it another time, cooldown is now = 3 - assertThat(storageChannel.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactly( - new ResourceAmount<>("A", 2) - ); - assertThat(source.getAll()).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - new ResourceAmount<>("A", 3), - new ResourceAmount<>("B", 5) - ); - } - @Test void shouldRespectAllowlist(@InjectNetworkStorageChannel final StorageChannel storageChannel) { // Arrange diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java index 3e8c3a56e..19b1c2416 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java @@ -38,7 +38,7 @@ public class NetworkTestExtension implements BeforeEachCallback, AfterEachCallba ), SimpleNetworkNode.class, a -> new SimpleNetworkNode(a.energyUsage()), GridNetworkNode.class, a -> new GridNetworkNode<>(a.energyUsage(), NetworkTestFixtures.STORAGE_CHANNEL_TYPE), - ImporterNetworkNode.class, a -> new ImporterNetworkNode(a.energyUsage(), 0), + ImporterNetworkNode.class, a -> new ImporterNetworkNode(a.energyUsage()), ControllerNetworkNode.class, a -> new ControllerNetworkNode() ); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java index 4224e7933..674be2c8d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java @@ -109,6 +109,10 @@ public void setRedstoneMode(final RedstoneMode redstoneMode) { setChanged(); } + public void doWork() { + getNode().doWork(); + } + @Override public boolean canPerformOutgoingConnection(final Direction direction) { final Direction myDirection = getDirection(); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index c7cdffd2b..99278d010 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -19,6 +19,7 @@ import java.util.Set; import javax.annotation.Nullable; +import com.google.common.util.concurrent.RateLimiter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; @@ -50,15 +51,14 @@ public class ImporterBlockEntity extends AbstractInternalNetworkNodeContainerBlo private final UpgradeContainer upgradeContainer; private boolean exactMode; + private RateLimiter rateLimiter = UpgradeConstants.getRateLimiter(0); + public ImporterBlockEntity(final BlockPos pos, final BlockState state) { super( BlockEntities.INSTANCE.getImporter(), pos, state, - new ImporterNetworkNode( - calculateEnergyUsage(0, false), - UpgradeConstants.calculateCoolDownTime(0) - ) + new ImporterNetworkNode(calculateEnergyUsage(0, false)) ); getNode().setNormalizer(this::normalize); this.resourceFilterContainer = new ResourceFilterContainer( @@ -103,6 +103,13 @@ public void setLevel(final Level level) { updateTransferStrategy(serverLevel); } + @Override + public void doWork() { + if (rateLimiter.tryAcquire()) { + super.doWork(); + } + } + private void updateTransferStrategy(final ServerLevel serverLevel) { final Direction direction = getDirection(); if (direction == null) { @@ -204,7 +211,7 @@ private void upgradeContainerChanged() { private void initializeUpgrades() { final int amountOfSpeedUpgrades = upgradeContainer.countItem(Items.INSTANCE.getSpeedUpgrade()); final boolean hasStackUpgrade = hasStackUpgrade(); - getNode().setCoolDownTime(UpgradeConstants.calculateCoolDownTime(amountOfSpeedUpgrades)); + rateLimiter = UpgradeConstants.getRateLimiter(amountOfSpeedUpgrades); getNode().setEnergyUsage(calculateEnergyUsage(amountOfSpeedUpgrades, hasStackUpgrade)); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java index 88b596204..a22d48f80 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java @@ -1,14 +1,14 @@ package com.refinedmods.refinedstorage2.platform.common.block.entity; +import com.google.common.util.concurrent.RateLimiter; + public final class UpgradeConstants { public static final int UPGRADE_SLOTS = 4; - private static final long DEFAULT_COOL_DOWN_TIMER = 8; private UpgradeConstants() { } - public static long calculateCoolDownTime(final long amountOfSpeedUpgrades) { - return DEFAULT_COOL_DOWN_TIMER - - (long) (amountOfSpeedUpgrades / (double) UPGRADE_SLOTS * DEFAULT_COOL_DOWN_TIMER); + public static RateLimiter getRateLimiter(final long amountOfSpeedUpgrades) { + return RateLimiter.create(amountOfSpeedUpgrades + 1); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java index 7c9b3eecb..1818683a1 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/ticker/NetworkNodeBlockEntityTicker.java @@ -33,6 +33,6 @@ public NetworkNodeBlockEntityTicker(final Supplier> allowedTy @Override public void tick(final Level level, final BlockPos pos, final BlockState state, final T blockEntity) { blockEntity.updateActiveness(state, activenessProperty); - blockEntity.getNode().doWork(); + blockEntity.doWork(); } } From b26d39b013cc7eae36cf722be474b66f58a57bd0 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Mon, 1 Aug 2022 21:09:50 +0200 Subject: [PATCH 12/23] Reuse normalizer. --- .../platform/api/resource/FuzzyModeNormalizer.java | 10 ++++++++++ .../common/block/entity/ImporterBlockEntity.java | 12 +----------- .../diskdrive/AbstractDiskDriveBlockEntity.java | 12 +----------- .../storage/AbstractStorageBlockBlockEntity.java | 12 +----------- 4 files changed, 13 insertions(+), 33 deletions(-) diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/FuzzyModeNormalizer.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/FuzzyModeNormalizer.java index 6c9de7987..a7abed9c9 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/FuzzyModeNormalizer.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/FuzzyModeNormalizer.java @@ -2,4 +2,14 @@ public interface FuzzyModeNormalizer { T normalize(); + + static Object tryNormalize(boolean exactMode, Object value) { + if (exactMode) { + return value; + } + if (value instanceof FuzzyModeNormalizer normalizer) { + return normalizer.normalize(); + } + return value; + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index 99278d010..891785e03 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -60,7 +60,7 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { state, new ImporterNetworkNode(calculateEnergyUsage(0, false)) ); - getNode().setNormalizer(this::normalize); + getNode().setNormalizer(value -> FuzzyModeNormalizer.tryNormalize(exactMode, value)); this.resourceFilterContainer = new ResourceFilterContainer( PlatformApi.INSTANCE.getResourceTypeRegistry(), 9, @@ -73,16 +73,6 @@ public ImporterBlockEntity(final BlockPos pos, final BlockState state) { ); } - private Object normalize(final Object value) { - if (exactMode) { - return value; - } - if (value instanceof FuzzyModeNormalizer fuzzyModeNormalizer) { - return fuzzyModeNormalizer.normalize(); - } - return value; - } - // used to handle rotations @Override @SuppressWarnings("deprecation") diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java index 9ced48f91..41b431594 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java @@ -89,7 +89,7 @@ protected AbstractDiskDriveBlockEntity(final BlockPos pos, final BlockState stat )); getNode().setDiskProvider(diskInventory); getNode().setListener(this); - getNode().setNormalizer(this::normalize); + getNode().setNormalizer(value -> FuzzyModeNormalizer.tryNormalize(exactMode, value)); } public static boolean hasDisk(final CompoundTag tag, final int slot) { @@ -125,16 +125,6 @@ private void initializeResourceFilter() { getNode().setFilterTemplates(resourceFilterContainer.getTemplates()); } - private Object normalize(final Object value) { - if (exactMode) { - return value; - } - if (value instanceof FuzzyModeNormalizer fuzzyModeNormalizer) { - return fuzzyModeNormalizer.normalize(); - } - return value; - } - @Override public void setLevel(final Level level) { super.setLevel(level); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storage/AbstractStorageBlockBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storage/AbstractStorageBlockBlockEntity.java index f13cc9e9a..b6623cc18 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storage/AbstractStorageBlockBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storage/AbstractStorageBlockBlockEntity.java @@ -54,7 +54,7 @@ protected AbstractStorageBlockBlockEntity(final BlockEntityType type, final StorageNetworkNode node, final ResourceType resourceType) { super(type, pos, state, node); - node.setNormalizer(this::normalize); + getNode().setNormalizer(value -> FuzzyModeNormalizer.tryNormalize(exactMode, value)); this.resourceFilterContainer = new FilteredResourceFilterContainer( PlatformApi.INSTANCE.getResourceTypeRegistry(), 9, @@ -63,16 +63,6 @@ protected AbstractStorageBlockBlockEntity(final BlockEntityType type, ); } - private Object normalize(final Object value) { - if (exactMode) { - return value; - } - if (value instanceof FuzzyModeNormalizer fuzzyModeNormalizer) { - return fuzzyModeNormalizer.normalize(); - } - return value; - } - protected abstract PlatformStorage createStorage(Runnable listener); private void resourceFilterContainerChanged() { From b3a3d0f325b49e0d29ef0031b025bd169b260881 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Mon, 1 Aug 2022 21:55:42 +0200 Subject: [PATCH 13/23] Simplify grid container / listening code, hide StorageChannel implementation detail. --- .../api/core/CoreValidations.java | 6 + .../api/core/CoreValidationsTest.java | 12 ++ .../refinedstorage2/api/grid/GridWatcher.java | 15 ++- .../network/node/grid/GridNetworkNode.java | 39 +++++- .../node/grid/GridNetworkNodeTest.java | 125 ++++++++++++++++-- .../entity/grid/AbstractGridBlockEntity.java | 7 +- .../grid/AbstractGridContainerMenu.java | 15 +-- .../grid/FluidGridContainerMenu.java | 24 +--- .../grid/ItemGridContainerMenu.java | 24 +--- 9 files changed, 206 insertions(+), 61 deletions(-) diff --git a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/CoreValidations.java b/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/CoreValidations.java index fa95457f3..62fbd1415 100644 --- a/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/CoreValidations.java +++ b/refinedstorage2-core-api/src/main/java/com/refinedmods/refinedstorage2/api/core/CoreValidations.java @@ -61,4 +61,10 @@ public static void validateContains(final Collection collection, final T throw new IllegalArgumentException(message); } } + + public static void validateNotContains(final Collection collection, final T value, final String message) { + if (collection.contains(value)) { + throw new IllegalArgumentException(message); + } + } } diff --git a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java b/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java index 51de85174..c41903baf 100644 --- a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java +++ b/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java @@ -102,4 +102,16 @@ void shouldValidateContains() { assertDoesNotThrow(() -> CoreValidations.validateContains(List.of(1), 1, "bla")); } + + @Test + void shouldValidateNotContains() { + // Act & assert + final Exception e = assertThrows( + IllegalArgumentException.class, + () -> CoreValidations.validateNotContains(List.of(1), 1, "bla") + ); + assertThat(e.getMessage()).isEqualTo("bla"); + + assertDoesNotThrow(() -> CoreValidations.validateNotContains(List.of(1), 2, "bla")); + } } diff --git a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/GridWatcher.java b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/GridWatcher.java index d575fc04d..b6cd755c6 100644 --- a/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/GridWatcher.java +++ b/refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/GridWatcher.java @@ -1,16 +1,29 @@ package com.refinedmods.refinedstorage2.api.grid; +import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; +import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; + +import javax.annotation.Nullable; + import org.apiguardian.api.API; /** * A grid listener. */ @API(status = API.Status.STABLE, since = "2.0.0-milestone.1.0") -public interface GridWatcher { +public interface GridWatcher { /** * Called when the activeness state of the grid has changed. * * @param newActive the new activeness state */ void onActiveChanged(boolean newActive); + + /** + * Called when a resource is changed. + * + * @param change the change + * @param trackedResource the tracked resource, if present + */ + void onChanged(ResourceListOperationResult change, @Nullable TrackedResource trackedResource); } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java index aa23e08cf..1d2cb5264 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNode.java @@ -1,18 +1,26 @@ package com.refinedmods.refinedstorage2.api.network.node.grid; +import com.refinedmods.refinedstorage2.api.core.CoreValidations; import com.refinedmods.refinedstorage2.api.grid.GridWatcher; +import com.refinedmods.refinedstorage2.api.grid.service.GridService; +import com.refinedmods.refinedstorage2.api.grid.service.GridServiceImpl; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; import com.refinedmods.refinedstorage2.api.network.node.AbstractNetworkNode; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.list.listenable.ResourceListListener; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; +import java.util.HashMap; import java.util.HashSet; +import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; +import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -20,7 +28,8 @@ public class GridNetworkNode extends AbstractNetworkNode { private static final Logger LOGGER = LogManager.getLogger(); - private final Set watchers = new HashSet<>(); + private final Set> watchers = new HashSet<>(); + private final Map, ResourceListListener> associatedResourceListeners = new HashMap<>(); private final long energyUsage; private final StorageChannelType type; @@ -29,7 +38,7 @@ public GridNetworkNode(final long energyUsage, final StorageChannelType type) this.type = type; } - public StorageChannel getStorageChannel() { + private StorageChannel getStorageChannel() { if (network == null) { throw new IllegalStateException("Network must be present to retrieve storage channel"); } @@ -54,16 +63,38 @@ public long getEnergyUsage() { return energyUsage; } - public void addWatcher(final GridWatcher watcher) { + public void addWatcher(final GridWatcher watcher, + final Class actorType) { + CoreValidations.validateNotContains(watchers, watcher, "Watcher is already registered"); watchers.add(watcher); + final StorageChannel storageChannel = getStorageChannel(); + final ResourceListListener listener = change -> watcher.onChanged( + change, + storageChannel.findTrackedResourceByActorType( + change.resourceAmount().getResource(), + actorType + ).orElse(null) + ); + storageChannel.addListener(listener); + associatedResourceListeners.put(watcher, listener); LOGGER.info("Watcher was added, new count is {}", watchers.size()); } - public void removeWatcher(final GridWatcher watcher) { + public void removeWatcher(final GridWatcher watcher) { + CoreValidations.validateContains(watchers, watcher, "Watcher is not registered"); watchers.remove(watcher); + final ResourceListListener listener = Objects.requireNonNull(associatedResourceListeners.get(watcher)); + getStorageChannel().removeListener(listener); + associatedResourceListeners.remove(watcher); LOGGER.info("Watcher was removed, new count is {}", watchers.size()); } + public GridService createService(final Actor actor, + final Function maxAmountProvider, + final long singleAmount) { + return new GridServiceImpl<>(getStorageChannel(), actor, maxAmountProvider, singleAmount); + } + @Override protected void onActiveChanged(final boolean newActive) { super.onActiveChanged(newActive); diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNodeTest.java index 263638062..9411d49f7 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/grid/GridNetworkNodeTest.java @@ -2,26 +2,35 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.GridWatcher; +import com.refinedmods.refinedstorage2.api.grid.service.GridInsertMode; +import com.refinedmods.refinedstorage2.api.grid.service.GridService; +import com.refinedmods.refinedstorage2.api.network.node.storage.FakeActor; import com.refinedmods.refinedstorage2.api.network.test.extension.AddNetworkNode; import com.refinedmods.refinedstorage2.api.network.test.extension.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.api.network.test.extension.NetworkTestExtension; import com.refinedmods.refinedstorage2.api.network.test.extension.SetupNetwork; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; +import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.EmptyActor; +import com.refinedmods.refinedstorage2.api.storage.InMemoryStorageImpl; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.limited.LimitedStorageImpl; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedStorageImpl; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Optional; +import javax.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; @ExtendWith(NetworkTestExtension.class) @SetupNetwork @@ -31,7 +40,7 @@ class GridNetworkNodeTest { @BeforeEach void setUp(@InjectNetworkStorageChannel final StorageChannel networkStorage) { - networkStorage.addSource(new TrackedStorageImpl<>(new LimitedStorageImpl<>(1000), () -> 0L)); + networkStorage.addSource(new TrackedStorageImpl<>(new LimitedStorageImpl<>(1000), () -> 2L)); networkStorage.insert("A", 100, Action.EXECUTE, EmptyActor.INSTANCE); networkStorage.insert("B", 200, Action.EXECUTE, EmptyActor.INSTANCE); } @@ -63,18 +72,18 @@ void testIteratingThroughResources() { new ResourceAmount<>("B", 200) ); assertThat(trackedResources).usingRecursiveFieldByFieldElementComparator().containsExactlyInAnyOrder( - Optional.of(new TrackedResource(EmptyActor.INSTANCE.getName(), 0L)), - Optional.of(new TrackedResource(EmptyActor.INSTANCE.getName(), 0L)) + Optional.of(new TrackedResource(EmptyActor.INSTANCE.getName(), 2L)), + Optional.of(new TrackedResource(EmptyActor.INSTANCE.getName(), 2L)) ); } @Test - void shouldNotifyWatchers() { + void shouldNotifyWatchersOfActivenessChanges() { // Arrange final FakeGridWatcher watcher = new FakeGridWatcher(); // Act - sut.addWatcher(watcher); + sut.addWatcher(watcher, EmptyActor.class); sut.setActive(true); sut.setActive(false); sut.removeWatcher(watcher); @@ -82,15 +91,113 @@ void shouldNotifyWatchers() { sut.setActive(false); // Assert - assertThat(watcher.changes).containsExactly(true, false); + assertThat(watcher.activenessChanges).containsExactly(true, false); + assertThat(watcher.changes).isEmpty(); } - private static class FakeGridWatcher implements GridWatcher { - private final List changes = new ArrayList<>(); + @Test + void shouldNotifyWatchersOfStorageChanges( + @InjectNetworkStorageChannel final StorageChannel networkStorage + ) { + // Arrange + final FakeGridWatcher watcher = new FakeGridWatcher(); + sut.addWatcher(watcher, FakeActor.class); + + // Act + networkStorage.insert("A", 10, Action.EXECUTE, EmptyActor.INSTANCE); + networkStorage.insert("A", 1, Action.EXECUTE, FakeActor.INSTANCE); + sut.removeWatcher(watcher); + networkStorage.insert("A", 1, Action.EXECUTE, FakeActor.INSTANCE); + + // Assert + assertThat(watcher.activenessChanges).isEmpty(); + assertThat(watcher.changes).usingRecursiveFieldByFieldElementComparator().containsExactly( + new Change<>("A", 10, null), + new Change<>("A", 1, new TrackedResource("Fake", 2)) + ); + } + + @Test + void shouldNotBeAbleToRemoveUnknownWatcher() { + // Arrange + final FakeGridWatcher watcher = new FakeGridWatcher(); + + // Act & assert + assertThrows(IllegalArgumentException.class, () -> sut.removeWatcher(watcher)); + } + + @Test + void shouldNotBeAbleToAddDuplicateWatcher() { + // Arrange + final FakeGridWatcher watcher = new FakeGridWatcher(); + final Class actorType1 = EmptyActor.class; + final Class actorType2 = FakeActor.class; + + sut.addWatcher(watcher, actorType1); + + // Act & assert + assertThrows(IllegalArgumentException.class, () -> sut.addWatcher(watcher, actorType1)); + assertThrows(IllegalArgumentException.class, () -> sut.addWatcher(watcher, actorType2)); + } + + @Test + void shouldCreateService( + @InjectNetworkStorageChannel final StorageChannel networkStorage + ) { + // Arrange + final GridService service = sut.createService( + FakeActor.INSTANCE, + r -> 5L, + 1 + ); + + final InMemoryStorageImpl source = new InMemoryStorageImpl<>(); + source.insert("Z", 10, Action.EXECUTE, EmptyActor.INSTANCE); + + // Act + service.insert("Z", GridInsertMode.SINGLE_RESOURCE, source); + final Collection> afterSingle = networkStorage + .getAll() + .stream() + .map(ra -> new ResourceAmount<>(ra.getResource(), ra.getAmount())) + .toList(); + + service.insert("Z", GridInsertMode.ENTIRE_RESOURCE, source); + final Collection> afterEntire = networkStorage + .getAll() + .stream() + .map(ra -> new ResourceAmount<>(ra.getResource(), ra.getAmount())) + .toList(); + + // Assert + assertThat(afterSingle).usingRecursiveFieldByFieldElementComparator().contains( + new ResourceAmount<>("Z", 1) + ); + assertThat(afterEntire).usingRecursiveFieldByFieldElementComparator().contains( + new ResourceAmount<>("Z", 6) + ); + } + + private static class FakeGridWatcher implements GridWatcher { + private final List activenessChanges = new ArrayList<>(); + private final List> changes = new ArrayList<>(); @Override public void onActiveChanged(final boolean newActive) { - changes.add(newActive); + activenessChanges.add(newActive); } + + @Override + public void onChanged(final ResourceListOperationResult change, + final @Nullable TrackedResource trackedResource) { + changes.add(new Change<>( + change.resourceAmount().getResource(), + change.change(), + trackedResource + )); + } + } + + private record Change(T resource, long change, @Nullable TrackedResource trackedResource) { } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/AbstractGridBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/AbstractGridBlockEntity.java index 103f3065e..a258c8935 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/AbstractGridBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/AbstractGridBlockEntity.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.grid.GridWatcher; import com.refinedmods.refinedstorage2.api.network.node.grid.GridNetworkNode; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.common.Platform; @@ -50,11 +51,11 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte protected abstract void writeResourceAmount(FriendlyByteBuf buf, ResourceAmount stack); - public void addWatcher(final GridWatcher watcher) { - getNode().addWatcher(watcher); + public void addWatcher(final GridWatcher watcher, final Class actorType) { + getNode().addWatcher(watcher, actorType); } - public void removeWatcher(final GridWatcher watcher) { + public void removeWatcher(final GridWatcher watcher) { getNode().removeWatcher(watcher); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java index bda1acca2..5b8054b57 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java @@ -6,11 +6,10 @@ import com.refinedmods.refinedstorage2.api.grid.view.GridSortingType; import com.refinedmods.refinedstorage2.api.grid.view.GridView; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; -import com.refinedmods.refinedstorage2.api.resource.list.listenable.ResourceListListener; -import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; +import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.common.Config; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.block.entity.grid.AbstractGridBlockEntity; @@ -35,7 +34,7 @@ import org.apache.logging.log4j.Logger; public abstract class AbstractGridContainerMenu extends AbstractBaseContainerMenu - implements ResourceListListener, GridWatcher { + implements GridWatcher { private static final Logger LOGGER = LogManager.getLogger(); private static String lastSearchQuery = ""; @@ -45,8 +44,6 @@ public abstract class AbstractGridContainerMenu extends AbstractBaseContainer @Nullable protected AbstractGridBlockEntity grid; @Nullable - protected StorageChannel storageChannel; // TODO - Support changing of the channel. - @Nullable private Runnable sizeChangedListener; private GridSynchronizer synchronizer; @@ -103,9 +100,8 @@ protected AbstractGridContainerMenu(final MenuType type, )); this.playerInventory = playerInventory; - this.storageChannel = grid.getNode().getStorageChannel(); - this.storageChannel.addListener(this); this.grid = grid; + this.grid.addWatcher(this, PlayerActor.class); addSlots(0); @@ -170,9 +166,8 @@ private static void updateLastSearchQuery(final String text) { @Override public void removed(final Player playerEntity) { super.removed(playerEntity); - - if (storageChannel != null) { - storageChannel.removeListener(this); + if (grid != null) { + grid.removeWatcher(this); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/FluidGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/FluidGridContainerMenu.java index 2e1d23ab3..d39562f3e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/FluidGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/FluidGridContainerMenu.java @@ -3,12 +3,12 @@ import com.refinedmods.refinedstorage2.api.grid.service.GridExtractMode; import com.refinedmods.refinedstorage2.api.grid.service.GridInsertMode; import com.refinedmods.refinedstorage2.api.grid.service.GridService; -import com.refinedmods.refinedstorage2.api.grid.service.GridServiceImpl; import com.refinedmods.refinedstorage2.api.grid.view.GridViewImpl; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; +import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.grid.FluidGridEventHandler; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; @@ -19,7 +19,7 @@ import com.refinedmods.refinedstorage2.platform.common.internal.grid.ClientFluidGridEventHandler; import com.refinedmods.refinedstorage2.platform.common.util.PacketUtil; -import java.util.Objects; +import javax.annotation.Nullable; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; @@ -45,9 +45,7 @@ public FluidGridContainerMenu(final int syncId, final FluidGridBlockEntity grid, final ExtractableStorage bucketStorage) { super(Menus.INSTANCE.getFluidGrid(), syncId, playerInventory, grid, createView()); - grid.addWatcher(this); - final GridService gridService = new GridServiceImpl<>( - Objects.requireNonNull(storageChannel), + final GridService gridService = grid.getNode().createService( new PlayerActor(playerInventory.player), resource -> Long.MAX_VALUE, Platform.INSTANCE.getBucketAmount() @@ -60,14 +58,6 @@ public FluidGridContainerMenu(final int syncId, ); } - @Override - public void removed(final Player playerEntity) { - super.removed(playerEntity); - if (grid != null) { - grid.removeWatcher(this); - } - } - private static GridViewImpl createView() { return new GridViewImpl<>(Platform.INSTANCE.getFluidGridResourceFactory(), new ResourceListImpl<>()); } @@ -78,17 +68,17 @@ protected ResourceAmount readResourceAmount(final FriendlyByteBuf } @Override - public void onChanged(final ResourceListOperationResult change) { + public void onChanged(final ResourceListOperationResult change, + @Nullable final TrackedResource trackedResource) { final FluidResource resource = change.resourceAmount().getResource(); - LOGGER.info("Received a change of {} for {}", change.change(), resource); + LOGGER.debug("Received a change of {} for {}", change.change(), resource); Platform.INSTANCE.getServerToClientCommunications().sendGridFluidUpdate( (ServerPlayer) playerInventory.player, resource, change.change(), - Objects.requireNonNull(storageChannel) - .findTrackedResourceByActorType(resource, PlayerActor.class).orElse(null) + trackedResource ); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/ItemGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/ItemGridContainerMenu.java index 8a0c8b243..3d0d0fe2e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/ItemGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/ItemGridContainerMenu.java @@ -3,11 +3,11 @@ import com.refinedmods.refinedstorage2.api.grid.service.GridExtractMode; import com.refinedmods.refinedstorage2.api.grid.service.GridInsertMode; import com.refinedmods.refinedstorage2.api.grid.service.GridService; -import com.refinedmods.refinedstorage2.api.grid.service.GridServiceImpl; import com.refinedmods.refinedstorage2.api.grid.view.GridViewImpl; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListImpl; import com.refinedmods.refinedstorage2.api.resource.list.ResourceListOperationResult; +import com.refinedmods.refinedstorage2.api.storage.tracked.TrackedResource; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; import com.refinedmods.refinedstorage2.platform.api.grid.ItemGridEventHandler; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; @@ -18,7 +18,7 @@ import com.refinedmods.refinedstorage2.platform.common.internal.grid.ClientItemGridEventHandler; import com.refinedmods.refinedstorage2.platform.common.util.PacketUtil; -import java.util.Objects; +import javax.annotation.Nullable; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; @@ -43,9 +43,7 @@ public ItemGridContainerMenu(final int syncId, final Inventory playerInventory, final AbstractGridBlockEntity grid) { super(Menus.INSTANCE.getGrid(), syncId, playerInventory, grid, createView()); - grid.addWatcher(this); - final GridService gridService = new GridServiceImpl<>( - Objects.requireNonNull(storageChannel), + final GridService gridService = grid.getNode().createService( new PlayerActor(playerInventory.player), itemResource -> (long) itemResource.item().getMaxStackSize(), 1 @@ -53,14 +51,6 @@ public ItemGridContainerMenu(final int syncId, this.itemGridEventHandler = Platform.INSTANCE.createItemGridEventHandler(this, gridService, playerInventory); } - @Override - public void removed(final Player playerEntity) { - super.removed(playerEntity); - if (grid != null) { - grid.removeWatcher(this); - } - } - private static GridViewImpl createView() { return new GridViewImpl<>(Platform.INSTANCE.getItemGridResourceFactory(), new ResourceListImpl<>()); } @@ -71,17 +61,17 @@ protected ResourceAmount readResourceAmount(final FriendlyByteBuf } @Override - public void onChanged(final ResourceListOperationResult change) { + public void onChanged(final ResourceListOperationResult change, + @Nullable final TrackedResource trackedResource) { final ItemResource resource = change.resourceAmount().getResource(); - LOGGER.info("Received a change of {} for {}", change.change(), resource); + LOGGER.debug("Received a change of {} for {}", change.change(), resource); Platform.INSTANCE.getServerToClientCommunications().sendGridItemUpdate( (ServerPlayer) playerInventory.player, resource, change.change(), - Objects.requireNonNull(storageChannel) - .findTrackedResourceByActorType(resource, PlayerActor.class).orElse(null) + trackedResource ); } From 1bb565f07b806b995f2ae15cb24a62392aca9f60 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Tue, 2 Aug 2022 08:24:20 +0200 Subject: [PATCH 14/23] Disallow Jetbrains annotations importing. --- build.gradle | 1 + checkstyle-imports.xml | 6 ++++++ checkstyle.xml | 3 +++ 3 files changed, 10 insertions(+) create mode 100644 checkstyle-imports.xml diff --git a/build.gradle b/build.gradle index 42c4d91f7..d862402fb 100644 --- a/build.gradle +++ b/build.gradle @@ -40,6 +40,7 @@ subprojects { checkstyle { configFile rootProject.file("checkstyle.xml") + configDirectory.set(rootProject.projectDir) toolVersion = project.checkstyleVersion } diff --git a/checkstyle-imports.xml b/checkstyle-imports.xml new file mode 100644 index 000000000..6956590b9 --- /dev/null +++ b/checkstyle-imports.xml @@ -0,0 +1,6 @@ + + + + diff --git a/checkstyle.xml b/checkstyle.xml index 79537e41f..36b09fc15 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -33,6 +33,9 @@ + + + From 7d1a467e73c5ed9bb7e22164b1646504ac277a54 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Tue, 2 Aug 2022 08:26:05 +0200 Subject: [PATCH 15/23] Stop hardcoding disk slot count. --- .../node/diskdrive/DiskDriveNetworkNode.java | 21 +++++++++++-------- .../StorageNetworkComponentTest.java | 2 +- .../diskdrive/DiskDriveNetworkNodeTest.java | 9 ++++---- .../network/test/extension/AddDiskDrive.java | 2 ++ .../test/extension/NetworkTestExtension.java | 3 ++- .../AbstractDiskDriveBlockEntity.java | 8 +++++-- .../entity/diskdrive/DiskDriveInventory.java | 5 ++--- .../diskdrive/DiskDriveContainerMenu.java | 7 +++---- 8 files changed, 33 insertions(+), 24 deletions(-) diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java index 65aa01639..712de0286 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java @@ -26,8 +26,6 @@ import org.apache.logging.log4j.Logger; public class DiskDriveNetworkNode extends AbstractNetworkNode implements StorageProvider { - public static final int DISK_COUNT = 8; - private static final Logger LOGGER = LogManager.getLogger(DiskDriveNetworkNode.class); @Nullable @@ -40,7 +38,7 @@ public class DiskDriveNetworkNode extends AbstractNetworkNode implements Storage private final long energyUsage; private final long energyUsagePerDisk; - private final DiskDriveDiskStorage[] disks = new DiskDriveDiskStorage[DISK_COUNT]; + private final DiskDriveDiskStorage[] disks; private final Map, DiskDriveCompositeStorage> compositeStorages; private int diskCount; @@ -51,10 +49,12 @@ public class DiskDriveNetworkNode extends AbstractNetworkNode implements Storage public DiskDriveNetworkNode(final long energyUsage, final long energyUsagePerDisk, - final OrderedRegistry> storageChannelTypeRegistry) { + final OrderedRegistry> storageChannelTypeRegistry, + final int diskCount) { this.energyUsage = energyUsage; this.energyUsagePerDisk = energyUsagePerDisk; this.compositeStorages = createCompositeStorages(storageChannelTypeRegistry); + this.disks = new DiskDriveDiskStorage[diskCount]; } private Map, DiskDriveCompositeStorage> createCompositeStorages( @@ -77,7 +77,7 @@ public void initialize(final StorageRepository newStorageRepository) { return; } this.storageRepository = newStorageRepository; - for (int i = 0; i < DISK_COUNT; ++i) { + for (int i = 0; i < disks.length; ++i) { initializeDiskInSlot(i); } updateDiskCount(); @@ -161,8 +161,7 @@ private void enableAllDisks() { @SuppressWarnings({"unchecked", "rawtypes"}) private void enableAllDisksForChannel(final StorageChannelType type, final DiskDriveCompositeStorage composite) { - for (int i = 0; i < DISK_COUNT; ++i) { - final DiskDriveDiskStorage disk = disks[i]; + for (final DiskDriveDiskStorage disk : disks) { if (disk != null && disk.getStorageChannelType() == type) { composite.addSource((DiskDriveDiskStorage) disk); } @@ -199,8 +198,8 @@ public long getEnergyUsage() { } public DiskDriveState createState() { - final DiskDriveState states = new DiskDriveState(DISK_COUNT); - for (int i = 0; i < DISK_COUNT; ++i) { + final DiskDriveState states = new DiskDriveState(disks.length); + for (int i = 0; i < disks.length; ++i) { states.setState(i, getState(disks[i])); } return states; @@ -246,6 +245,10 @@ public Optional> getStorageForChannel(final StorageChannelType return Optional.empty(); } + public int getDiskCount() { + return disks.length; + } + private record DiskChange(boolean removed, DiskDriveCompositeStorage compositeStorage, DiskDriveDiskStorage storage) { diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java index f6bc0680d..7efbb4807 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/component/StorageNetworkComponentTest.java @@ -38,7 +38,7 @@ void setUp() { final FakeStorageProviderRepository storageProviderRepository = new FakeStorageProviderRepository(); storageProviderRepository.setInSlot(0, new LimitedStorageImpl<>(100)); - diskDrive = new DiskDriveNetworkNode(0, 0, NetworkTestFixtures.STORAGE_CHANNEL_TYPE_REGISTRY); + diskDrive = new DiskDriveNetworkNode(0, 0, NetworkTestFixtures.STORAGE_CHANNEL_TYPE_REGISTRY, 9); diskDrive.setNetwork(new NetworkImpl(NetworkTestFixtures.NETWORK_COMPONENT_MAP_FACTORY)); diskDrive.setListener(mock(DiskDriveListener.class)); diskDrive.setDiskProvider(storageProviderRepository); diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java index bf921a976..82de49624 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java @@ -88,8 +88,9 @@ void testInitialState(@InjectNetworkStorageChannel final StorageChannel assertThat(networkStorage.getAll()).isEmpty(); assertThat(networkStorage.getStored()).isZero(); assertThat(states.getStates()) - .hasSize(DiskDriveNetworkNode.DISK_COUNT) + .hasSize(9) .allMatch(state -> state == StorageDiskState.NONE); + assertThat(sut.getDiskCount()).isEqualTo(9); } @ParameterizedTest @@ -205,13 +206,13 @@ void shouldRemoveDiskInSlot(@InjectNetworkStorageChannel final StorageChannel state == StorageDiskState.NONE); } diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java index b57a99b6b..5a718f45c 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/AddDiskDrive.java @@ -14,5 +14,7 @@ boolean active() default true; + int diskCount() default 9; + String networkId() default "default"; } diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java index 19b1c2416..748238935 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java @@ -109,7 +109,8 @@ private void tryAddDiskDrive(final Object testInstance, final Field field) { final DiskDriveNetworkNode resolvedNode = new DiskDriveNetworkNode( annotation.baseEnergyUsage(), annotation.energyUsagePerDisk(), - NetworkTestFixtures.STORAGE_CHANNEL_TYPE_REGISTRY + NetworkTestFixtures.STORAGE_CHANNEL_TYPE_REGISTRY, + annotation.diskCount() ); resolvedNode.setActive(annotation.active()); final Network network = networkMap.get(annotation.networkId()); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java index 41b431594..4309ac13b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java @@ -56,6 +56,8 @@ public abstract class AbstractDiskDriveBlockEntity implements BlockEntityWithDrops, DiskDriveListener, ExtendedMenuProvider, StorageSettingsProvider { private static final Logger LOGGER = LogManager.getLogger(); + private static final int AMOUNT_OF_DISKS = 9; + private static final String TAG_PRIORITY = "pri"; private static final String TAG_FILTER_MODE = "fim"; private static final String TAG_EXACT_MODE = "em"; @@ -69,7 +71,7 @@ public abstract class AbstractDiskDriveBlockEntity @Nullable protected DiskDriveState driveState; - private final DiskDriveInventory diskInventory = new DiskDriveInventory(this); + private final DiskDriveInventory diskInventory; private final ResourceFilterContainer resourceFilterContainer = new ResourceFilterContainer( PlatformApi.INSTANCE.getResourceTypeRegistry(), 9, @@ -85,8 +87,10 @@ protected AbstractDiskDriveBlockEntity(final BlockPos pos, final BlockState stat super(BlockEntities.INSTANCE.getDiskDrive(), pos, state, new DiskDriveNetworkNode( Platform.INSTANCE.getConfig().getDiskDrive().getEnergyUsage(), Platform.INSTANCE.getConfig().getDiskDrive().getEnergyUsagePerDisk(), - PlatformApi.INSTANCE.getStorageChannelTypeRegistry() + PlatformApi.INSTANCE.getStorageChannelTypeRegistry(), + AMOUNT_OF_DISKS )); + this.diskInventory = new DiskDriveInventory(this, getNode().getDiskCount()); getNode().setDiskProvider(diskInventory); getNode().setListener(this); getNode().setNormalizer(value -> FuzzyModeNormalizer.tryNormalize(exactMode, value)); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/DiskDriveInventory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/DiskDriveInventory.java index b1cfe5b39..9513848ab 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/DiskDriveInventory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/DiskDriveInventory.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage2.platform.common.block.entity.diskdrive; -import com.refinedmods.refinedstorage2.api.network.node.diskdrive.DiskDriveNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.diskdrive.StorageDiskProvider; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.storage.item.StorageDiskItem; @@ -14,8 +13,8 @@ public class DiskDriveInventory extends SimpleContainer implements StorageDiskProvider { private final AbstractDiskDriveBlockEntity diskDrive; - public DiskDriveInventory(final AbstractDiskDriveBlockEntity diskDrive) { - super(DiskDriveNetworkNode.DISK_COUNT); + public DiskDriveInventory(final AbstractDiskDriveBlockEntity diskDrive, final int diskCount) { + super(diskCount); this.diskDrive = diskDrive; } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java index ac74fff5d..8e2405500 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/diskdrive/DiskDriveContainerMenu.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage2.platform.common.containermenu.storage.diskdrive; -import com.refinedmods.refinedstorage2.api.network.node.diskdrive.DiskDriveNetworkNode; import com.refinedmods.refinedstorage2.api.storage.StorageInfo; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.storage.StorageTooltipHelper; @@ -44,7 +43,7 @@ public DiskDriveContainerMenu(final int syncId, final Inventory playerInventory, addSlots( playerInventory.player, - new SimpleContainer(DiskDriveNetworkNode.DISK_COUNT), + new SimpleContainer(9), new ResourceFilterContainer(PlatformApi.INSTANCE.getResourceTypeRegistry(), 9) ); @@ -72,10 +71,10 @@ public DiskDriveContainerMenu(final int syncId, private void addSlots(final Player player, final SimpleContainer diskInventory, final ResourceFilterContainer resourceFilterContainer) { - for (int i = 0; i < DiskDriveNetworkNode.DISK_COUNT; ++i) { + for (int i = 0; i < diskInventory.getContainerSize(); ++i) { diskSlots.add(addSlot(createDiskSlot(diskInventory, i))); } - for (int i = 0; i < 9; ++i) { + for (int i = 0; i < resourceFilterContainer.size(); ++i) { addSlot(createFilterSlot(resourceFilterContainer, i)); } addPlayerInventory(player.getInventory(), 8, 141); From 29e71931d243ca451c67e361c37d21f2adb6899e Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Tue, 2 Aug 2022 08:26:50 +0200 Subject: [PATCH 16/23] Stop using Jetbrains annotations. --- .../platform/common/block/CableBlockSupport.java | 3 ++- .../block/entity/FabricDiskDriveBlockEntity.java | 6 ++++-- .../internal/grid/FluidGridEventHandlerImpl.java | 3 ++- .../menu/FabricExtendedMenuProviderAdapter.java | 3 ++- .../fabric/render/model/DiskDriveUnbakedModel.java | 2 +- .../fabric/render/model/EmissiveModelRegistry.java | 2 +- .../platform/forge/ModInitializer.java | 8 ++++---- .../forge/block/entity/ForgeDiskDriveBlockEntity.java | 5 +++-- .../platform/forge/internal/grid/CursorStorage.java | 11 ++++++----- .../forge/render/model/baked/DiskDriveBakedModel.java | 10 +++++----- .../render/model/baked/DiskDriveItemBakedModel.java | 10 +++++----- 11 files changed, 35 insertions(+), 28 deletions(-) diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java index 4d034d25f..4e32bd055 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/CableBlockSupport.java @@ -2,6 +2,8 @@ import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; +import javax.annotation.Nullable; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.LevelAccessor; @@ -12,7 +14,6 @@ import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import org.jetbrains.annotations.Nullable; import static net.minecraft.world.level.block.Block.box; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/block/entity/FabricDiskDriveBlockEntity.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/block/entity/FabricDiskDriveBlockEntity.java index 3209dff32..6b0f2825e 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/block/entity/FabricDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/block/entity/FabricDiskDriveBlockEntity.java @@ -2,10 +2,11 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.diskdrive.AbstractDiskDriveBlockEntity; +import javax.annotation.Nullable; + import net.fabricmc.fabric.api.rendering.data.v1.RenderAttachmentBlockEntity; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; public class FabricDiskDriveBlockEntity extends AbstractDiskDriveBlockEntity implements RenderAttachmentBlockEntity { public FabricDiskDriveBlockEntity(final BlockPos pos, final BlockState state) { @@ -13,7 +14,8 @@ public FabricDiskDriveBlockEntity(final BlockPos pos, final BlockState state) { } @Override - public @Nullable Object getRenderAttachmentData() { + @Nullable + public Object getRenderAttachmentData() { return driveState; } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridEventHandlerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridEventHandlerImpl.java index 8e7180add..1b309d32f 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridEventHandlerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridEventHandlerImpl.java @@ -10,6 +10,8 @@ import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; +import javax.annotation.Nullable; + import net.fabricmc.fabric.api.transfer.v1.context.ContainerItemContext; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidStorage; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidVariant; @@ -23,7 +25,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.Items; -import org.jetbrains.annotations.Nullable; import static com.refinedmods.refinedstorage2.platform.fabric.util.VariantUtil.ofFluidVariant; import static com.refinedmods.refinedstorage2.platform.fabric.util.VariantUtil.toFluidVariant; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/menu/FabricExtendedMenuProviderAdapter.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/menu/FabricExtendedMenuProviderAdapter.java index 62cb54f8b..57db09ff0 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/menu/FabricExtendedMenuProviderAdapter.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/menu/FabricExtendedMenuProviderAdapter.java @@ -2,6 +2,8 @@ import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; +import javax.annotation.Nullable; + import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerFactory; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; @@ -9,7 +11,6 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; -import org.jetbrains.annotations.Nullable; public class FabricExtendedMenuProviderAdapter implements ExtendedScreenHandlerFactory { private final ExtendedMenuProvider extendedMenuProvider; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/DiskDriveUnbakedModel.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/DiskDriveUnbakedModel.java index d409cb300..b649bd5be 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/DiskDriveUnbakedModel.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/DiskDriveUnbakedModel.java @@ -6,6 +6,7 @@ import java.util.Objects; import java.util.Set; import java.util.function.Function; +import javax.annotation.Nullable; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.BakedModel; @@ -13,7 +14,6 @@ import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.client.resources.model.ModelState; import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/EmissiveModelRegistry.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/EmissiveModelRegistry.java index 1cbe13803..141823b40 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/EmissiveModelRegistry.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/EmissiveModelRegistry.java @@ -5,13 +5,13 @@ import java.util.HashMap; import java.util.Map; import java.util.function.Function; +import javax.annotation.Nullable; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.resources.ResourceLocation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.Nullable; public final class EmissiveModelRegistry { public static final EmissiveModelRegistry INSTANCE = new EmissiveModelRegistry(); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java index 4202d1580..aeaa56f2f 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java @@ -57,6 +57,8 @@ import com.refinedmods.refinedstorage2.platform.forge.packet.NetworkManager; import java.util.function.Supplier; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.core.Direction; import net.minecraft.core.Registry; @@ -87,8 +89,6 @@ import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.CABLE; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.CONSTRUCTION_CORE; @@ -593,9 +593,9 @@ private void registerControllerEnergy(final AttachCapabilitiesEvent final LazyOptional capability = LazyOptional .of(() -> (IEnergyStorage) controllerBlockEntity.getEnergyStorage()); e.addCapability(createIdentifier("energy"), new ICapabilityProvider() { - @NotNull @Override - public LazyOptional getCapability(@NotNull final Capability cap, + @Nonnull + public LazyOptional getCapability(final Capability cap, @Nullable final Direction side) { if (cap == CapabilityEnergy.ENERGY && controllerBlockEntity.getEnergyStorage() instanceof IEnergyStorage) { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/block/entity/ForgeDiskDriveBlockEntity.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/block/entity/ForgeDiskDriveBlockEntity.java index 0ca8f74d5..d25ace369 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/block/entity/ForgeDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/block/entity/ForgeDiskDriveBlockEntity.java @@ -3,11 +3,12 @@ import com.refinedmods.refinedstorage2.api.network.node.diskdrive.DiskDriveState; import com.refinedmods.refinedstorage2.platform.common.block.entity.diskdrive.AbstractDiskDriveBlockEntity; +import javax.annotation.Nonnull; + import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.model.data.ModelProperty; -import org.jetbrains.annotations.NotNull; public class ForgeDiskDriveBlockEntity extends AbstractDiskDriveBlockEntity { public static final ModelProperty STATE_PROPERTY = new ModelProperty<>(); @@ -22,7 +23,7 @@ protected void onDriveStateUpdated() { super.onDriveStateUpdated(); } - @NotNull + @Nonnull @Override public ModelData getModelData() { return ModelData.builder().with(STATE_PROPERTY, driveState).build(); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/grid/CursorStorage.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/grid/CursorStorage.java index 514d9c664..7ad3735a3 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/grid/CursorStorage.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/grid/CursorStorage.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.platform.forge.internal.grid; +import javax.annotation.Nonnull; + import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemHandlerHelper; -import org.jetbrains.annotations.NotNull; public class CursorStorage implements IItemHandler { private final AbstractContainerMenu containerMenu; @@ -19,13 +20,13 @@ public int getSlots() { } @Override - @NotNull + @Nonnull public ItemStack getStackInSlot(final int slot) { return containerMenu.getCarried(); } @Override - @NotNull + @Nonnull public ItemStack insertItem(final int slot, final ItemStack stack, final boolean simulate) { if (slot != 0) { return stack; @@ -60,7 +61,7 @@ private ItemStack insertIntoCursorWithExistingContent(final ItemStack itemStack, } @Override - @NotNull + @Nonnull public ItemStack extractItem(final int slot, final int amount, final boolean simulate) { if (slot != 0) { return ItemStack.EMPTY; @@ -82,7 +83,7 @@ public int getSlotLimit(final int slot) { } @Override - public boolean isItemValid(final int slot, @NotNull final ItemStack stack) { + public boolean isItemValid(final int slot, @Nonnull final ItemStack stack) { return slot == 0; } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java index c747484ad..b9441dbee 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java @@ -15,6 +15,8 @@ import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; @@ -34,8 +36,6 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.BakedModelWrapper; import net.minecraftforge.client.model.data.ModelData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class DiskDriveBakedModel extends BakedModelWrapper { private static final Vector3f[] TRANSLATORS = new Vector3f[8]; @@ -81,12 +81,12 @@ public ItemOverrides getOverrides() { return overrides; } - @NotNull + @Nonnull @Override public List getQuads(@Nullable final BlockState state, @Nullable final Direction side, - @NotNull final RandomSource rand, - @NotNull final ModelData extraData, + @Nonnull final RandomSource rand, + @Nonnull final ModelData extraData, @Nullable final RenderType renderType) { if (state == null || !(state.getBlock() instanceof DiskDriveBlock diskDriveBlock)) { return super.getQuads(state, side, rand); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java index 8c6637389..129512696 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java @@ -5,6 +5,8 @@ import java.util.List; import java.util.Map; import java.util.function.Function; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Vector3f; @@ -17,8 +19,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.BakedModelWrapper; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class DiskDriveItemBakedModel extends BakedModelWrapper { private final BakedModel baseModel; @@ -46,9 +46,9 @@ public ItemOverrides getOverrides() { } @Override - public @NotNull List getQuads(@Nullable final BlockState state, + public @Nonnull List getQuads(@Nullable final BlockState state, @Nullable final Direction side, - @NotNull final RandomSource rand) { + @Nonnull final RandomSource rand) { if (side == null) { if (noSideCache == null) { noSideCache = createQuads(state, null, rand); @@ -60,7 +60,7 @@ public ItemOverrides getOverrides() { private List createQuads(@Nullable final BlockState state, @Nullable final Direction side, - @NotNull final RandomSource rand) { + @Nonnull final RandomSource rand) { final List quads = new ArrayList<>(super.getQuads( state, side, From bf6c3047757d134adb5230a629ada6c7cc9ccd42 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Tue, 2 Aug 2022 08:27:13 +0200 Subject: [PATCH 17/23] Move RateLimiter creation to AbstractInternalNetworkNodeContainerBlockEntity. --- ...actInternalNetworkNodeContainerBlockEntity.java | 5 +++++ .../common/block/entity/ImporterBlockEntity.java | 5 ++--- .../common/block/entity/UpgradeConstants.java | 14 -------------- 3 files changed, 7 insertions(+), 17 deletions(-) delete mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java index 674be2c8d..0439c823e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java @@ -8,6 +8,7 @@ import javax.annotation.Nullable; +import com.google.common.util.concurrent.RateLimiter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; @@ -139,4 +140,8 @@ protected final Direction getDirection() { } return directionalBlock.extractDirection(blockState); } + + protected RateLimiter createRateLimiter(final int amountOfSpeedUpgrades) { + return RateLimiter.create((double) amountOfSpeedUpgrades + 1); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index 891785e03..77a5c1a23 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -50,8 +50,7 @@ public class ImporterBlockEntity extends AbstractInternalNetworkNodeContainerBlo private final ResourceFilterContainer resourceFilterContainer; private final UpgradeContainer upgradeContainer; private boolean exactMode; - - private RateLimiter rateLimiter = UpgradeConstants.getRateLimiter(0); + private RateLimiter rateLimiter = createRateLimiter(0); public ImporterBlockEntity(final BlockPos pos, final BlockState state) { super( @@ -201,7 +200,7 @@ private void upgradeContainerChanged() { private void initializeUpgrades() { final int amountOfSpeedUpgrades = upgradeContainer.countItem(Items.INSTANCE.getSpeedUpgrade()); final boolean hasStackUpgrade = hasStackUpgrade(); - rateLimiter = UpgradeConstants.getRateLimiter(amountOfSpeedUpgrades); + rateLimiter = createRateLimiter(amountOfSpeedUpgrades); getNode().setEnergyUsage(calculateEnergyUsage(amountOfSpeedUpgrades, hasStackUpgrade)); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java deleted file mode 100644 index a22d48f80..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeConstants.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.block.entity; - -import com.google.common.util.concurrent.RateLimiter; - -public final class UpgradeConstants { - public static final int UPGRADE_SLOTS = 4; - - private UpgradeConstants() { - } - - public static RateLimiter getRateLimiter(final long amountOfSpeedUpgrades) { - return RateLimiter.create(amountOfSpeedUpgrades + 1); - } -} From 796ce423af9df20f2ab3b1c27061938d5ea56676 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Tue, 2 Aug 2022 08:27:59 +0200 Subject: [PATCH 18/23] Stop hardcoding amount of resource filter slots/upgrade slots. --- .../api/core/CoreValidationsTest.java | 65 +++++++++++++------ .../common/block/entity/UpgradeContainer.java | 2 +- .../containermenu/ImporterContainerMenu.java | 4 +- .../AbstractStorageBlockContainerMenu.java | 2 +- 4 files changed, 48 insertions(+), 25 deletions(-) diff --git a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java b/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java index c41903baf..8a198d080 100644 --- a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java +++ b/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java @@ -12,16 +12,22 @@ class CoreValidationsTest { @Test void shouldValidateEquals() { // Act & assert - final Exception e1 = - assertThrows(IllegalStateException.class, () -> CoreValidations.validateEquals(1, 2, "bla")); + final Exception e1 = assertThrows( + IllegalStateException.class, + () -> CoreValidations.validateEquals(1, 2, "bla") + ); assertThat(e1.getMessage()).isEqualTo("bla"); - final Exception e2 = - assertThrows(IllegalStateException.class, () -> CoreValidations.validateEquals(null, 2, "bla")); + final Exception e2 = assertThrows( + IllegalStateException.class, + () -> CoreValidations.validateEquals(null, 2, "bla") + ); assertThat(e2.getMessage()).isEqualTo("bla"); - final Exception e3 = - assertThrows(IllegalStateException.class, () -> CoreValidations.validateEquals(1, null, "bla")); + final Exception e3 = assertThrows( + IllegalStateException.class, + () -> CoreValidations.validateEquals(1, null, "bla") + ); assertThat(e3.getMessage()).isEqualTo("bla"); assertDoesNotThrow(() -> CoreValidations.validateEquals(1, 1, "bla")); @@ -31,8 +37,10 @@ void shouldValidateEquals() { @Test void shouldValidateNotNull() { // Act & assert - final Exception e = - assertThrows(NullPointerException.class, () -> CoreValidations.validateNotNull(null, "bla")); + final Exception e = assertThrows( + NullPointerException.class, + () -> CoreValidations.validateNotNull(null, "bla") + ); assertThat(e.getMessage()).isEqualTo("bla"); assertDoesNotThrow(() -> CoreValidations.validateNotNull("not null", "bla")); @@ -43,8 +51,10 @@ void shouldValidateNotNull() { @Test void shouldValidateNotNegative() { // Act & assert - final Exception e = - assertThrows(IllegalArgumentException.class, () -> CoreValidations.validateNotNegative(-1, "bla")); + final Exception e = assertThrows( + IllegalArgumentException.class, + () -> CoreValidations.validateNotNegative(-1, "bla") + ); assertThat(e.getMessage()).isEqualTo("bla"); assertDoesNotThrow(() -> CoreValidations.validateNotNegative(0, "bla")); @@ -56,12 +66,16 @@ void shouldValidateNotNegative() { @Test void shouldValidateNegative() { // Act & assert - final Exception e1 = - assertThrows(IllegalArgumentException.class, () -> CoreValidations.validateNegative(0, "bla")); + final Exception e1 = assertThrows( + IllegalArgumentException.class, + () -> CoreValidations.validateNegative(0, "bla") + ); assertThat(e1.getMessage()).isEqualTo("bla"); - final Exception e2 = - assertThrows(IllegalArgumentException.class, () -> CoreValidations.validateNegative(1, "bla")); + final Exception e2 = assertThrows( + IllegalArgumentException.class, + () -> CoreValidations.validateNegative(1, "bla") + ); assertThat(e2.getMessage()).isEqualTo("bla"); assertDoesNotThrow(() -> CoreValidations.validateNegative(-1, "bla")); @@ -71,8 +85,10 @@ void shouldValidateNegative() { @Test void shouldValidateLargerThanZero() { // Act & assert - final Exception e = - assertThrows(IllegalArgumentException.class, () -> CoreValidations.validateLargerThanZero(0, "bla")); + final Exception e = assertThrows( + IllegalArgumentException.class, + () -> CoreValidations.validateLargerThanZero(0, "bla") + ); assertThat(e.getMessage()).isEqualTo("bla"); final Exception e2 = @@ -86,8 +102,11 @@ void shouldValidateLargerThanZero() { @Test void shouldValidateEmpty() { // Act & assert - final Exception e = - assertThrows(IllegalArgumentException.class, () -> CoreValidations.validateEmpty(List.of(1), "bla")); + final List badList = List.of(1); + final Exception e = assertThrows( + IllegalArgumentException.class, + () -> CoreValidations.validateEmpty(badList, "bla") + ); assertThat(e.getMessage()).isEqualTo("bla"); assertDoesNotThrow(() -> CoreValidations.validateEmpty(List.of(), "bla")); @@ -96,8 +115,11 @@ void shouldValidateEmpty() { @Test void shouldValidateContains() { // Act & assert - final Exception e = - assertThrows(IllegalArgumentException.class, () -> CoreValidations.validateContains(List.of(1), 2, "bla")); + final List badList = List.of(1); + final Exception e = assertThrows( + IllegalArgumentException.class, + () -> CoreValidations.validateContains(badList, 2, "bla") + ); assertThat(e.getMessage()).isEqualTo("bla"); assertDoesNotThrow(() -> CoreValidations.validateContains(List.of(1), 1, "bla")); @@ -106,9 +128,10 @@ void shouldValidateContains() { @Test void shouldValidateNotContains() { // Act & assert + final List badList = List.of(1); final Exception e = assertThrows( IllegalArgumentException.class, - () -> CoreValidations.validateNotContains(List.of(1), 1, "bla") + () -> CoreValidations.validateNotContains(badList, 1, "bla") ); assertThat(e.getMessage()).isEqualTo("bla"); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java index 5fab7dcbf..06b95c530 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/UpgradeContainer.java @@ -19,7 +19,7 @@ public UpgradeContainer(final UpgradeDestination destination, final UpgradeRegis public UpgradeContainer(final UpgradeDestination destination, final UpgradeRegistry registry, final Runnable listener) { - super(UpgradeConstants.UPGRADE_SLOTS); + super(4); this.destination = destination; this.registry = registry; this.addListener(container -> listener.run()); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java index 330ec104a..37fab324e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/ImporterContainerMenu.java @@ -72,10 +72,10 @@ public ImporterContainerMenu(final int syncId, private void addSlots(final Player player, final ResourceFilterContainer resourceFilterContainer, final UpgradeContainer upgradeContainer) { - for (int i = 0; i < 9; ++i) { + for (int i = 0; i < resourceFilterContainer.size(); ++i) { addSlot(createFilterSlot(resourceFilterContainer, i)); } - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < upgradeContainer.getContainerSize(); ++i) { addSlot(new Slot(upgradeContainer, i, 187, 6 + (i * 18))); } addPlayerInventory(player.getInventory(), 8, 55); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java index 3c1c39cbd..7c0a3bc04 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/storage/block/AbstractStorageBlockContainerMenu.java @@ -52,7 +52,7 @@ protected AbstractStorageBlockContainerMenu(final MenuType type, } private void addSlots(final Player player, final ResourceFilterContainer resourceFilterContainer) { - for (int i = 0; i < 9; ++i) { + for (int i = 0; i < resourceFilterContainer.size(); ++i) { addSlot(createFilterSlot(resourceFilterContainer, i)); } addPlayerInventory(player.getInventory(), 8, 141); From a0d0015a43bfa3c387f790f62df75c4c0fd3b348 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Tue, 2 Aug 2022 09:05:04 +0200 Subject: [PATCH 19/23] Fix importer not extracting energy. --- .../node/diskdrive/DiskDriveNetworkNode.java | 2 +- .../node/importer/ImporterNetworkNode.java | 7 ++-- .../network/node/SimpleNetworkNodeTest.java | 13 +++++++ .../diskdrive/DiskDriveNetworkNodeTest.java | 2 +- .../importer/ImporterNetworkNodeTest.java | 36 +++++++++++++++++-- .../test/extension/NetworkTestExtension.java | 7 ++-- .../extension/NetworkTestExtensionTest.java | 12 +++++++ .../AbstractDiskDriveBlockEntity.java | 2 +- 8 files changed, 70 insertions(+), 11 deletions(-) diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java index 712de0286..30994ee0e 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNode.java @@ -245,7 +245,7 @@ public Optional> getStorageForChannel(final StorageChannelType return Optional.empty(); } - public int getDiskCount() { + public int getAmountOfDiskSlots() { return disks.length; } diff --git a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java index 5a3e10e6c..4cdc14508 100644 --- a/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java +++ b/refinedstorage2-network-api/src/main/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNode.java @@ -6,7 +6,6 @@ import com.refinedmods.refinedstorage2.api.network.node.NetworkNodeActor; import com.refinedmods.refinedstorage2.api.storage.Actor; -import java.util.Objects; import java.util.Set; import java.util.function.UnaryOperator; import javax.annotation.Nullable; @@ -29,9 +28,11 @@ public void setTransferStrategy(@Nullable final ImporterTransferStrategy transfe @Override public void doWork() { - if (isActive() && transferStrategy != null) { - transferStrategy.transfer(filter, actor, Objects.requireNonNull(network)); + super.doWork(); + if (network == null || !isActive() || transferStrategy == null) { + return; } + transferStrategy.transfer(filter, actor, network); } public FilterMode getFilterMode() { diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java index e3d621448..ac1f335ae 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/SimpleNetworkNodeTest.java @@ -10,6 +10,7 @@ import org.junit.jupiter.api.extension.ExtendWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @ExtendWith(NetworkTestExtension.class) @SetupNetwork(energyStored = 10, energyCapacity = 100) @@ -17,12 +18,18 @@ class SimpleNetworkNodeTest { @AddNetworkNode(energyUsage = 10, active = false) SimpleNetworkNode sut; + @AddNetworkNode(networkId = "nonexistent") + SimpleNetworkNode sutWithoutNetwork; + @Test void testInitialState() { // Assert assertThat(sut.isActive()).isFalse(); assertThat(sut.getNetwork()).isNotNull(); assertThat(sut.getEnergyUsage()).isEqualTo(10); + + assertThat(sutWithoutNetwork.isActive()).isTrue(); + assertThat(sutWithoutNetwork.getNetwork()).isNull(); } @Test @@ -34,6 +41,12 @@ void shouldNotExtractEnergyWhenInactive(@InjectNetworkEnergyComponent final Ener assertThat(energy.getStored()).isEqualTo(10); } + @Test + void shouldNotExtractEnergyWithoutNetwork() { + // Act + assertDoesNotThrow(sutWithoutNetwork::doWork); + } + @Test void shouldExtractEnergy(@InjectNetworkEnergyComponent final EnergyNetworkComponent energy) { // Arrange diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java index 82de49624..40f3202f3 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/diskdrive/DiskDriveNetworkNodeTest.java @@ -90,7 +90,7 @@ void testInitialState(@InjectNetworkStorageChannel final StorageChannel assertThat(states.getStates()) .hasSize(9) .allMatch(state -> state == StorageDiskState.NONE); - assertThat(sut.getDiskCount()).isEqualTo(9); + assertThat(sut.getAmountOfDiskSlots()).isEqualTo(9); } @ParameterizedTest diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java index 055984de9..cf718391c 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/node/importer/ImporterNetworkNodeTest.java @@ -2,8 +2,10 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.core.filter.FilterMode; +import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; import com.refinedmods.refinedstorage2.api.network.test.NetworkTestFixtures; import com.refinedmods.refinedstorage2.api.network.test.extension.AddNetworkNode; +import com.refinedmods.refinedstorage2.api.network.test.extension.InjectNetworkEnergyComponent; import com.refinedmods.refinedstorage2.api.network.test.extension.InjectNetworkStorageChannel; import com.refinedmods.refinedstorage2.api.network.test.extension.NetworkTestExtension; import com.refinedmods.refinedstorage2.api.network.test.extension.SetupNetwork; @@ -21,13 +23,17 @@ import org.junit.jupiter.api.extension.ExtendWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @ExtendWith(NetworkTestExtension.class) -@SetupNetwork +@SetupNetwork(energyStored = 1000, energyCapacity = 1000) class ImporterNetworkNodeTest { @AddNetworkNode ImporterNetworkNode sut; + @AddNetworkNode(networkId = "nonexistent") + ImporterNetworkNode sutWithoutNetwork; + @BeforeEach void setUp() { sut.setEnergyUsage(5); @@ -40,19 +46,42 @@ void testInitialState() { assertThat(sut.getFilterMode()).isEqualTo(FilterMode.BLOCK); } + @Test + void shouldExtractEnergy( + @InjectNetworkEnergyComponent final EnergyNetworkComponent energy + ) { + // Act + sut.doWork(); + + // Assert + assertThat(energy.getStored()).isEqualTo(1000 - 5); + } + @Test void shouldNotWorkWithoutTransferStrategy( - @InjectNetworkStorageChannel final StorageChannel storageChannel + @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkEnergyComponent final EnergyNetworkComponent energy ) { // Act sut.doWork(); // Assert assertThat(storageChannel.getAll()).isEmpty(); + assertThat(energy.getStored()).isEqualTo(1000 - 5); } @Test - void shouldNotWorkWithoutBeingActive(@InjectNetworkStorageChannel final StorageChannel storageChannel) { + void shouldNotWorkWithoutNetwork() { + // Act & assert + assertDoesNotThrow(sutWithoutNetwork::doWork); + assertThat(sutWithoutNetwork.isActive()).isTrue(); + } + + @Test + void shouldNotWorkOrExtractEnergyWithoutBeingActive( + @InjectNetworkStorageChannel final StorageChannel storageChannel, + @InjectNetworkEnergyComponent final EnergyNetworkComponent energy + ) { // Arrange storageChannel.addSource(new InMemoryStorageImpl<>()); @@ -76,6 +105,7 @@ void shouldNotWorkWithoutBeingActive(@InjectNetworkStorageChannel final StorageC new ResourceAmount<>("A", 100), new ResourceAmount<>("B", 100) ); + assertThat(energy.getStored()).isEqualTo(1000); } @Test diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java index 748238935..4ae8a429b 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtension.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.Map; import java.util.function.Function; +import javax.annotation.Nullable; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; @@ -131,9 +132,11 @@ private void tryAddSimpleNetworkNode(final Object testInstance, final Field fiel private void registerNetworkNode(final Object testInstance, final Field field, final NetworkNode networkNode, - final Network network) { + @Nullable final Network network) { networkNode.setNetwork(network); - network.addContainer(() -> networkNode); + if (network != null) { + network.addContainer(() -> networkNode); + } setField(testInstance, field, networkNode); } diff --git a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java index 86e80db02..609708025 100644 --- a/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java +++ b/refinedstorage2-network-api/src/test/java/com/refinedmods/refinedstorage2/api/network/test/extension/NetworkTestExtensionTest.java @@ -4,6 +4,7 @@ import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; import com.refinedmods.refinedstorage2.api.network.component.GraphNetworkComponent; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.node.SimpleNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; import com.refinedmods.refinedstorage2.api.network.node.diskdrive.DiskDriveNetworkNode; import com.refinedmods.refinedstorage2.api.network.node.storage.StorageNetworkNode; @@ -32,6 +33,9 @@ class NetworkTestExtensionTest { @AddDiskDrive(networkId = "b", active = false) DiskDriveNetworkNode storageInB; + @AddNetworkNode(networkId = "nonexistent") + SimpleNetworkNode nonexistentNetworkNode; + @Test void shouldInjectNetwork() { // Assert @@ -40,6 +44,14 @@ void shouldInjectNetwork() { assertThat(a).isNotSameAs(b); } + @Test + void shouldSetNetwork() { + // Assert + assertThat(nonexistentNetworkNode.getNetwork()).isNull(); + assertThat(storageInA.getNetwork()).isEqualTo(a); + assertThat(storageInB.getNetwork()).isEqualTo(b); + } + @Test void shouldSetActivenessOfNetworkNode() { // Assert diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java index 4309ac13b..3efa476bf 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java @@ -90,7 +90,7 @@ protected AbstractDiskDriveBlockEntity(final BlockPos pos, final BlockState stat PlatformApi.INSTANCE.getStorageChannelTypeRegistry(), AMOUNT_OF_DISKS )); - this.diskInventory = new DiskDriveInventory(this, getNode().getDiskCount()); + this.diskInventory = new DiskDriveInventory(this, getNode().getAmountOfDiskSlots()); getNode().setDiskProvider(diskInventory); getNode().setListener(this); getNode().setNormalizer(value -> FuzzyModeNormalizer.tryNormalize(exactMode, value)); From 17d840aef0d8e35969e90005bba3fc043080fbe4 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 6 Aug 2022 13:00:30 +0200 Subject: [PATCH 20/23] Small cleanup + use rate limiters instead. --- .../api/core/CoreValidationsTest.java | 2 +- ...ternalNetworkNodeContainerBlockEntity.java | 17 +++++-------- .../block/entity/ControllerBlockEntity.java | 14 +++++------ .../AbstractDiskDriveBlockEntity.java | 9 +++---- .../fabric/ClientModInitializerImpl.java | 9 ++++--- .../baked/transform/EmissiveTransform.java | 25 ++++++++++++------- .../model/DiskDriveUnbakedGeometry.java | 2 +- .../model/baked/DiskDriveBakedModel.java | 2 ++ .../model/baked/DiskDriveItemBakedModel.java | 9 ++++--- 9 files changed, 47 insertions(+), 42 deletions(-) diff --git a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java b/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java index 8a198d080..c49254591 100644 --- a/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java +++ b/refinedstorage2-core-api/src/test/java/com/refinedmods/refinedstorage2/api/core/CoreValidationsTest.java @@ -60,7 +60,7 @@ void shouldValidateNotNegative() { assertDoesNotThrow(() -> CoreValidations.validateNotNegative(0, "bla")); assertDoesNotThrow(() -> CoreValidations.validateNotNegative(1, "bla")); - assertThat(CoreValidations.validateNotNegative(0, "test")).isEqualTo(0); + assertThat(CoreValidations.validateNotNegative(0, "test")).isZero(); } @Test diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java index 0439c823e..17ce105f9 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java @@ -22,12 +22,11 @@ public abstract class AbstractInternalNetworkNodeContainerBlockEntity { private static final Logger LOGGER = LogManager.getLogger(); - private static final int ACTIVE_CHANGE_MINIMUM_INTERVAL_MS = 1000; private static final String TAG_REDSTONE_MODE = "rm"; + private final RateLimiter activenessChangeRateLimiter = RateLimiter.create(1); @Nullable private Boolean lastActive; - private long lastActiveChanged; private RedstoneMode redstoneMode = RedstoneMode.IGNORE; protected AbstractInternalNetworkNodeContainerBlockEntity(final BlockEntityType type, @@ -66,16 +65,12 @@ public void updateActiveness(final BlockState state, lastActive = getNode().isActive(); } - final boolean active = isActive(); - final boolean inTime = System.currentTimeMillis() - lastActiveChanged > ACTIVE_CHANGE_MINIMUM_INTERVAL_MS; + final boolean newActive = isActive(); - if (active != lastActive && (lastActiveChanged == 0 || inTime)) { - LOGGER.info("Activeness change for node at {}: {} -> {}", getBlockPos(), lastActive, active); - - this.lastActive = active; - this.lastActiveChanged = System.currentTimeMillis(); - - activenessChanged(state, active, activenessProperty); + if (newActive != lastActive && activenessChangeRateLimiter.tryAcquire()) { + LOGGER.info("Activeness change for node at {}: {} -> {}", getBlockPos(), lastActive, newActive); + this.lastActive = newActive; + activenessChanged(state, newActive, activenessProperty); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java index 0ef5abcb4..1363fce73 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java @@ -12,6 +12,7 @@ import javax.annotation.Nullable; +import com.google.common.util.concurrent.RateLimiter; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; @@ -33,11 +34,10 @@ public class ControllerBlockEntity extends AbstractInternalNetworkNodeContainerB private static final String TAG_STORED = "stored"; private static final String TAG_CAPACITY = "capacity"; - private static final int ENERGY_TYPE_CHANGE_MINIMUM_INTERVAL_MS = 1000; private final ControllerType type; private final EnergyStorage energyStorage; - private long lastTypeChanged; + private final RateLimiter energyStateChangeRateLimiter = RateLimiter.create(1); public ControllerBlockEntity(final ControllerType type, final BlockPos pos, final BlockState state) { super(getBlockEntityType(type), pos, state, new ControllerNetworkNode()); @@ -65,19 +65,17 @@ public static boolean hasEnergy(@Nullable final CompoundTag tag) { } public void updateEnergyTypeInLevel(final BlockState state) { - final ControllerEnergyType energyType = ControllerEnergyType.ofState(getNode().getState()); + final ControllerEnergyType currentEnergyType = ControllerEnergyType.ofState(getNode().getState()); final ControllerEnergyType inLevelEnergyType = state.getValue(ControllerBlock.ENERGY_TYPE); - final boolean inTime = System.currentTimeMillis() - lastTypeChanged > ENERGY_TYPE_CHANGE_MINIMUM_INTERVAL_MS; - if (energyType != inLevelEnergyType && (lastTypeChanged == 0 || inTime)) { + if (currentEnergyType != inLevelEnergyType && energyStateChangeRateLimiter.tryAcquire()) { LOGGER.info( "Energy type state change for Controller at {}: {} -> {}", getBlockPos(), inLevelEnergyType, - energyType + currentEnergyType ); - this.lastTypeChanged = System.currentTimeMillis(); - updateEnergyTypeInLevel(state, energyType); + updateEnergyTypeInLevel(state, currentEnergyType); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java index 3efa476bf..f9120d965 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java @@ -24,6 +24,7 @@ import javax.annotation.Nullable; +import com.google.common.util.concurrent.RateLimiter; import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; import net.minecraft.nbt.ByteTag; @@ -66,8 +67,6 @@ public abstract class AbstractDiskDriveBlockEntity private static final String TAG_STATES = "states"; private static final String TAG_RESOURCE_FILTER = "rf"; - private static final int DISK_STATE_CHANGE_MINIMUM_INTERVAL_MS = 1000; - @Nullable protected DiskDriveState driveState; @@ -77,9 +76,9 @@ public abstract class AbstractDiskDriveBlockEntity 9, this::resourceFilterContainerChanged ); + private final RateLimiter diskStateChangeRateLimiter = RateLimiter.create(1); private boolean syncRequested; - private long lastStateChanged; private boolean exactMode; @@ -105,10 +104,8 @@ public void updateDiskStateIfNecessaryInLevel() { if (!syncRequested) { return; } - final boolean inTime = (System.currentTimeMillis() - lastStateChanged) > DISK_STATE_CHANGE_MINIMUM_INTERVAL_MS; - if (lastStateChanged == 0 || inTime) { + if (diskStateChangeRateLimiter.tryAcquire()) { LOGGER.info("Disk state change for block at {}", getBlockPos()); - this.lastStateChanged = System.currentTimeMillis(); this.syncRequested = false; sync(); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java index 6b5d610e9..aa574e303 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java @@ -90,17 +90,20 @@ private void registerEmissiveModels() { } private void registerEmissiveControllerModels(final DyeColor color) { + final ResourceLocation spriteLocation = createIdentifier("block/controller/cutouts/" + color.getName()); + // Block EmissiveModelRegistry.INSTANCE.register( createIdentifier("block/controller/" + color.getName()), - createIdentifier("block/controller/cutouts/" + color.getName()) + spriteLocation ); + // Item EmissiveModelRegistry.INSTANCE.register( ColorMap.generateId(color, IdentifierUtil.MOD_ID, "controller"), - createIdentifier("block/controller/cutouts/" + color.getName()) + spriteLocation ); EmissiveModelRegistry.INSTANCE.register( ColorMap.generateId(color, IdentifierUtil.MOD_ID, "creative_controller"), - createIdentifier("block/controller/cutouts/" + color.getName()) + spriteLocation ); } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/baked/transform/EmissiveTransform.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/baked/transform/EmissiveTransform.java index 176034e3f..088c76f7d 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/baked/transform/EmissiveTransform.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/model/baked/transform/EmissiveTransform.java @@ -18,24 +18,31 @@ public EmissiveTransform(final ResourceLocation emissiveSprite) { @Override public boolean transform(final MutableQuadView quad) { - final SpriteFinder finder = SpriteFinder.get( - Minecraft.getInstance().getModelManager().getAtlas(TextureAtlas.LOCATION_BLOCKS) - ); + doTransform(quad); + return true; + } + + private void doTransform(final MutableQuadView quad) { + final SpriteFinder finder = SpriteFinder.get(getAtlas()); if (finder == null) { - return true; + return; } final TextureAtlasSprite sprite = finder.find(quad, 0); if (sprite == null) { - return true; + return; } if (!emissiveSprite.equals(sprite.getName())) { - return true; + return; } - doTransform(quad); - return true; + applyLightmap(quad); } - private void doTransform(final MutableQuadView quad) { + @SuppressWarnings("deprecation") + private static TextureAtlas getAtlas() { + return Minecraft.getInstance().getModelManager().getAtlas(TextureAtlas.LOCATION_BLOCKS); + } + + private void applyLightmap(final MutableQuadView quad) { quad.lightmap(0, LightTexture.pack(15, 15)); quad.lightmap(1, LightTexture.pack(15, 15)); quad.lightmap(2, LightTexture.pack(15, 15)); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/DiskDriveUnbakedGeometry.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/DiskDriveUnbakedGeometry.java index 93297bdca..653ce89e1 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/DiskDriveUnbakedGeometry.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/DiskDriveUnbakedGeometry.java @@ -73,7 +73,7 @@ private Function getDiskItemModelBakery(final ModelState s final ModelBakery bakery, final Function sg) { - return (trans) -> { + return trans -> { final Transformation translation = new Transformation(trans, null, null, null); final ModelState wrappedState = new SimpleModelState(translation, state.isUvLocked()); return bakery.bake(DISK_DISCONNECTED_MODEL, wrappedState, sg); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java index b9441dbee..3f26eea32 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveBakedModel.java @@ -189,6 +189,7 @@ public List load(final DiskDriveStateCacheKey key) { return quads; } + @SuppressWarnings("deprecation") private List getBaseQuads(final BlockState state, final RandomSource rand, @Nullable final Direction side, @@ -200,6 +201,7 @@ private List getBaseQuads(final BlockState state, ); } + @SuppressWarnings("deprecation") private List getDiskModel(final BlockState state, final RandomSource rand, @Nullable final Direction side, diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java index 129512696..7f0c08b28 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/model/baked/DiskDriveItemBakedModel.java @@ -46,9 +46,10 @@ public ItemOverrides getOverrides() { } @Override - public @Nonnull List getQuads(@Nullable final BlockState state, - @Nullable final Direction side, - @Nonnull final RandomSource rand) { + @Nonnull + public List getQuads(@Nullable final BlockState state, + @Nullable final Direction side, + @Nonnull final RandomSource rand) { if (side == null) { if (noSideCache == null) { noSideCache = createQuads(state, null, rand); @@ -58,6 +59,7 @@ public ItemOverrides getOverrides() { return cache.computeIfAbsent(side, key -> createQuads(state, side, rand)); } + @SuppressWarnings("deprecation") private List createQuads(@Nullable final BlockState state, @Nullable final Direction side, @Nonnull final RandomSource rand) { @@ -80,6 +82,7 @@ public List getRenderPasses(final ItemStack itemStack, final boolean } @Override + @SuppressWarnings("deprecation") public BakedModel applyTransform(final ItemTransforms.TransformType cameraTransformType, final PoseStack poseStack, final boolean applyLeftHandTransform) { From ab6a198fa447a8f9cb1f72a9367f8c9aa4cae301 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 6 Aug 2022 13:44:51 +0200 Subject: [PATCH 21/23] Fixed Grid tooltip being too small in some cases and item durability not being rendered. Fixes #206 --- CHANGELOG.md | 1 + .../grid/AbstractGridContainerMenu.java | 2 +- .../common/screen/SmallTextTooltipRenderer.java | 14 ++++++-------- .../common/screen/grid/ItemGridScreen.java | 5 ++++- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e95e9fb3d..cd915d486 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed - Fixed network connection state not rebuilding after using Wrench on a directional block. +- Fixed Grid tooltip being too small in some cases and item durability not being rendered. ### Added diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java index 5b8054b57..198906506 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/AbstractGridContainerMenu.java @@ -111,7 +111,7 @@ protected AbstractGridContainerMenu(final MenuType type, protected abstract ResourceAmount readResourceAmount(FriendlyByteBuf buf); public void onResourceUpdate(final T template, final long amount, @Nullable final TrackedResource trackedResource) { - LOGGER.info("{} got updated with {}", template, amount); + LOGGER.debug("{} got updated with {}", template, amount); view.onChange(template, amount, trackedResource); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java index 996f5886b..c7c92043f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java @@ -37,7 +37,7 @@ public void render(@Nullable final Minecraft minecraft, } final float smallTextScale = (minecraft != null && minecraft.isEnforceUnicode()) ? 1F : 0.7F; final int tooltipWidth = calculateWidth(font, lines, smallLines, smallTextScale); - final int tooltipHeight = calculateHeight(lines, smallLines); + final int tooltipHeight = calculateHeight(font, lines, smallLines); final int tooltipX = calculateTooltipX(x, screenWidth, tooltipWidth); final int tooltipY = calculateTooltipY(y, screenHeight, tooltipHeight); render(font, poseStack, lines, smallLines, smallTextScale, tooltipWidth, tooltipHeight, tooltipX, tooltipY); @@ -145,14 +145,12 @@ private int calculateWidth(final Font font, } - private int calculateHeight(final List lines, + private int calculateHeight(final Font font, + final List lines, final List smallLines) { - int tooltipHeight = 8; - if (lines.size() > 1) { - tooltipHeight += 2 + (lines.size() - 1) * 10; - } - tooltipHeight += smallLines.size() * 10; - return tooltipHeight; + int tooltipHeight = (lines.size() * 12); + tooltipHeight += smallLines.size() * 9; + return tooltipHeight - (Minecraft.getInstance().isEnforceUnicode() ? 0 : 3); } private int calculateTooltipX(final int x, final int screenWidth, final int tooltipWidth) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java index e27533dfa..bb9569471 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java @@ -13,6 +13,7 @@ import javax.annotation.Nullable; import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; @@ -78,7 +79,9 @@ protected void renderResource(final PoseStack poseStack, final int slotX, final int slotY, final AbstractGridResource resource) { - itemRenderer.renderAndDecorateItem(((ItemGridResource) resource).getItemStack(), slotX, slotY); + final ItemStack itemStack = ((ItemGridResource) resource).getItemStack(); + itemRenderer.renderGuiItem(itemStack, slotX, slotY); + itemRenderer.renderGuiItemDecorations(Minecraft.getInstance().font, itemStack, slotX, slotY, null); } @Override From a7ca5ae8ce351c27608b5387a01cd404d7880bb1 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 6 Aug 2022 13:45:10 +0200 Subject: [PATCH 22/23] Stop using initial null value, it's not needed. --- .../AbstractInternalNetworkNodeContainerBlockEntity.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java index 17ce105f9..b8544cc34 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/AbstractInternalNetworkNodeContainerBlockEntity.java @@ -25,8 +25,7 @@ public abstract class AbstractInternalNetworkNodeContainerBlockEntity type, @@ -61,12 +60,7 @@ public void load(final CompoundTag tag) { public void updateActiveness(final BlockState state, @Nullable final BooleanProperty activenessProperty) { - if (lastActive == null) { - lastActive = getNode().isActive(); - } - final boolean newActive = isActive(); - if (newActive != lastActive && activenessChangeRateLimiter.tryAcquire()) { LOGGER.info("Activeness change for node at {}: {} -> {}", getBlockPos(), lastActive, newActive); this.lastActive = newActive; From 5ad28ca72f91124c5fa7d6e4171b32db3e4278fd Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 6 Aug 2022 13:47:02 +0200 Subject: [PATCH 23/23] Use non static font. --- .../platform/common/screen/SmallTextTooltipRenderer.java | 5 ++--- .../platform/common/screen/grid/ItemGridScreen.java | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java index c7c92043f..8fca7219b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/SmallTextTooltipRenderer.java @@ -37,7 +37,7 @@ public void render(@Nullable final Minecraft minecraft, } final float smallTextScale = (minecraft != null && minecraft.isEnforceUnicode()) ? 1F : 0.7F; final int tooltipWidth = calculateWidth(font, lines, smallLines, smallTextScale); - final int tooltipHeight = calculateHeight(font, lines, smallLines); + final int tooltipHeight = calculateHeight(lines, smallLines); final int tooltipX = calculateTooltipX(x, screenWidth, tooltipWidth); final int tooltipY = calculateTooltipY(y, screenHeight, tooltipHeight); render(font, poseStack, lines, smallLines, smallTextScale, tooltipWidth, tooltipHeight, tooltipX, tooltipY); @@ -145,8 +145,7 @@ private int calculateWidth(final Font font, } - private int calculateHeight(final Font font, - final List lines, + private int calculateHeight(final List lines, final List smallLines) { int tooltipHeight = (lines.size() * 12); tooltipHeight += smallLines.size() * 9; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java index bb9569471..151c1d6e9 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/ItemGridScreen.java @@ -13,7 +13,6 @@ import javax.annotation.Nullable; import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; @@ -81,7 +80,7 @@ protected void renderResource(final PoseStack poseStack, final AbstractGridResource resource) { final ItemStack itemStack = ((ItemGridResource) resource).getItemStack(); itemRenderer.renderGuiItem(itemStack, slotX, slotY); - itemRenderer.renderGuiItemDecorations(Minecraft.getInstance().font, itemStack, slotX, slotY, null); + itemRenderer.renderGuiItemDecorations(font, itemStack, slotX, slotY, null); } @Override