Compare commits

..

No commits in common. "a8d1a99e286bc7fae355d6b44c4fd64b07afb7a1" and "c8adbc271abbab8bf8e59ca714484d96c6744e2c" have entirely different histories.

64 changed files with 792 additions and 763 deletions

View file

@ -3,16 +3,7 @@ plugins {
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.neoforged.gradle.userdev' version '7.0.163'
}
tasks.named('wrapper', Wrapper).configure {
// Define wrapper values here so as to not have to always do so when updating gradlew.properties.
// Switching this to Wrapper.DistributionType.ALL will download the full gradle sources that comes with
// documentation attached on cursor hover of gradle classes and methods. However, this comes with increased
// file size for Gradle. If you do switch this to ALL, run the Gradle wrapper task twice afterwards.
// (Verify by checking gradle/wrapper/gradle-wrapper.properties to see if distributionUrl now points to `-all`)
distributionType = Wrapper.DistributionType.BIN
id 'net.neoforged.gradle.userdev' version '7.0.80'
}
// Enable the Jar-in-Jar system for your mod
@ -36,8 +27,8 @@ base {
archivesName = mod_name
}
// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
runs {
@ -71,7 +62,7 @@ runs {
server {
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
argument '--nogui'
programArgument '--nogui'
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
@ -86,7 +77,7 @@ runs {
// workingDirectory project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
arguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
}
}
@ -136,8 +127,8 @@ tasks.withType(ProcessResources).configureEach {
]
inputs.properties replaceProperties
filesMatching(['META-INF/neoforge.mods.toml']) {
expand replaceProperties
filesMatching(['META-INF/mods.toml']) {
expand replaceProperties + [project: project]
}
}
@ -163,11 +154,3 @@ publishing {
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior.
idea {
module {
downloadSources = true
downloadJavadoc = true
}
}

View file

@ -1,24 +1,22 @@
org.gradle.jvmargs=-Xmx1G
org.gradle.daemon=false
org.gradle.debug=false
#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings
# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started
neogradle.subsystems.parchment.minecraftVersion=1.21
neogradle.subsystems.parchment.mappingsVersion=2024.07.28
neogradle.subsystems.parchment.minecraftVersion=1.20.3
neogradle.subsystems.parchment.mappingsVersion=2023.12.31
# Environment Properties
# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge
# The Minecraft version must agree with the Neo version to get a valid artifact
minecraft_version=1.21.1
minecraft_version_range=[1.21.1,1.22)
minecraft_version=1.20.4
minecraft_version_range=[1.20.4,1.21)
# The Neo version must agree with the Minecraft version to get a valid artifact
neo_version=21.1.45
neo_version=20.4.195
# The Neo version range can use any version of Neo as bounds
neo_version_range=[21.1.0,)
neo_version_range=[20.4,)
# The loader version range can only use the major version of FML as bounds
loader_version_range=[4,)
loader_version_range=[2,)
jei_version=19.18.3.204
jei_version=17.3.0.49
jgt_version=1.5.2
jheaps_version=0.14
apfloat_version=1.10.1

Binary file not shown.

View file

@ -1,7 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

54
gradlew vendored
View file

@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -15,8 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
@ -34,10 +32,10 @@
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
@ -57,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@ -82,12 +80,13 @@ do
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@ -134,29 +133,22 @@ location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@ -201,15 +193,11 @@ if "$cygwin" || "$msys" ; then
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
@ -217,12 +205,6 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.

37
gradlew.bat vendored
View file

@ -13,10 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@ -27,8 +25,7 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@ -43,13 +40,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
if "%ERRORLEVEL%" == "0" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
@ -59,11 +56,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
@ -78,15 +75,13 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View file

@ -3,9 +3,7 @@ package de.ellpeck.prettypipes;
import de.ellpeck.prettypipes.entities.PipeFrameEntity;
import de.ellpeck.prettypipes.entities.PipeFrameRenderer;
import de.ellpeck.prettypipes.items.*;
import de.ellpeck.prettypipes.misc.DirectionSelector;
import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.misc.ModuleClearingRecipe;
import de.ellpeck.prettypipes.packets.*;
import de.ellpeck.prettypipes.pipe.IPipeConnectable;
@ -49,6 +47,7 @@ import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalGui;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.minecraft.client.renderer.entity.EntityRenderers;
import net.minecraft.core.Direction;
@ -69,26 +68,24 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockBehaviour.Properties;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.common.Mod.EventBusSubscriber;
import net.neoforged.fml.common.Mod.EventBusSubscriber.Bus;
import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
import net.neoforged.neoforge.capabilities.BlockCapability;
import net.neoforged.neoforge.capabilities.Capabilities;
import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent;
import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent;
import net.neoforged.neoforge.common.extensions.IMenuTypeExtension;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlerEvent;
import net.neoforged.neoforge.registries.RegisterEvent;
import java.util.Comparator;
import java.util.Locale;
import java.util.function.BiFunction;
import static net.neoforged.fml.common.EventBusSubscriber.Bus;
@EventBusSubscriber(bus = Bus.MOD)
public final class Registry {
public static BlockCapability<IPipeConnectable, Direction> pipeConnectableCapability = BlockCapability.createSided(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_connectable"), IPipeConnectable.class);
public static BlockCapability<IPipeConnectable, Direction> pipeConnectableCapability = BlockCapability.createSided(new ResourceLocation(PrettyPipes.ID, "pipe_connectable"), IPipeConnectable.class);
public static Item wrenchItem;
public static Item pipeFrameItem;
@ -122,19 +119,19 @@ public final class Registry {
@SubscribeEvent
public static void register(RegisterEvent event) {
event.register(Registries.BLOCK, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe"), Registry.pipeBlock = new PipeBlock(Properties.of().strength(2).sound(SoundType.STONE).noOcclusion()));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlock = new ItemTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE)));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlock = new CraftingTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE)));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlock = new PressurizerBlock(Properties.of().strength(3).sound(SoundType.STONE)));
h.register(new ResourceLocation(PrettyPipes.ID, "pipe"), Registry.pipeBlock = new PipeBlock(Properties.of().strength(2).sound(SoundType.STONE).noOcclusion()));
h.register(new ResourceLocation(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlock = new ItemTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE)));
h.register(new ResourceLocation(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlock = new CraftingTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE)));
h.register(new ResourceLocation(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlock = new PressurizerBlock(Properties.of().strength(3).sound(SoundType.STONE)));
});
event.register(Registries.ITEM, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "wrench"), Registry.wrenchItem = new WrenchItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "blank_module"), new Item(new Item.Properties()));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameItem = new PipeFrameItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "stack_size_module"), new StackSizeModuleItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "redstone_module"), new RedstoneModuleItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "filter_increase_modifier"), new FilterIncreaseModuleItem());
h.register(new ResourceLocation(PrettyPipes.ID, "wrench"), Registry.wrenchItem = new WrenchItem());
h.register(new ResourceLocation(PrettyPipes.ID, "blank_module"), new Item(new Item.Properties()));
h.register(new ResourceLocation(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameItem = new PipeFrameItem());
h.register(new ResourceLocation(PrettyPipes.ID, "stack_size_module"), new StackSizeModuleItem());
h.register(new ResourceLocation(PrettyPipes.ID, "redstone_module"), new RedstoneModuleItem());
h.register(new ResourceLocation(PrettyPipes.ID, "filter_increase_modifier"), new FilterIncreaseModuleItem());
Registry.registerTieredModule(h, "extraction_module", ExtractionModuleItem::new);
Registry.registerTieredModule(h, "filter_module", FilterModuleItem::new);
@ -146,33 +143,33 @@ public final class Registry {
for (var type : ItemEquality.Type.values()) {
var name = type.name().toLowerCase(Locale.ROOT) + "_filter_modifier";
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, name), new FilterModifierModuleItem(name, type));
h.register(new ResourceLocation(PrettyPipes.ID, name), new FilterModifierModuleItem(name, type));
}
for (var type : SortingModuleItem.Type.values()) {
var name = type.name().toLowerCase(Locale.ROOT) + "_sorting_modifier";
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, name), new SortingModuleItem(name, type));
h.register(new ResourceLocation(PrettyPipes.ID, name), new SortingModuleItem(name, type));
}
BuiltInRegistries.BLOCK.entrySet().stream()
.filter(b -> b.getKey().location().getNamespace().equals(PrettyPipes.ID))
.forEach(b -> h.register(b.getKey().location(), new BlockItem(b.getValue(), new Item.Properties())));
.filter(b -> b.getKey().location().getNamespace().equals(PrettyPipes.ID))
.forEach(b -> h.register(b.getKey().location(), new BlockItem(b.getValue(), new Item.Properties())));
});
event.register(Registries.BLOCK_ENTITY_TYPE, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe"), Registry.pipeBlockEntity = BlockEntityType.Builder.of(PipeBlockEntity::new, Registry.pipeBlock).build(null));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlockEntity = BlockEntityType.Builder.of(ItemTerminalBlockEntity::new, Registry.itemTerminalBlock).build(null));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlockEntity = BlockEntityType.Builder.of(CraftingTerminalBlockEntity::new, Registry.craftingTerminalBlock).build(null));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlockEntity = BlockEntityType.Builder.of(PressurizerBlockEntity::new, Registry.pressurizerBlock).build(null));
h.register(new ResourceLocation(PrettyPipes.ID, "pipe"), Registry.pipeBlockEntity = BlockEntityType.Builder.of(PipeBlockEntity::new, Registry.pipeBlock).build(null));
h.register(new ResourceLocation(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlockEntity = BlockEntityType.Builder.of(ItemTerminalBlockEntity::new, Registry.itemTerminalBlock).build(null));
h.register(new ResourceLocation(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlockEntity = BlockEntityType.Builder.of(CraftingTerminalBlockEntity::new, Registry.craftingTerminalBlock).build(null));
h.register(new ResourceLocation(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlockEntity = BlockEntityType.Builder.of(PressurizerBlockEntity::new, Registry.pressurizerBlock).build(null));
});
event.register(Registries.ENTITY_TYPE, h ->
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameEntity = EntityType.Builder.<PipeFrameEntity>of(PipeFrameEntity::new, MobCategory.MISC).build("pipe_frame")));
h.register(new ResourceLocation(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameEntity = EntityType.Builder.<PipeFrameEntity>of(PipeFrameEntity::new, MobCategory.MISC).build("pipe_frame")));
event.register(Registries.MENU, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe"), Registry.pipeContainer = IMenuTypeExtension.create((windowId, inv, data) -> new MainPipeContainer(Registry.pipeContainer, windowId, inv.player, data.readBlockPos())));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new ItemTerminalContainer(Registry.itemTerminalContainer, windowId, inv.player, data.readBlockPos())));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new CraftingTerminalContainer(Registry.craftingTerminalContainer, windowId, inv.player, data.readBlockPos())));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pressurizer"), Registry.pressurizerContainer = IMenuTypeExtension.create((windowId, inv, data) -> new PressurizerContainer(Registry.pressurizerContainer, windowId, inv.player, data.readBlockPos())));
h.register(new ResourceLocation(PrettyPipes.ID, "pipe"), Registry.pipeContainer = IMenuTypeExtension.create((windowId, inv, data) -> new MainPipeContainer(Registry.pipeContainer, windowId, inv.player, data.readBlockPos())));
h.register(new ResourceLocation(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new ItemTerminalContainer(Registry.itemTerminalContainer, windowId, inv.player, data.readBlockPos())));
h.register(new ResourceLocation(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new CraftingTerminalContainer(Registry.craftingTerminalContainer, windowId, inv.player, data.readBlockPos())));
h.register(new ResourceLocation(PrettyPipes.ID, "pressurizer"), Registry.pressurizerContainer = IMenuTypeExtension.create((windowId, inv, data) -> new PressurizerContainer(Registry.pressurizerContainer, windowId, inv.player, data.readBlockPos())));
Registry.extractionModuleContainer = Registry.registerPipeContainer(h, "extraction_module");
Registry.filterModuleContainer = Registry.registerPipeContainer(h, "filter_module");
@ -184,27 +181,18 @@ public final class Registry {
});
event.register(BuiltInRegistries.CREATIVE_MODE_TAB.key(), h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "tab"), CreativeModeTab.builder()
.title(Component.translatable("item_group." + PrettyPipes.ID + ".tab"))
.icon(() -> new ItemStack(Registry.wrenchItem))
.displayItems((params, output) -> BuiltInRegistries.ITEM.entrySet().stream()
.filter(b -> b.getKey().location().getNamespace().equals(PrettyPipes.ID))
.sorted(Comparator.comparing(b -> b.getValue().getClass().getSimpleName()))
.forEach(b -> output.accept(b.getValue()))).build()
h.register(new ResourceLocation(PrettyPipes.ID, "tab"), CreativeModeTab.builder()
.title(Component.translatable("item_group." + PrettyPipes.ID + ".tab"))
.icon(() -> new ItemStack(Registry.wrenchItem))
.displayItems((params, output) -> BuiltInRegistries.ITEM.entrySet().stream()
.filter(b -> b.getKey().location().getNamespace().equals(PrettyPipes.ID))
.sorted(Comparator.comparing(b -> b.getValue().getClass().getSimpleName()))
.forEach(b -> output.accept(b.getValue()))).build()
);
});
event.register(Registries.RECIPE_SERIALIZER, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "module_clearing"), ModuleClearingRecipe.SERIALIZER);
});
event.register(Registries.DATA_COMPONENT_TYPE, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_module_contents"), CraftingModuleItem.Contents.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_filter_data"), ItemFilter.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "stack_size_module_data"), StackSizeModuleItem.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "direction_selector_data"), DirectionSelector.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "filter_modifier_data"), FilterModifierModuleItem.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "sorting_module_data"), SortingModuleItem.Data.TYPE);
h.register(new ResourceLocation(PrettyPipes.ID, "module_clearing"), ModuleClearingRecipe.SERIALIZER);
});
}
@ -219,14 +207,14 @@ public final class Registry {
}
@SubscribeEvent
public static void registerPayloads(final RegisterPayloadHandlersEvent event) {
public static void registerPayloads(final RegisterPayloadHandlerEvent event) {
var registrar = event.registrar(PrettyPipes.ID);
registrar.playBidirectional(PacketItemEnterPipe.TYPE, PacketItemEnterPipe.CODEC, PacketItemEnterPipe::onMessage);
registrar.playBidirectional(PacketButton.TYPE, PacketButton.CODEC, PacketButton::onMessage);
registrar.playBidirectional(PacketCraftingModuleTransfer.TYPE, PacketCraftingModuleTransfer.CODEC, PacketCraftingModuleTransfer::onMessage);
registrar.playBidirectional(PacketGhostSlot.TYPE, PacketGhostSlot.CODEC, PacketGhostSlot::onMessage);
registrar.playBidirectional(PacketNetworkItems.TYPE, PacketNetworkItems.CODEC, PacketNetworkItems::onMessage);
registrar.playBidirectional(PacketRequest.TYPE, PacketRequest.CODEC, PacketRequest::onMessage);
registrar.play(PacketItemEnterPipe.ID, PacketItemEnterPipe::new, PacketItemEnterPipe::onMessage);
registrar.play(PacketButton.ID, PacketButton::new, PacketButton::onMessage);
registrar.play(PacketCraftingModuleTransfer.ID, PacketCraftingModuleTransfer::new, PacketCraftingModuleTransfer::onMessage);
registrar.play(PacketGhostSlot.ID, PacketGhostSlot::new, PacketGhostSlot::onMessage);
registrar.play(PacketNetworkItems.ID, PacketNetworkItems::new, PacketNetworkItems::onMessage);
registrar.play(PacketRequest.ID, PacketRequest::new, PacketRequest::onMessage);
}
private static <T extends AbstractPipeContainer<?>> MenuType<T> registerPipeContainer(RegisterEvent.RegisterHelper<MenuType<?>> helper, String name) {
@ -236,13 +224,13 @@ public final class Registry {
var moduleStack = tile.modules.getStackInSlot(moduleIndex);
return ((IModule) moduleStack.getItem()).getContainer(moduleStack, tile, windowId, inv, inv.player, moduleIndex);
});
helper.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, name), type);
helper.register(new ResourceLocation(PrettyPipes.ID, name), type);
return type;
}
private static void registerTieredModule(RegisterEvent.RegisterHelper<Item> helper, String name, BiFunction<String, ModuleTier, ModuleItem> item) {
for (var tier : ModuleTier.values())
helper.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, tier.name().toLowerCase(Locale.ROOT) + "_" + name), item.apply(name, tier));
helper.register(new ResourceLocation(PrettyPipes.ID, tier.name().toLowerCase(Locale.ROOT) + "_" + name), item.apply(name, tier));
}
@EventBusSubscriber(bus = Bus.MOD, value = Dist.CLIENT)
@ -252,21 +240,18 @@ public final class Registry {
public static void setup(FMLClientSetupEvent event) {
BlockEntityRenderers.register(Registry.pipeBlockEntity, PipeRenderer::new);
EntityRenderers.register(Registry.pipeFrameEntity, PipeFrameRenderer::new);
}
@SubscribeEvent
public static void registerMenuScreens(RegisterMenuScreensEvent event) {
event.register(Registry.pipeContainer, MainPipeGui::new);
event.register(Registry.itemTerminalContainer, ItemTerminalGui::new);
event.register(Registry.pressurizerContainer, PressurizerGui::new);
event.register(Registry.craftingTerminalContainer, CraftingTerminalGui::new);
event.register(Registry.extractionModuleContainer, ExtractionModuleGui::new);
event.register(Registry.filterModuleContainer, FilterModuleGui::new);
event.register(Registry.retrievalModuleContainer, RetrievalModuleGui::new);
event.register(Registry.stackSizeModuleContainer, StackSizeModuleGui::new);
event.register(Registry.filterIncreaseModuleContainer, FilterIncreaseModuleGui::new);
event.register(Registry.craftingModuleContainer, CraftingModuleGui::new);
event.register(Registry.filterModifierModuleContainer, FilterModifierModuleGui::new);
MenuScreens.register(Registry.pipeContainer, MainPipeGui::new);
MenuScreens.register(Registry.itemTerminalContainer, ItemTerminalGui::new);
MenuScreens.register(Registry.pressurizerContainer, PressurizerGui::new);
MenuScreens.register(Registry.craftingTerminalContainer, CraftingTerminalGui::new);
MenuScreens.register(Registry.extractionModuleContainer, ExtractionModuleGui::new);
MenuScreens.register(Registry.filterModuleContainer, FilterModuleGui::new);
MenuScreens.register(Registry.retrievalModuleContainer, RetrievalModuleGui::new);
MenuScreens.register(Registry.stackSizeModuleContainer, StackSizeModuleGui::new);
MenuScreens.register(Registry.filterIncreaseModuleContainer, FilterIncreaseModuleGui::new);
MenuScreens.register(Registry.craftingModuleContainer, CraftingModuleGui::new);
MenuScreens.register(Registry.filterModifierModuleContainer, FilterModifierModuleGui::new);
}
}

View file

@ -1,17 +1,12 @@
package de.ellpeck.prettypipes;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.IntArrayTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
@ -27,7 +22,6 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.neoforged.neoforge.common.util.INBTSerializable;
import net.neoforged.neoforge.items.IItemHandler;
import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.items.wrapper.SidedInvWrapper;
import org.apache.commons.lang3.tuple.Pair;
@ -35,21 +29,9 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.IntStream;
@SuppressWarnings("ALL")
public final class Utility {
public static final Codec<ItemStackHandler> ITEM_STACK_HANDLER_CODEC = RecordCodecBuilder.create(builder -> builder.group(
Codec.INT.fieldOf("size").forGetter(h -> h.getSlots()),
Codec.list(ItemStack.CODEC).fieldOf("items").forGetter(h -> IntStream.range(0, h.getSlots()).mapToObj(h::getStackInSlot).toList())
).apply(builder, (size, items) -> {
var ret = new ItemStackHandler(size);
for (var i = 0; i < items.size(); i++)
ret.setStackInSlot(i, items.get(i));
return ret;
}));
public static <T extends BlockEntity> T getBlockEntity(Class<T> type, BlockGetter world, BlockPos pos) {
var tile = world.getBlockEntity(pos);
return type.isInstance(tile) ? (T) tile : null;
@ -122,10 +104,10 @@ public final class Utility {
return ItemStack.EMPTY;
}
public static ListTag serializeAll(HolderLookup.Provider provider, Collection<? extends INBTSerializable<CompoundTag>> items) {
public static ListTag serializeAll(Collection<? extends INBTSerializable<CompoundTag>> items) {
var list = new ListTag();
for (INBTSerializable<CompoundTag> item : items)
list.add(item.serializeNBT(provider));
list.add(item.serializeNBT());
return list;
}
@ -158,19 +140,8 @@ public final class Utility {
return new SidedInvWrapper(inventory, direction);
}
public static BlockPos readBlockPos(Tag tag) {
if (tag instanceof IntArrayTag i) {
int[] arr = i.getAsIntArray();
if (arr.length == 3)
return new BlockPos(arr[0], arr[1], arr[2]);
}
return null;
}
public interface IMergeItemStack {
boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean reverseDirection);
}
}

View file

@ -4,21 +4,25 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.packets.PacketCraftingModuleTransfer;
import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer;
import mezz.jei.api.constants.RecipeTypes;
import mezz.jei.api.constants.VanillaTypes;
import mezz.jei.api.gui.ingredient.IRecipeSlotsView;
import mezz.jei.api.recipe.RecipeIngredientRole;
import mezz.jei.api.recipe.RecipeType;
import mezz.jei.api.recipe.transfer.IRecipeTransferError;
import mezz.jei.api.recipe.transfer.IUniversalRecipeTransferHandler;
import mezz.jei.api.recipe.transfer.IRecipeTransferHandler;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingRecipe;
import net.minecraft.world.item.crafting.RecipeHolder;
import net.neoforged.neoforge.network.PacketDistributor;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Optional;
public class CraftingModuleTransferHandler implements IUniversalRecipeTransferHandler<CraftingModuleContainer> {
public class CraftingModuleTransferHandler implements IRecipeTransferHandler<CraftingModuleContainer, RecipeHolder<CraftingRecipe>> {
@Override
public Class<CraftingModuleContainer> getContainerClass() {
@ -31,16 +35,21 @@ public class CraftingModuleTransferHandler implements IUniversalRecipeTransferHa
}
@Override
public @Nullable IRecipeTransferError transferRecipe(CraftingModuleContainer container, Object recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) {
public RecipeType<RecipeHolder<CraftingRecipe>> getRecipeType() {
return RecipeTypes.CRAFTING;
}
@Override
public @Nullable IRecipeTransferError transferRecipe(CraftingModuleContainer container, RecipeHolder<CraftingRecipe> recipe, IRecipeSlotsView slots, Player player, boolean maxTransfer, boolean doTransfer) {
if (!doTransfer)
return null;
var inputs = new ArrayList<ItemStack>();
var outputs = new ArrayList<ItemStack>();
for (var entry : recipeSlots.getSlotViews()) {
for (var entry : slots.getSlotViews()) {
var allIngredients = entry.getIngredients(VanillaTypes.ITEM_STACK).toList();
if (allIngredients.isEmpty())
continue;
var remain = allIngredients.getFirst().copy();
var remain = allIngredients.get(0).copy();
var toAdd = entry.getRole() == RecipeIngredientRole.INPUT ? inputs : outputs;
for (var stack : toAdd) {
if (ItemEquality.compareItems(stack, remain)) {
@ -54,7 +63,7 @@ public class CraftingModuleTransferHandler implements IUniversalRecipeTransferHa
if (!remain.isEmpty())
toAdd.add(remain);
}
PacketDistributor.sendToServer(new PacketCraftingModuleTransfer(inputs, outputs));
PacketDistributor.SERVER.noArg().send(new PacketCraftingModuleTransfer(inputs, outputs));
return null;
}

View file

@ -46,8 +46,8 @@ public class CraftingTerminalTransferHandler implements IRecipeTransferHandler<C
List<PacketGhostSlot.Entry> stacks = new ArrayList<>();
var ingredients = slots.getSlotViews(RecipeIngredientRole.INPUT);
for (var entry : ingredients)
stacks.add(PacketGhostSlot.Entry.fromStacks(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList())));
PacketDistributor.sendToServer(new PacketGhostSlot(container.getTile().getBlockPos(), stacks));
stacks.add(new PacketGhostSlot.Entry(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList())));
PacketDistributor.SERVER.noArg().send(new PacketGhostSlot(container.getTile().getBlockPos(), stacks));
return null;
}

View file

@ -16,10 +16,10 @@ import net.minecraft.client.gui.components.Button;
import net.minecraft.client.renderer.Rect2i;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.client.event.ClientTickEvent;
import net.neoforged.neoforge.client.event.ScreenEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.TickEvent;
import net.neoforged.bus.api.SubscribeEvent;
import java.util.ArrayList;
import java.util.List;
@ -38,7 +38,7 @@ public class JEIPrettyPipesPlugin implements IModPlugin {
@Override
public ResourceLocation getPluginUid() {
return ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "jei_plugin");
return new ResourceLocation(PrettyPipes.ID, "jei_plugin");
}
@Override
@ -103,7 +103,7 @@ public class JEIPrettyPipesPlugin implements IModPlugin {
}
@SubscribeEvent
public void onClientTick(ClientTickEvent event) {
public void onClientTick(TickEvent.ClientTickEvent event) {
if (!PlayerPrefs.get().syncJei)
return;

View file

@ -5,7 +5,7 @@ import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.PipeBlock;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
@ -41,9 +41,9 @@ public class PipeFrameEntity extends ItemFrame implements IEntityWithComplexSpaw
}
@Override
protected void defineSynchedData(SynchedEntityData.Builder pBuilder) {
super.defineSynchedData(pBuilder);
pBuilder.define(PipeFrameEntity.AMOUNT, -1);
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(PipeFrameEntity.AMOUNT, -1);
}
@Override
@ -154,15 +154,14 @@ public class PipeFrameEntity extends ItemFrame implements IEntityWithComplexSpaw
}
@Override
public void writeSpawnData(RegistryFriendlyByteBuf buffer) {
public void writeSpawnData(FriendlyByteBuf buffer) {
buffer.writeBlockPos(this.pos);
buffer.writeInt(this.direction.ordinal());
}
@Override
public void readSpawnData(RegistryFriendlyByteBuf additionalData) {
public void readSpawnData(FriendlyByteBuf additionalData) {
this.pos = additionalData.readBlockPos();
this.direction = Direction.values()[additionalData.readInt()];
}
}

View file

@ -13,10 +13,12 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.items.IItemHandler;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
@ -26,16 +28,16 @@ public abstract class ModuleItem extends Item implements IModule {
private final String name;
public ModuleItem(String name, Item.Properties properties) {
super(properties.stacksTo(16));
public ModuleItem(String name) {
super(new Properties().stacksTo(16));
this.name = name;
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
super.appendHoverText(pStack, pContext, pTooltipComponents, pTooltipFlag);
Utility.addTooltip(this.name, pTooltipComponents);
public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
super.appendHoverText(stack, worldIn, tooltip, flagIn);
Utility.addTooltip(this.name, tooltip);
}
@Override
@ -107,5 +109,4 @@ public abstract class ModuleItem extends Item implements IModule {
public DirectionSelector getDirectionSelector(ItemStack module, PipeBlockEntity tile) {
return null;
}
}

View file

@ -5,7 +5,6 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.entities.PipeFrameEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionResult;
@ -15,9 +14,10 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import javax.annotation.Nullable;
import java.util.List;
public class PipeFrameItem extends Item {
@ -40,9 +40,10 @@ public class PipeFrameItem extends Item {
var world = context.getLevel();
HangingEntity hangingentity = new PipeFrameEntity(Registry.pipeFrameEntity, world, blockpos1, direction);
var customdata = itemstack.getOrDefault(DataComponents.ENTITY_DATA, CustomData.EMPTY);
if (!customdata.isEmpty())
EntityType.updateCustomEntityTag(world, playerentity, hangingentity, customdata);
var compoundTag = itemstack.getTag();
if (compoundTag != null) {
EntityType.updateCustomEntityTag(world, playerentity, hangingentity, compoundTag);
}
if (hangingentity.survives()) {
if (!world.isClientSide) {
@ -63,9 +64,8 @@ public class PipeFrameItem extends Item {
}
@Override
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
super.appendHoverText(pStack, pContext, pTooltipComponents, pTooltipFlag);
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), pTooltipComponents);
public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
super.appendHoverText(stack, worldIn, tooltip, flagIn);
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), tooltip);
}
}

View file

@ -4,7 +4,6 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.pipe.ConnectionType;
import de.ellpeck.prettypipes.pipe.PipeBlock;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
@ -18,6 +17,7 @@ import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
@ -107,8 +107,8 @@ public class WrenchItem extends Item {
}
@Override
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), pTooltipComponents);
public void appendHoverText(ItemStack stack, Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), tooltip);
}
@Override
@ -122,7 +122,7 @@ public class WrenchItem extends Item {
}
@Override
public boolean supportsEnchantment(ItemStack stack, Holder<Enchantment> enchantment) {
public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) {
return enchantment == Enchantments.SILK_TOUCH;
}

View file

@ -1,13 +1,11 @@
package de.ellpeck.prettypipes.misc;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.ItemStack;
import net.neoforged.api.distmarker.Dist;
@ -15,8 +13,6 @@ import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.client.gui.widget.ExtendedButton;
import org.apache.commons.lang3.ArrayUtils;
import java.util.List;
public class DirectionSelector {
private static final Direction[] ALL = ArrayUtils.addAll(Direction.values(), (Direction) null);
@ -37,7 +33,7 @@ public class DirectionSelector {
@OnlyIn(Dist.CLIENT)
public AbstractWidget getButton(int x, int y) {
return new ExtendedButton(x, y, 100, 20, Component.translatable("info." + PrettyPipes.ID + ".populate"), button ->
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.DIRECTION_SELECTOR, List.of())) {
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.DIRECTION_SELECTOR)) {
@Override
public Component getMessage() {
var pipe = DirectionSelector.this.pipe;
@ -68,13 +64,18 @@ public class DirectionSelector {
if (!this.modified)
return;
this.modified = false;
this.stack.set(Data.TYPE, new Data(this.direction.getName()));
var tag = new CompoundTag();
if (this.direction != null)
tag.putString("direction", this.direction.getName());
this.stack.getOrCreateTag().put("direction_selector", tag);
}
public void load() {
var data = this.stack.get(Data.TYPE);
if (data != null)
this.direction = Direction.byName(data.direction);
if (this.stack.hasTag()) {
var tag = this.stack.getTag().getCompound("direction_selector");
this.direction = Direction.byName(tag.getString("direction"));
}
}
public Direction[] directions() {
@ -91,9 +92,9 @@ public class DirectionSelector {
if (this.pipe.getItemHandler(dir) == null)
return false;
return this.pipe.streamModules()
.filter(p -> p.getLeft() != this.stack)
.map(p -> p.getRight().getDirectionSelector(p.getLeft(), this.pipe))
.noneMatch(p -> p != null && p.direction == dir);
.filter(p -> p.getLeft() != this.stack)
.map(p -> p.getRight().getDirectionSelector(p.getLeft(), this.pipe))
.noneMatch(p -> p != null && p.direction == dir);
}
public interface IDirectionContainer {
@ -101,14 +102,4 @@ public class DirectionSelector {
DirectionSelector getSelector();
}
public record Data(String direction) {
public static final Codec<DirectionSelector.Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Codec.STRING.fieldOf("direction").forGetter(f -> f.direction)
).apply(i, DirectionSelector.Data::new));
public static final DataComponentType<DirectionSelector.Data> TYPE = DataComponentType.<DirectionSelector.Data>builder().persistent(DirectionSelector.Data.CODEC).cacheEncoding().build();
}
}

View file

@ -15,7 +15,6 @@ public record EquatableItemStack(ItemStack stack, ItemEquality... equalityTypes)
@Override
public int hashCode() {
return Objects.hash(this.stack.getItem(), this.stack.getComponents());
return Objects.hash(this.stack.getItem(), this.stack.getTag());
}
}

View file

@ -5,7 +5,7 @@ import de.ellpeck.prettypipes.network.PipeNetwork;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.event.server.ServerStartingEvent;
import java.io.IOException;
@ -13,7 +13,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
@EventBusSubscriber
@Mod.EventBusSubscriber
public final class Events {
@SubscribeEvent

View file

@ -10,7 +10,7 @@ import java.util.function.Supplier;
public class ItemEquality {
public static final ItemEquality DAMAGE = new ItemEquality((stack, filter) -> stack.getDamageValue() == filter.getDamageValue(), false, Type.DAMAGE);
public static final ItemEquality NBT = new ItemEquality((stack, filter) -> Objects.equals(stack.getComponents(), filter.getComponents()), false, Type.NBT);
public static final ItemEquality NBT = new ItemEquality((stack, filter) -> Objects.equals(stack.getTag(), filter.getTag()) && stack.areAttachmentsCompatible(filter), false, Type.NBT);
public static final ItemEquality MOD = new ItemEquality((stack, filter) -> stack.getItem().getCreatorModId(stack).equals(filter.getItem().getCreatorModId(filter)), true, Type.MOD);
public final Type type;

View file

@ -1,9 +1,6 @@
package de.ellpeck.prettypipes.misc;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem;
@ -13,7 +10,7 @@ import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
@ -26,26 +23,18 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class ItemFilter {
public final ItemStackHandler content;
public boolean isWhitelist;
public boolean canPopulateFromInventories;
public boolean canModifyWhitelist = true;
public class ItemFilter extends ItemStackHandler {
private final ItemStack stack;
private final PipeBlockEntity pipe;
public boolean isWhitelist;
public boolean canPopulateFromInventories;
public boolean canModifyWhitelist = true;
private boolean modified;
public ItemFilter(int size, ItemStack stack, PipeBlockEntity pipe) {
this.content = new ItemStackHandler(size) {
@Override
protected void onContentsChanged(int slot) {
ItemFilter.this.modified = true;
}
};
super(size);
this.stack = stack;
this.pipe = pipe;
this.load();
@ -53,8 +42,8 @@ public class ItemFilter {
public List<Slot> getSlots(int x, int y) {
List<Slot> slots = new ArrayList<>();
for (var i = 0; i < this.content.getSlots(); i++)
slots.add(new FilterSlot(this.content, i, x + i % 9 * 18, y + i / 9 * 18, true));
for (var i = 0; i < this.getSlots(); i++)
slots.add(new FilterSlot(this, i, x + i % 9 * 18, y + i / 9 * 18, true));
return slots;
}
@ -64,12 +53,12 @@ public class ItemFilter {
if (this.canModifyWhitelist) {
var whitelistText = (Supplier<String>) () -> "info." + PrettyPipes.ID + "." + (this.isWhitelist ? "whitelist" : "blacklist");
buttons.add(Button.builder(Component.translatable(whitelistText.get()), button -> {
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, List.of(0));
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 0);
button.setMessage(Component.translatable(whitelistText.get()));
}).bounds(x - 20, y, 20, 20).tooltip(Tooltip.create(Component.translatable(whitelistText.get() + ".description").withStyle(ChatFormatting.GRAY))).build());
}
if (this.canPopulateFromInventories) {
buttons.add(Button.builder(Component.translatable("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, List.of(1))).bounds(x - 42, y, 20, 20).tooltip(Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY))).build());
buttons.add(Button.builder(Component.translatable("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 1)).bounds(x - 42, y, 20, 20).tooltip(Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY))).build());
}
return buttons;
}
@ -95,7 +84,7 @@ public class ItemFilter {
copy.setCount(1);
// try inserting into ourselves and any filter increase modifiers
for (var filter : filters) {
if (ItemHandlerHelper.insertItem(filter.content, copy, false).isEmpty()) {
if (ItemHandlerHelper.insertItem(filter, copy, false).isEmpty()) {
changed = true;
filter.save();
break;
@ -115,9 +104,9 @@ public class ItemFilter {
private boolean isFiltered(ItemStack stack, Direction direction) {
var types = ItemFilter.getEqualityTypes(this.pipe);
// also check if any filter increase modules have the item we need
for (ItemFilter handler : this.pipe.getFilters(direction)) {
for (var i = 0; i < handler.content.getSlots(); i++) {
var filter = handler.content.getStackInSlot(i);
for (ItemStackHandler handler : this.pipe.getFilters(direction)) {
for (var i = 0; i < handler.getSlots(); i++) {
var filter = handler.getStackInSlot(i);
if (filter.isEmpty())
continue;
if (ItemEquality.compareItems(stack, filter, types))
@ -129,27 +118,42 @@ public class ItemFilter {
public void save() {
if (this.modified) {
this.stack.set(Data.TYPE, new Data(this.content, this.isWhitelist));
this.stack.getOrCreateTag().put("filter", this.serializeNBT());
this.pipe.setChanged();
this.modified = false;
}
}
public void load() {
var content = this.stack.get(Data.TYPE);
if (content != null) {
this.content.setSize(content.items.getSlots());
for (var i = 0; i < this.content.getSlots(); i++)
this.content.setStackInSlot(i, content.items.getStackInSlot(i));
this.isWhitelist = content.whitelist;
}
if (this.stack.hasTag())
this.deserializeNBT(this.stack.getTag().getCompound("filter"));
}
@Override
public CompoundTag serializeNBT() {
var nbt = super.serializeNBT();
if (this.canModifyWhitelist)
nbt.putBoolean("whitelist", this.isWhitelist);
return nbt;
}
@Override
public void deserializeNBT(CompoundTag nbt) {
super.deserializeNBT(nbt);
if (this.canModifyWhitelist)
this.isWhitelist = nbt.getBoolean("whitelist");
}
@Override
protected void onContentsChanged(int slot) {
this.modified = true;
}
public static ItemEquality[] getEqualityTypes(PipeBlockEntity pipe) {
return pipe.streamModules()
.filter(m -> m.getRight() instanceof FilterModifierModuleItem)
.map(m -> ((FilterModifierModuleItem) m.getRight()).getEqualityType(m.getLeft()))
.toArray(ItemEquality[]::new);
.filter(m -> m.getRight() instanceof FilterModifierModuleItem)
.map(m -> ((FilterModifierModuleItem) m.getRight()).getEqualityType(m.getLeft()))
.toArray(ItemEquality[]::new);
}
public interface IFilteredContainer {
@ -161,14 +165,4 @@ public class ItemFilter {
}
public record Data(ItemStackHandler items, boolean whitelist) {
public static final Codec<Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("items").forGetter(f -> f.items),
Codec.BOOL.fieldOf("whitelist").forGetter(f -> f.whitelist)
).apply(i, Data::new));
public static final DataComponentType<Data> TYPE = DataComponentType.<Data>builder().persistent(Data.CODEC).cacheEncoding().build();
}
}

View file

@ -1,7 +1,9 @@
package de.ellpeck.prettypipes.misc;
import de.ellpeck.prettypipes.items.IModule;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.Level;
@ -15,10 +17,9 @@ public class ModuleClearingRecipe extends CustomRecipe {
}
@Override
public boolean matches(CraftingInput container, Level level) {
public boolean matches(CraftingContainer container, Level level) {
var foundModule = false;
for (var i = 0; i < container.size(); i++) {
var stack = container.getItem(i);
for (var stack : container.getItems()) {
if (!foundModule && stack.getItem() instanceof IModule) {
foundModule = true;
} else if (!stack.isEmpty()) {
@ -29,13 +30,11 @@ public class ModuleClearingRecipe extends CustomRecipe {
}
@Override
public ItemStack assemble(CraftingInput container, HolderLookup.Provider pRegistries) {
for (var i = 0; i < container.size(); i++) {
var stack = container.getItem(i);
if (stack.getItem() instanceof IModule)
return new ItemStack(stack.getItem());
}
return ItemStack.EMPTY;
public ItemStack assemble(CraftingContainer container, RegistryAccess access) {
var module = container.getItems().stream().filter(i -> i.getItem() instanceof IModule).findFirst().orElse(ItemStack.EMPTY);
if (!module.isEmpty())
module = new ItemStack(module.getItem());
return module;
}
@Override

View file

@ -50,5 +50,4 @@ public class PlayerPrefs {
var location = Minecraft.getInstance().gameDirectory;
return new File(location, PrettyPipes.ID + "prefs");
}
}

View file

@ -1,8 +1,6 @@
package de.ellpeck.prettypipes.network;
import de.ellpeck.prettypipes.Utility;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
@ -20,20 +18,20 @@ public class NetworkEdge extends DefaultWeightedEdge implements INBTSerializable
public NetworkEdge() {
}
public NetworkEdge(HolderLookup.Provider provider, CompoundTag nbt) {
this.deserializeNBT(provider, nbt);
public NetworkEdge(CompoundTag nbt) {
this.deserializeNBT(nbt);
}
public BlockPos getStartPipe() {
return this.pipes.getFirst();
return this.pipes.get(0);
}
public BlockPos getEndPipe() {
return this.pipes.getLast();
return this.pipes.get(this.pipes.size() - 1);
}
@Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) {
public CompoundTag serializeNBT() {
var nbt = new CompoundTag();
var list = new ListTag();
for (var pos : this.pipes)
@ -43,11 +41,10 @@ public class NetworkEdge extends DefaultWeightedEdge implements INBTSerializable
}
@Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) {
public void deserializeNBT(CompoundTag nbt) {
this.pipes.clear();
var list = nbt.getList("pipes", Tag.TAG_COMPOUND);
for (var tag : list)
this.pipes.add(Utility.readBlockPos(tag));
for (var i = 0; i < list.size(); i++)
this.pipes.add(NbtUtils.readBlockPos(list.getCompound(i)));
}
}

View file

@ -3,7 +3,6 @@ package de.ellpeck.prettypipes.network;
import de.ellpeck.prettypipes.misc.ItemEquality;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.world.item.ItemStack;
@ -29,8 +28,8 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
this.direction = direction;
}
public NetworkLocation(HolderLookup.Provider provider, CompoundTag nbt) {
this.deserializeNBT(provider, nbt);
public NetworkLocation(CompoundTag nbt) {
this.deserializeNBT(nbt);
}
public List<Integer> getStackSlots(Level world, ItemStack stack, ItemEquality... equalityTypes) {
@ -92,7 +91,7 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
}
@Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) {
public CompoundTag serializeNBT() {
var nbt = new CompoundTag();
nbt.put("pipe_pos", NbtUtils.writeBlockPos(this.pipePos));
nbt.putInt("direction", this.direction.ordinal());
@ -100,9 +99,8 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
}
@Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) {
this.pipePos = NbtUtils.readBlockPos(nbt, "pipe_pos").orElse(null);
public void deserializeNBT(CompoundTag nbt) {
this.pipePos = NbtUtils.readBlockPos(nbt.getCompound("pipe_pos"));
this.direction = Direction.values()[nbt.getInt("direction")];
}
}

View file

@ -1,6 +1,5 @@
package de.ellpeck.prettypipes.network;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.common.util.INBTSerializable;
@ -21,24 +20,24 @@ public class NetworkLock implements INBTSerializable<CompoundTag> {
this.stack = stack;
}
public NetworkLock(HolderLookup.Provider provider, CompoundTag nbt) {
this.deserializeNBT(provider, nbt);
public NetworkLock(CompoundTag nbt) {
this.deserializeNBT(nbt);
}
@Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) {
public CompoundTag serializeNBT() {
var nbt = new CompoundTag();
nbt.putUUID("id", this.lockId);
nbt.put("location", this.location.serializeNBT(provider));
nbt.put("stack", this.stack.save(provider));
nbt.put("location", this.location.serializeNBT());
nbt.put("stack", this.stack.save(new CompoundTag()));
return nbt;
}
@Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) {
public void deserializeNBT(CompoundTag nbt) {
this.lockId = nbt.getUUID("id");
this.location = new NetworkLocation(provider, nbt.getCompound("location"));
this.stack = ItemStack.parseOptional(provider, nbt.getCompound("stack"));
this.location = new NetworkLocation(nbt.getCompound("location"));
this.stack = ItemStack.of(nbt.getCompound("stack"));
}
@Override
@ -57,5 +56,4 @@ public class NetworkLock implements INBTSerializable<CompoundTag> {
public String toString() {
return "NetworkLock{" + "location=" + this.location.pipePos + ", stack=" + this.stack + '}';
}
}

View file

@ -8,7 +8,6 @@ import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
@ -34,7 +33,7 @@ import java.util.function.Consumer;
public class PipeItem implements IPipeItem {
public static final ResourceLocation TYPE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_item");
public static final ResourceLocation TYPE = new ResourceLocation(PrettyPipes.ID, "pipe_item");
public ItemStack stack;
public float speed;
@ -64,10 +63,10 @@ public class PipeItem implements IPipeItem {
this(PipeItem.TYPE, stack, speed);
}
public PipeItem(HolderLookup.Provider provider, ResourceLocation type, CompoundTag nbt) {
public PipeItem(ResourceLocation type, CompoundTag nbt) {
this.type = type;
this.path = new ArrayList<>();
this.deserializeNBT(provider, nbt);
this.deserializeNBT(nbt);
}
@Override
@ -222,12 +221,12 @@ public class PipeItem implements IPipeItem {
}
protected BlockPos getStartPipe() {
return this.path.getFirst();
return this.path.get(0);
}
@Override
public BlockPos getDestPipe() {
return this.path.getLast();
return this.path.get(this.path.size() - 1);
}
@Override
@ -241,10 +240,10 @@ public class PipeItem implements IPipeItem {
}
@Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) {
public CompoundTag serializeNBT() {
var nbt = new CompoundTag();
nbt.putString("type", this.type.toString());
nbt.put("stack", this.stack.save(provider));
nbt.put("stack", this.stack.save(new CompoundTag()));
nbt.putFloat("speed", this.speed);
nbt.put("start_inv", NbtUtils.writeBlockPos(this.startInventory));
nbt.put("dest_inv", NbtUtils.writeBlockPos(this.destInventory));
@ -262,12 +261,12 @@ public class PipeItem implements IPipeItem {
}
@Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) {
this.stack = ItemStack.parseOptional(provider, nbt.getCompound("stack"));
public void deserializeNBT(CompoundTag nbt) {
this.stack = ItemStack.of(nbt.getCompound("stack"));
this.speed = nbt.getFloat("speed");
this.startInventory = NbtUtils.readBlockPos(nbt, "start_inv").orElse(null);
this.destInventory = NbtUtils.readBlockPos(nbt, "dest_inv").orElse(null);
this.currGoalPos = NbtUtils.readBlockPos(nbt, "curr_goal").orElse(null);
this.startInventory = NbtUtils.readBlockPos(nbt.getCompound("start_inv"));
this.destInventory = NbtUtils.readBlockPos(nbt.getCompound("dest_inv"));
this.currGoalPos = NbtUtils.readBlockPos(nbt.getCompound("curr_goal"));
this.retryOnObstruction = nbt.getBoolean("drop_on_obstruction");
this.currentTile = nbt.getInt("tile");
this.x = nbt.getFloat("x");
@ -275,8 +274,8 @@ public class PipeItem implements IPipeItem {
this.z = nbt.getFloat("z");
this.path.clear();
var list = nbt.getList("path", Tag.TAG_COMPOUND);
for (var tag : list)
this.path.add(Utility.readBlockPos(tag));
for (var i = 0; i < list.size(); i++)
this.path.add(NbtUtils.readBlockPos(list.getCompound(i)));
}
@Override
@ -288,9 +287,9 @@ public class PipeItem implements IPipeItem {
@OnlyIn(Dist.CLIENT)
public void render(PipeBlockEntity tile, PoseStack matrixStack, Random random, float partialTicks, int light, int overlay, MultiBufferSource source) {
matrixStack.translate(
Mth.lerp(partialTicks, this.lastX, this.x),
Mth.lerp(partialTicks, this.lastY, this.y),
Mth.lerp(partialTicks, this.lastZ, this.z));
Mth.lerp(partialTicks, this.lastX, this.x),
Mth.lerp(partialTicks, this.lastY, this.y),
Mth.lerp(partialTicks, this.lastZ, this.z));
if (this.stack.getItem() instanceof BlockItem) {
var scale = 0.7F;
@ -309,9 +308,9 @@ public class PipeItem implements IPipeItem {
matrixStack.pushPose();
if (amount > 1) {
matrixStack.translate(
(random.nextFloat() * 2.0F - 1.0F) * 0.25F * 0.5F,
(random.nextFloat() * 2.0F - 1.0F) * 0.25F * 0.5F,
(random.nextFloat() * 2.0F - 1.0F) * 0.25F * 0.5F);
(random.nextFloat() * 2.0F - 1.0F) * 0.25F * 0.5F,
(random.nextFloat() * 2.0F - 1.0F) * 0.25F * 0.5F,
(random.nextFloat() * 2.0F - 1.0F) * 0.25F * 0.5F);
}
Minecraft.getInstance().getItemRenderer().renderStatic(this.stack, ItemDisplayContext.GROUND, light, overlay, matrixStack, source, tile.getLevel(), 0);
matrixStack.popPose();
@ -345,7 +344,7 @@ public class PipeItem implements IPipeItem {
// add the single pipe twice if there's only one
// this is a dirty hack, but it works fine so eh
for (var i = 0; i < 2; i++)
ret.add(nodes.getFirst());
ret.add(nodes.get(0));
return ret;
}
for (var i = 0; i < nodes.size() - 1; i++) {
@ -369,5 +368,4 @@ public class PipeItem implements IPipeItem {
}
return ret;
}
}

View file

@ -12,14 +12,12 @@ import de.ellpeck.prettypipes.pipe.PipeBlock;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.saveddata.SavedData;
@ -62,17 +60,17 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
this.dijkstra = new DijkstraShortestPath<>(this.graph);
}
public PipeNetwork(CompoundTag nbt, HolderLookup.Provider provider) {
public PipeNetwork(CompoundTag nbt) {
this();
var nodes = nbt.getList("nodes", Tag.TAG_COMPOUND);
for (var node : nodes)
this.graph.addVertex(Utility.readBlockPos(node));
for (var i = 0; i < nodes.size(); i++)
this.graph.addVertex(NbtUtils.readBlockPos(nodes.getCompound(i)));
var edges = nbt.getList("edges", Tag.TAG_COMPOUND);
for (var i = 0; i < edges.size(); i++)
this.addEdge(new NetworkEdge(provider, edges.getCompound(i)));
for (var item : Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), i -> IPipeItem.load(provider, i)))
this.addEdge(new NetworkEdge(edges.getCompound(i)));
for (var item : Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load))
this.pipeItems.put(item.getCurrentPipe(), item);
for (var lock : Utility.deserializeAll(nbt.getList("locks", Tag.TAG_COMPOUND), t -> new NetworkLock(provider, t)))
for (var lock : Utility.deserializeAll(nbt.getList("locks", Tag.TAG_COMPOUND), NetworkLock::new))
this.createNetworkLock(lock);
}
@ -102,25 +100,25 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
@Override
public String toString() {
return "PipeNetwork{" +
"\ngraph=" + this.graph +
",\nnodeToConnectedNodes=" + this.nodeToConnectedNodes +
",\ntileCache=" + this.tileCache.keySet() +
",\npipeItems=" + this.pipeItems +
",\nnetworkLocks=" + this.networkLocks + '}';
"\ngraph=" + this.graph +
",\nnodeToConnectedNodes=" + this.nodeToConnectedNodes +
",\ntileCache=" + this.tileCache.keySet() +
",\npipeItems=" + this.pipeItems +
",\nnetworkLocks=" + this.networkLocks + '}';
}
@Override
public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) {
public CompoundTag save(CompoundTag nbt) {
var nodes = new ListTag();
for (var node : this.graph.vertexSet())
nodes.add(NbtUtils.writeBlockPos(node));
nbt.put("nodes", nodes);
var edges = new ListTag();
for (var edge : this.graph.edgeSet())
edges.add(edge.serializeNBT(provider));
edges.add(edge.serializeNBT());
nbt.put("edges", edges);
nbt.put("items", Utility.serializeAll(provider, this.pipeItems.values()));
nbt.put("locks", Utility.serializeAll(provider, this.networkLocks.values()));
nbt.put("items", Utility.serializeAll(this.pipeItems.values()));
nbt.put("locks", Utility.serializeAll(this.networkLocks.values()));
return nbt;
}
@ -201,7 +199,7 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
var item = itemSupplier.apply(startPipe.getItemSpeed(stack));
item.setDestination(startInventory, destInventory, path);
startPipe.addNewItem(item);
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(startPipePos), new PacketItemEnterPipe(startPipePos, item.serializeNBT(this.level.registryAccess())));
PacketDistributor.TRACKING_CHUNK.with(this.level.getChunkAt(startPipePos)).send(new PacketItemEnterPipe(startPipePos, item));
return true;
}
@ -289,8 +287,8 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
var stack = request.getRight();
// add up all the items that should go to the same location
var existing = items.stream()
.filter(s -> s.getLeft().equals(dest) && ItemEquality.compareItems(s.getRight(), stack, equalityTypes))
.findFirst();
.filter(s -> s.getLeft().equals(dest) && ItemEquality.compareItems(s.getRight(), stack, equalityTypes))
.findFirst();
if (existing.isPresent()) {
existing.get().getRight().grow(stack.getCount());
} else {
@ -304,8 +302,8 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
public int getCurrentlyCraftingAmount(BlockPos destNode, ItemStack stack, ItemEquality... equalityTypes) {
return this.getCurrentlyCrafting(destNode).stream()
.filter(p -> p.getLeft().equals(destNode) && ItemEquality.compareItems(p.getRight(), stack, equalityTypes))
.mapToInt(p -> p.getRight().getCount()).sum();
.filter(p -> p.getLeft().equals(destNode) && ItemEquality.compareItems(p.getRight(), stack, equalityTypes))
.mapToInt(p -> p.getRight().getCount()).sum();
}
public List<Pair<BlockPos, ItemStack>> getAllCraftables(BlockPos node) {
@ -377,8 +375,8 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
public int getLockedAmount(BlockPos pos, ItemStack stack, NetworkLock ignoredLock, ItemEquality... equalityTypes) {
return this.getNetworkLocks(pos).stream()
.filter(l -> !l.equals(ignoredLock) && ItemEquality.compareItems(l.stack, stack, equalityTypes))
.mapToInt(l -> l.stack.getCount()).sum();
.filter(l -> !l.equals(ignoredLock) && ItemEquality.compareItems(l.stack, stack, equalityTypes))
.mapToInt(l -> l.stack.getCount()).sum();
}
private void refreshNode(BlockPos pos, BlockState state) {
@ -483,9 +481,9 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
// sort destinations first by their priority (eg trash pipes should be last)
// and then by their distance from the specified node
ret = Streams.stream(new BreadthFirstIterator<>(this.graph, node))
.filter(p -> this.getPipe(p) != null)
.sorted(Comparator.<BlockPos>comparingInt(p -> this.getPipe(p).getPriority()).reversed().thenComparing(paths::getWeight))
.collect(Collectors.toList());
.filter(p -> this.getPipe(p) != null)
.sorted(Comparator.<BlockPos>comparingInt(p -> this.getPipe(p).getPriority()).reversed().thenComparing(paths::getWeight))
.collect(Collectors.toList());
this.nodeToConnectedNodes.put(node, ret);
this.endProfile();
}
@ -515,8 +513,8 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
public int getItemsOnTheWay(BlockPos goalInv, ItemStack type, ItemEquality... equalityTypes) {
return this.getPipeItemsOnTheWay(goalInv)
.filter(i -> type == null || ItemEquality.compareItems(i.getContent(), type, equalityTypes))
.mapToInt(i -> i.getItemsOnTheWay(goalInv)).sum();
.filter(i -> type == null || ItemEquality.compareItems(i.getContent(), type, equalityTypes))
.mapToInt(i -> i.getItemsOnTheWay(goalInv)).sum();
}
public void startProfile(String name) {

View file

@ -13,10 +13,8 @@ import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.MenuProvider;
@ -24,50 +22,64 @@ import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.neoforged.neoforge.network.PacketDistributor;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import org.apache.logging.log4j.util.TriConsumer;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import static de.ellpeck.prettypipes.misc.DirectionSelector.IDirectionContainer;
public record PacketButton(BlockPos pos, int result, List<Integer> data) implements CustomPacketPayload {
public class PacketButton implements CustomPacketPayload {
public static final Type<PacketButton> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "button"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketButton> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketButton::pos,
ByteBufCodecs.INT, PacketButton::result,
ByteBufCodecs.collection(ArrayList::new, ByteBufCodecs.INT), PacketButton::data,
PacketButton::new);
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "button");
public PacketButton(BlockPos pos, ButtonResult result, List<Integer> data) {
this(pos, result.ordinal(), data);
private final BlockPos pos;
private final ButtonResult result;
private final int[] data;
public PacketButton(BlockPos pos, ButtonResult result, int... data) {
this.pos = pos;
this.result = result;
this.data = data;
}
public PacketButton(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.result = ButtonResult.values()[buf.readByte()];
this.data = buf.readVarIntArray();
}
@Override
public Type<? extends CustomPacketPayload> type() {
return PacketButton.TYPE;
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeByte(this.result.ordinal());
buf.writeVarIntArray(this.data);
}
public static void onMessage(PacketButton message, IPayloadContext ctx) {
var player = ctx.player();
ButtonResult.values()[message.result].action.accept(message.pos, message.data, player);
@Override
public ResourceLocation id() {
return PacketButton.ID;
}
public static void sendAndExecute(BlockPos pos, ButtonResult result, List<Integer> data) {
PacketDistributor.sendToServer(new PacketButton(pos, result, data));
public static void onMessage(PacketButton message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
message.result.action.accept(message.pos, message.data, player);
});
}
public static void sendAndExecute(BlockPos pos, ButtonResult result, int... data) {
PacketDistributor.SERVER.noArg().send(new PacketButton(pos, result, data));
result.action.accept(pos, data, Minecraft.getInstance().player);
}
public enum ButtonResult {
PIPE_TAB((pos, data, player) -> {
var tile = Utility.getBlockEntity(PipeBlockEntity.class, player.level(), pos);
if (data.getFirst() < 0) {
if (data[0] < 0) {
player.openMenu(tile, pos);
} else {
var stack = tile.modules.getStackInSlot(data.getFirst());
var stack = tile.modules.getStackInSlot(data[0]);
player.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
@ -77,32 +89,30 @@ public record PacketButton(BlockPos pos, int result, List<Integer> data) impleme
@Nullable
@Override
public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) {
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data.getFirst());
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data[0]);
}
}, buf -> {
buf.writeBlockPos(pos);
buf.writeInt(data.getFirst());
buf.writeInt(data[0]);
});
}
}),
FILTER_CHANGE((pos, data, player) -> {
if (player.containerMenu instanceof IFilteredContainer filtered)
filtered.getFilter().onButtonPacket(filtered, data.getFirst());
filtered.getFilter().onButtonPacket(filtered, data[0]);
}),
STACK_SIZE_MODULE_BUTTON((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu;
var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT);
container.moduleStack.set(StackSizeModuleItem.Data.TYPE, new StackSizeModuleItem.Data(moduleData.maxStackSize(), !moduleData.limitToMaxStackSize()));
StackSizeModuleItem.setLimitToMaxStackSize(container.moduleStack, !StackSizeModuleItem.getLimitToMaxStackSize(container.moduleStack));
}),
STACK_SIZE_AMOUNT((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu;
var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT);
container.moduleStack.set(StackSizeModuleItem.Data.TYPE, new StackSizeModuleItem.Data(data.getFirst(), moduleData.limitToMaxStackSize()));
StackSizeModuleItem.setMaxStackSize(container.moduleStack, data[0]);
}),
CRAFT_TERMINAL_REQUEST((pos, data, player) -> {
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), pos);
tile.requestCraftingItems(player, data.getFirst(), data.get(1) > 0);
tile.requestCraftingItems(player, data[0], data[1] > 0);
}),
CANCEL_CRAFTING((pos, data, player) -> {
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), pos);
@ -110,16 +120,16 @@ public record PacketButton(BlockPos pos, int result, List<Integer> data) impleme
}),
TAG_FILTER((pos, data, player) -> {
var container = (FilterModifierModuleContainer) player.containerMenu;
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data.getFirst()));
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data[0]));
}),
DIRECTION_SELECTOR((pos, data, player) -> {
if (player.containerMenu instanceof IDirectionContainer filtered)
filtered.getSelector().onButtonPacket();
});
public final TriConsumer<BlockPos, List<Integer>, Player> action;
public final TriConsumer<BlockPos, int[], Player> action;
ButtonResult(TriConsumer<BlockPos, List<Integer>, Player> action) {
ButtonResult(TriConsumer<BlockPos, int[], Player> action) {
this.action = action;
}
}

View file

@ -2,40 +2,63 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import java.util.ArrayList;
import java.util.List;
public record PacketCraftingModuleTransfer(List<ItemStack> inputs, List<ItemStack> outputs) implements CustomPacketPayload {
public class PacketCraftingModuleTransfer implements CustomPacketPayload {
public static final Type<PacketCraftingModuleTransfer> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_module_transfer"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketCraftingModuleTransfer> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketCraftingModuleTransfer::inputs,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketCraftingModuleTransfer::outputs,
PacketCraftingModuleTransfer::new);
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "crafting_module_transfer");
@Override
public Type<? extends CustomPacketPayload> type() {
return PacketCraftingModuleTransfer.TYPE;
private final List<ItemStack> inputs;
private final List<ItemStack> outputs;
public PacketCraftingModuleTransfer(List<ItemStack> inputs, List<ItemStack> outputs) {
this.inputs = inputs;
this.outputs = outputs;
}
public static void onMessage(PacketCraftingModuleTransfer message, IPayloadContext ctx) {
var player = ctx.player();
if (player.containerMenu instanceof CraftingModuleContainer container) {
PacketCraftingModuleTransfer.copy(container.input, message.inputs);
PacketCraftingModuleTransfer.copy(container.output, message.outputs);
container.modified = true;
container.broadcastChanges();
}
public PacketCraftingModuleTransfer(FriendlyByteBuf buf) {
this.inputs = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.inputs.add(buf.readItem());
this.outputs = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.outputs.add(buf.readItem());
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeInt(this.inputs.size());
for (var stack : this.inputs)
buf.writeItem(stack);
buf.writeInt(this.outputs.size());
for (var stack : this.outputs)
buf.writeItem(stack);
}
@Override
public ResourceLocation id() {
return PacketCraftingModuleTransfer.ID;
}
public static void onMessage(PacketCraftingModuleTransfer message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
if (player.containerMenu instanceof CraftingModuleContainer container) {
PacketCraftingModuleTransfer.copy(container.input, message.inputs);
PacketCraftingModuleTransfer.copy(container.output, message.outputs);
container.modified = true;
container.broadcastChanges();
}
});
}
private static void copy(ItemStackHandler container, List<ItemStack> contents) {

View file

@ -7,9 +7,7 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
@ -17,45 +15,78 @@ import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public record PacketGhostSlot(BlockPos pos, List<Entry> stacks) implements CustomPacketPayload {
public class PacketGhostSlot implements CustomPacketPayload {
public static final Type<PacketGhostSlot> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "ghost_slot"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketGhostSlot> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketGhostSlot::pos,
ByteBufCodecs.collection(ArrayList::new, Entry.CODEC), PacketGhostSlot::stacks,
PacketGhostSlot::new);
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "ghost_slot");
private final BlockPos pos;
private final List<Entry> stacks;
public PacketGhostSlot(BlockPos pos, List<Entry> stacks) {
this.pos = pos;
this.stacks = stacks;
}
public PacketGhostSlot(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.stacks = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.stacks.add(new Entry(buf));
}
@Override
public Type<? extends CustomPacketPayload> type() {
return PacketGhostSlot.TYPE;
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeInt(this.stacks.size());
for (var entry : this.stacks)
entry.write(buf);
}
public static void onMessage(PacketGhostSlot message, IPayloadContext ctx) {
var player = ctx.player();
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), message.pos);
if (tile != null)
tile.setGhostItems(message.stacks);
@Override
public ResourceLocation id() {
return PacketGhostSlot.ID;
}
public record Entry(List<ItemStack> stacks, TagKey<Item> tag) {
public static void onMessage(PacketGhostSlot message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), message.pos);
if (tile != null)
tile.setGhostItems(message.stacks);
});
}
public static final StreamCodec<RegistryFriendlyByteBuf, Entry> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), Entry::stacks,
ByteBufCodecs.fromCodec(TagKey.codec(Registries.ITEM)), Entry::tag,
Entry::new);
public static class Entry {
public static Entry fromStacks(Level level, List<ItemStack> stacks) {
private final List<ItemStack> stacks;
private final TagKey<Item> tag;
public Entry(Level level, List<ItemStack> stacks) {
var tag = Entry.getTagForStacks(level, stacks);
if (tag != null) {
return new Entry(null, tag);
this.stacks = null;
this.tag = tag;
} else {
return new Entry(stacks, null);
this.stacks = stacks;
this.tag = null;
}
}
public Entry(FriendlyByteBuf buf) {
if (buf.readBoolean()) {
this.tag = null;
this.stacks = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.stacks.add(buf.readItem());
} else {
this.stacks = null;
this.tag = TagKey.create(Registries.ITEM, new ResourceLocation(buf.readUtf()));
}
}
@ -63,8 +94,20 @@ public record PacketGhostSlot(BlockPos pos, List<Entry> stacks) implements Custo
if (this.stacks != null)
return this.stacks;
return Streams.stream(level.registryAccess().registry(Registries.ITEM).orElseThrow().getTagOrEmpty(this.tag).iterator())
.filter(h -> h.value() != null & h.value() != Items.AIR)
.map(h -> new ItemStack(h.value())).collect(Collectors.toList());
.filter(h -> h.value() != null & h.value() != Items.AIR)
.map(h -> new ItemStack(h.value())).collect(Collectors.toList());
}
public void write(FriendlyByteBuf buf) {
if (this.stacks != null) {
buf.writeBoolean(true);
buf.writeInt(this.stacks.size());
for (var stack : this.stacks)
buf.writeItem(stack);
} else {
buf.writeBoolean(false);
buf.writeUtf(this.tag.location().toString());
}
}
private static TagKey<Item> getTagForStacks(Level level, List<ItemStack> stacks) {

View file

@ -7,34 +7,49 @@ import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
public record PacketItemEnterPipe(BlockPos tilePos, CompoundTag item) implements CustomPacketPayload {
public class PacketItemEnterPipe implements CustomPacketPayload {
public static final Type<PacketItemEnterPipe> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_enter_pipe"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketItemEnterPipe> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketItemEnterPipe::tilePos,
ByteBufCodecs.COMPOUND_TAG, PacketItemEnterPipe::item,
PacketItemEnterPipe::new);
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "item_enter_pipe");
@Override
public Type<? extends CustomPacketPayload> type() {
return PacketItemEnterPipe.TYPE;
private final BlockPos tilePos;
private final CompoundTag item;
public PacketItemEnterPipe(BlockPos tilePos, IPipeItem item) {
this.tilePos = tilePos;
this.item = item.serializeNBT();
}
public static void onMessage(PacketItemEnterPipe message, IPayloadContext ctx) {
var mc = Minecraft.getInstance();
if (mc.level == null)
return;
var item = IPipeItem.load(mc.level.registryAccess(), message.item);
var pipe = Utility.getBlockEntity(PipeBlockEntity.class, mc.level, message.tilePos);
if (pipe != null)
pipe.getItems().add(item);
public PacketItemEnterPipe(FriendlyByteBuf buf) {
this.tilePos = buf.readBlockPos();
this.item = buf.readNbt();
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.tilePos);
buf.writeNbt(this.item);
}
@Override
public ResourceLocation id() {
return PacketItemEnterPipe.ID;
}
public static void onMessage(PacketItemEnterPipe message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var mc = Minecraft.getInstance();
if (mc.level == null)
return;
var item = IPipeItem.load(message.item);
var pipe = Utility.getBlockEntity(PipeBlockEntity.class, mc.level, message.tilePos);
if (pipe != null)
pipe.getItems().add(item);
});
}
}

View file

@ -3,35 +3,76 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.client.Minecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import java.util.ArrayList;
import java.util.List;
public record PacketNetworkItems(List<ItemStack> items, List<ItemStack> craftables, List<ItemStack> currentlyCrafting) implements CustomPacketPayload {
public class PacketNetworkItems implements CustomPacketPayload {
public static final Type<PacketNetworkItems> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "network_items"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketNetworkItems> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::items,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::craftables,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::currentlyCrafting,
PacketNetworkItems::new);
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "network_items");
@Override
public Type<? extends CustomPacketPayload> type() {
return PacketNetworkItems.TYPE;
private final List<ItemStack> items;
private final List<ItemStack> craftables;
private final List<ItemStack> currentlyCrafting;
public PacketNetworkItems(List<ItemStack> items, List<ItemStack> craftables, List<ItemStack> currentlyCrafting) {
this.items = items;
this.craftables = craftables;
this.currentlyCrafting = currentlyCrafting;
}
public static void onMessage(PacketNetworkItems message, IPayloadContext ctx) {
var mc = Minecraft.getInstance();
if (mc.screen instanceof ItemTerminalGui terminal)
terminal.updateItemList(message.items, message.craftables, message.currentlyCrafting);
public PacketNetworkItems(FriendlyByteBuf buf) {
this.items = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--) {
var stack = buf.readItem();
stack.setCount(buf.readVarInt());
this.items.add(stack);
}
this.craftables = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--)
this.craftables.add(buf.readItem());
this.currentlyCrafting = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--)
this.currentlyCrafting.add(buf.readItem());
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeVarInt(this.items.size());
for (var stack : this.items) {
var copy = stack.copy();
copy.setCount(1);
buf.writeItem(copy);
buf.writeVarInt(stack.getCount());
}
buf.writeVarInt(this.craftables.size());
for (var stack : this.craftables)
buf.writeItem(stack);
buf.writeVarInt(this.currentlyCrafting.size());
for (var stack : this.currentlyCrafting)
buf.writeItem(stack);
}
@Override
public ResourceLocation id() {
return PacketNetworkItems.ID;
}
@SuppressWarnings("Convert2Lambda")
public static void onMessage(PacketNetworkItems message, PlayPayloadContext ctx) {
ctx.workHandler().execute(new Runnable() {
@Override
public void run() {
var mc = Minecraft.getInstance();
if (mc.screen instanceof ItemTerminalGui terminal)
terminal.updateItemList(message.items, message.craftables, message.currentlyCrafting);
}
});
}
}

View file

@ -4,39 +4,59 @@ import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
public record PacketRequest(BlockPos pos, ItemStack stack, int componentsHash, int amount) implements CustomPacketPayload {
public class PacketRequest implements CustomPacketPayload {
public static final Type<PacketRequest> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "request"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketRequest> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketRequest::pos,
ItemStack.STREAM_CODEC, PacketRequest::stack,
ByteBufCodecs.INT, PacketRequest::componentsHash,
ByteBufCodecs.INT, PacketRequest::amount,
PacketRequest::new);
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "request");
private final BlockPos pos;
private final ItemStack stack;
private final int nbtHash;
private final int amount;
public PacketRequest(BlockPos pos, ItemStack stack, int amount) {
this(pos, stack, !stack.isComponentsPatchEmpty() ? stack.getComponents().hashCode() : 0, amount);
this.pos = pos;
this.stack = stack;
this.nbtHash = stack.hasTag() ? stack.getTag().hashCode() : 0;
this.amount = amount;
}
public PacketRequest(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.stack = buf.readItem();
this.nbtHash = buf.readVarInt();
this.amount = buf.readVarInt();
}
@Override
public Type<? extends CustomPacketPayload> type() {
return PacketRequest.TYPE;
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeItem(this.stack);
buf.writeVarInt(this.nbtHash);
buf.writeVarInt(this.amount);
}
public static void onMessage(PacketRequest message, IPayloadContext ctx) {
var player = ctx.player();
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), message.pos);
message.stack.setCount(message.amount);
tile.requestItem(player, message.stack, message.componentsHash);
@Override
public ResourceLocation id() {
return PacketRequest.ID;
}
@SuppressWarnings("Convert2Lambda")
public static void onMessage(PacketRequest message, PlayPayloadContext ctx) {
ctx.workHandler().execute(new Runnable() {
@Override
public void run() {
var player = ctx.player().orElseThrow();
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), message.pos);
message.stack.setCount(message.amount);
tile.requestItem(player, message.stack, message.nbtHash);
}
});
}
}

View file

@ -5,7 +5,6 @@ import de.ellpeck.prettypipes.network.NetworkEdge;
import de.ellpeck.prettypipes.network.PipeItem;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
@ -13,18 +12,18 @@ import net.minecraft.world.level.Level;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.common.util.INBTSerializable;
import org.apache.commons.lang3.function.TriFunction;
import org.jgrapht.GraphPath;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.BiFunction;
public interface IPipeItem extends INBTSerializable<CompoundTag> {
Map<ResourceLocation, TriFunction<HolderLookup.Provider, ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>(
Collections.singletonMap(PipeItem.TYPE, PipeItem::new));
Map<ResourceLocation, BiFunction<ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>(
Collections.singletonMap(PipeItem.TYPE, PipeItem::new));
ItemStack getContent();
@ -45,10 +44,9 @@ public interface IPipeItem extends INBTSerializable<CompoundTag> {
@OnlyIn(Dist.CLIENT)
void render(PipeBlockEntity tile, PoseStack matrixStack, Random random, float partialTicks, int light, int overlay, MultiBufferSource source);
static IPipeItem load(HolderLookup.Provider provider, CompoundTag nbt) {
var type = ResourceLocation.parse(nbt.getString("type"));
static IPipeItem load(CompoundTag nbt) {
var type = new ResourceLocation(nbt.getString("type"));
var func = IPipeItem.TYPES.get(type);
return func != null ? func.apply(provider, type, nbt) : null;
return func != null ? func.apply(type, nbt) : null;
}
}

View file

@ -10,7 +10,7 @@ import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.tags.FluidTags;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
@ -54,13 +54,13 @@ public class PipeBlock extends BaseEntityBlock implements SimpleWaterloggedBlock
private static final Map<Pair<BlockState, BlockState>, VoxelShape> COLL_SHAPE_CACHE = new HashMap<>();
private static final VoxelShape CENTER_SHAPE = Block.box(5, 5, 5, 11, 11, 11);
public static final Map<Direction, VoxelShape> DIR_SHAPES = ImmutableMap.<Direction, VoxelShape>builder()
.put(Direction.UP, Block.box(5, 10, 5, 11, 16, 11))
.put(Direction.DOWN, Block.box(5, 0, 5, 11, 6, 11))
.put(Direction.NORTH, Block.box(5, 5, 0, 11, 11, 6))
.put(Direction.SOUTH, Block.box(5, 5, 10, 11, 11, 16))
.put(Direction.EAST, Block.box(10, 5, 5, 16, 11, 11))
.put(Direction.WEST, Block.box(0, 5, 5, 6, 11, 11))
.build();
.put(Direction.UP, Block.box(5, 10, 5, 11, 16, 11))
.put(Direction.DOWN, Block.box(5, 0, 5, 11, 6, 11))
.put(Direction.NORTH, Block.box(5, 5, 0, 11, 11, 6))
.put(Direction.SOUTH, Block.box(5, 5, 10, 11, 11, 16))
.put(Direction.EAST, Block.box(10, 5, 5, 16, 11, 11))
.put(Direction.WEST, Block.box(0, 5, 5, 6, 11, 11))
.build();
static {
for (var dir : Direction.values())
@ -77,12 +77,12 @@ public class PipeBlock extends BaseEntityBlock implements SimpleWaterloggedBlock
}
@Override
public ItemInteractionResult useItemOn(ItemStack pStack, BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos);
if (tile == null)
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
return InteractionResult.PASS;
if (!tile.canHaveModules())
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
return InteractionResult.PASS;
var stack = player.getItemInHand(handIn);
if (stack.getItem() instanceof IModule) {
var copy = stack.copy();
@ -90,14 +90,14 @@ public class PipeBlock extends BaseEntityBlock implements SimpleWaterloggedBlock
var remain = ItemHandlerHelper.insertItem(tile.modules, copy, false);
if (remain.isEmpty()) {
stack.shrink(1);
return ItemInteractionResult.SUCCESS;
return InteractionResult.SUCCESS;
}
} else if (handIn == InteractionHand.MAIN_HAND && stack.isEmpty()) {
if (!worldIn.isClientSide)
player.openMenu(tile, pos);
return ItemInteractionResult.SUCCESS;
return InteractionResult.SUCCESS;
}
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
return InteractionResult.PASS;
}
@Override

View file

@ -11,7 +11,6 @@ import de.ellpeck.prettypipes.pipe.containers.MainPipeContainer;
import de.ellpeck.prettypipes.pressurizer.PressurizerBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
@ -93,60 +92,60 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
}
@Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) {
super.saveAdditional(compound, provider);
compound.put("modules", this.modules.serializeNBT(provider));
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.put("modules", this.modules.serializeNBT());
compound.putInt("module_drop_check", this.moduleDropCheck);
compound.put("requests", Utility.serializeAll(provider, this.craftIngredientRequests));
compound.put("requests", Utility.serializeAll(this.craftIngredientRequests));
if (this.cover != null)
compound.put("cover", NbtUtils.writeBlockState(this.cover));
var results = new ListTag();
for (var triple : this.craftResultRequests) {
var nbt = new CompoundTag();
nbt.putLong("dest_pipe", triple.getLeft().asLong());
nbt.put("item", triple.getRight().save(provider));
nbt.put("item", triple.getRight().save(new CompoundTag()));
results.add(nbt);
}
compound.put("craft_results", results);
}
@Override
public void loadAdditional(CompoundTag compound, HolderLookup.Provider provider) {
this.modules.deserializeNBT(provider, compound.getCompound("modules"));
public void load(CompoundTag compound) {
this.modules.deserializeNBT(compound.getCompound("modules"));
this.moduleDropCheck = compound.getInt("module_drop_check");
this.cover = compound.contains("cover") ? NbtUtils.readBlockState(this.level != null ? this.level.holderLookup(Registries.BLOCK) : BuiltInRegistries.BLOCK.asLookup(), compound.getCompound("cover")) : null;
this.craftIngredientRequests.clear();
this.craftIngredientRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), l -> new NetworkLock(provider, l)));
this.craftIngredientRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), NetworkLock::new));
this.craftResultRequests.clear();
var results = compound.getList("craft_results", Tag.TAG_COMPOUND);
for (var i = 0; i < results.size(); i++) {
var nbt = results.getCompound(i);
this.craftResultRequests.add(Pair.of(
BlockPos.of(nbt.getLong("dest_pipe")),
ItemStack.parseOptional(provider, nbt.getCompound("item"))));
BlockPos.of(nbt.getLong("dest_pipe")),
ItemStack.of(nbt.getCompound("item"))));
}
super.loadAdditional(compound, provider);
super.load(compound);
}
@Override
public CompoundTag getUpdateTag(HolderLookup.Provider provider) {
public CompoundTag getUpdateTag() {
// sync pipe items on load
var nbt = this.saveWithoutMetadata(provider);
nbt.put("items", Utility.serializeAll(provider, this.getItems()));
var nbt = this.saveWithoutMetadata();
nbt.put("items", Utility.serializeAll(this.getItems()));
return nbt;
}
@Override
public void handleUpdateTag(CompoundTag nbt, HolderLookup.Provider provider) {
this.loadWithComponents(nbt, provider);
public void handleUpdateTag(CompoundTag nbt) {
this.load(nbt);
var items = this.getItems();
items.clear();
items.addAll(Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), d -> IPipeItem.load(provider, d)));
items.addAll(Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load));
}
@Override
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider provider) {
this.loadWithComponents(pkt.getTag(), provider);
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
this.load(pkt.getTag());
}
public List<IPipeItem> getItems() {
@ -280,8 +279,8 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
public List<ItemStack> getAllCraftables() {
return this.streamModules()
.flatMap(m -> m.getRight().getAllCraftables(m.getLeft(), this).stream())
.collect(Collectors.toList());
.flatMap(m -> m.getRight().getAllCraftables(m.getLeft(), this).stream())
.collect(Collectors.toList());
}
public int getCraftableAmount(Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) {
@ -374,8 +373,8 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
public int getNextNode(List<BlockPos> nodes, int index) {
return this.streamModules()
.map(m -> m.getRight().getCustomNextNode(m.getLeft(), this, nodes, index))
.filter(m -> m != null && m >= 0).findFirst().orElse(index);
.map(m -> m.getRight().getCustomNextNode(m.getLeft(), this, nodes, index))
.filter(m -> m != null && m >= 0).findFirst().orElse(index);
}
public List<ItemFilter> getFilters(Direction direction) {

View file

@ -20,7 +20,7 @@ import java.util.List;
public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extends AbstractContainerScreen<T> {
protected static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/pipe.png");
protected static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/pipe.png");
private final List<Tab> tabs = new ArrayList<>();
private final ItemStack[] lastItems = new ItemStack[this.menu.tile.modules.getSlots()];
@ -144,7 +144,7 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
return false;
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32)
return false;
PacketDistributor.sendToServer(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, List.of(this.index)));
PacketDistributor.SERVER.noArg().send(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, this.index));
AbstractPipeGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true;
}

View file

@ -11,7 +11,7 @@ public class HighPriorityModuleItem extends ModuleItem {
private final int priority;
public HighPriorityModuleItem(String name, ModuleTier tier) {
super(name, new Properties());
super(name);
this.priority = tier.forTier(50, 100, 200);
}

View file

@ -11,7 +11,7 @@ public class LowPriorityModuleItem extends ModuleItem {
private final int priority;
public LowPriorityModuleItem(String name, ModuleTier tier) {
super(name, new Properties());
super(name);
this.priority = tier.forTier(-50, -100, -200);
}

View file

@ -8,7 +8,7 @@ import net.minecraft.world.item.ItemStack;
public class RedstoneModuleItem extends ModuleItem {
public RedstoneModuleItem() {
super("redstone_module", new Properties());
super("redstone_module");
}
@Override
@ -25,5 +25,4 @@ public class RedstoneModuleItem extends ModuleItem {
public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false;
}
}

View file

@ -1,12 +1,9 @@
package de.ellpeck.prettypipes.pipe.modules;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.world.item.ItemStack;
import java.util.List;
@ -16,7 +13,7 @@ public class SortingModuleItem extends ModuleItem {
private final Type type;
public SortingModuleItem(String name, Type type) {
super(name, new Properties());
super(name);
this.type = type;
}
@ -35,9 +32,8 @@ public class SortingModuleItem extends ModuleItem {
switch (this.type) {
case ROUND_ROBIN:
// store an ever-increasing index and choose destinations based on that
var prevData = module.get(Data.TYPE);
var next = prevData != null ? prevData.last + 1 : 0;
module.set(Data.TYPE, new Data(next));
var next = module.hasTag() ? module.getTag().getInt("last") + 1 : 0;
module.getOrCreateTag().putInt("last", next);
return next % nodes.size();
case RANDOM:
return tile.getLevel().random.nextInt(nodes.size());
@ -49,12 +45,4 @@ public class SortingModuleItem extends ModuleItem {
ROUND_ROBIN,
RANDOM
}
public record Data(int last) {
public static final Codec<Data> CODEC = RecordCodecBuilder.create(i -> i.group(Codec.INT.fieldOf("last").forGetter(f -> f.last)).apply(i, Data::new));
public static final DataComponentType<Data> TYPE = DataComponentType.<Data>builder().persistent(Data.CODEC).cacheEncoding().build();
}
}

View file

@ -11,7 +11,7 @@ public class SpeedModuleItem extends ModuleItem {
private final float speedIncrease;
public SpeedModuleItem(String name, ModuleTier tier) {
super(name, new Properties());
super(name);
this.speedIncrease = tier.forTier(0.05F, 0.1F, 0.2F);
}
@ -29,5 +29,4 @@ public class SpeedModuleItem extends ModuleItem {
public float getItemSpeedIncrease(ItemStack module, PipeBlockEntity tile) {
return this.speedIncrease;
}
}

View file

@ -19,10 +19,9 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
@Override
protected void addSlots() {
var contents = this.moduleStack.get(CraftingModuleItem.Contents.TYPE);
this.input = contents.input();
this.input = this.module.getInput(this.moduleStack);
for (var i = 0; i < this.input.getSlots(); i++) {
this.addSlot(new FilterSlot(this.input, i, (176 - this.input.getSlots() * 18) / 2 + 1 + i % 9 * 18, 17 + 32 + i / 9 * 18, false) {
this.addSlot(new FilterSlot(this.input, i, (176 - this.module.inputSlots * 18) / 2 + 1 + i % 9 * 18, 17 + 32 + i / 9 * 18, false) {
@Override
public void setChanged() {
super.setChanged();
@ -32,9 +31,9 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
});
}
this.output = contents.output();
this.output = this.module.getOutput(this.moduleStack);
for (var i = 0; i < this.output.getSlots(); i++) {
this.addSlot(new FilterSlot(this.output, i, (176 - this.output.getSlots() * 18) / 2 + 1 + i % 9 * 18, 85 + i / 9 * 18, false) {
this.addSlot(new FilterSlot(this.output, i, (176 - this.module.outputSlots * 18) / 2 + 1 + i % 9 * 18, 85 + i / 9 * 18, false) {
@Override
public void setChanged() {
super.setChanged();
@ -48,7 +47,6 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
public void removed(Player playerIn) {
super.removed(playerIn);
if (this.modified)
this.moduleStack.set(CraftingModuleItem.Contents.TYPE, new CraftingModuleItem.Contents(this.input, this.output));
this.module.save(this.input, this.output, this.moduleStack);
}
}

View file

@ -1,9 +1,6 @@
package de.ellpeck.prettypipes.pipe.modules.craft;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier;
@ -17,7 +14,6 @@ import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
@ -33,10 +29,14 @@ import java.util.function.Consumer;
public class CraftingModuleItem extends ModuleItem {
public final int inputSlots;
public final int outputSlots;
private final int speed;
public CraftingModuleItem(String name, ModuleTier tier) {
super(name, new Properties().component(Contents.TYPE, new Contents(new ItemStackHandler(tier.forTier(1, 4, 9)), new ItemStackHandler(tier.forTier(1, 2, 4)))));
super(name);
this.inputSlots = tier.forTier(1, 4, 9);
this.outputSlots = tier.forTier(1, 2, 4);
this.speed = tier.forTier(20, 10, 5);
}
@ -127,7 +127,7 @@ public class CraftingModuleItem extends ModuleItem {
@Override
public List<ItemStack> getAllCraftables(ItemStack module, PipeBlockEntity tile) {
List<ItemStack> ret = new ArrayList<>();
var output = module.get(Contents.TYPE).output;
var output = this.getOutput(module);
for (var i = 0; i < output.getSlots(); i++) {
var stack = output.getStackInSlot(i);
if (!stack.isEmpty())
@ -141,14 +141,15 @@ public class CraftingModuleItem extends ModuleItem {
var network = PipeNetwork.get(tile.getLevel());
var items = network.getOrderedNetworkItems(tile.getBlockPos());
var equalityTypes = ItemFilter.getEqualityTypes(tile);
var content = module.get(Contents.TYPE);
var input = this.getInput(module);
var craftable = 0;
for (var i = 0; i < content.output.getSlots(); i++) {
var out = content.output.getStackInSlot(i);
var output = this.getOutput(module);
for (var i = 0; i < output.getSlots(); i++) {
var out = output.getStackInSlot(i);
if (!out.isEmpty() && ItemEquality.compareItems(out, stack, equalityTypes)) {
// figure out how many crafting operations we can actually do with the input items we have in the network
var availableCrafts = CraftingTerminalBlockEntity.getAvailableCrafts(tile, content.input.getSlots(), content.input::getStackInSlot, k -> true, s -> items, unavailableConsumer, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes);
var availableCrafts = CraftingTerminalBlockEntity.getAvailableCrafts(tile, input.getSlots(), input::getStackInSlot, k -> true, s -> items, unavailableConsumer, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes);
if (availableCrafts > 0)
craftable += out.getCount() * availableCrafts;
}
@ -173,7 +174,7 @@ public class CraftingModuleItem extends ModuleItem {
var craftableCrafts = Mth.ceil(craftableAmount / (float) resultAmount);
var toCraft = Math.min(craftableCrafts, requiredCrafts);
var input = module.get(Contents.TYPE).input;
var input = this.getInput(module);
for (var i = 0; i < input.getSlots(); i++) {
var in = input.getStackInSlot(i);
if (in.isEmpty())
@ -194,8 +195,30 @@ public class CraftingModuleItem extends ModuleItem {
return remain;
}
public ItemStackHandler getInput(ItemStack module) {
var handler = new ItemStackHandler(this.inputSlots);
if (module.hasTag())
handler.deserializeNBT(module.getTag().getCompound("input"));
return handler;
}
public ItemStackHandler getOutput(ItemStack module) {
var handler = new ItemStackHandler(this.outputSlots);
if (module.hasTag())
handler.deserializeNBT(module.getTag().getCompound("output"));
return handler;
}
public void save(ItemStackHandler input, ItemStackHandler output, ItemStack module) {
var tag = module.getOrCreateTag();
if (input != null)
tag.put("input", input.serializeNBT());
if (output != null)
tag.put("output", output.serializeNBT());
}
private int getResultAmountPerCraft(ItemStack module, ItemStack stack, ItemEquality... equalityTypes) {
var output = module.get(Contents.TYPE).output;
var output = this.getOutput(module);
var resultAmount = 0;
for (var i = 0; i < output.getSlots(); i++) {
var out = output.getStackInSlot(i);
@ -210,15 +233,4 @@ public class CraftingModuleItem extends ModuleItem {
deps.push(module);
return deps;
}
public record Contents(ItemStackHandler input, ItemStackHandler output) {
public static final Codec<Contents> CODEC = RecordCodecBuilder.create(i -> i.group(
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("input").forGetter(d -> d.input),
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("output").forGetter(d -> d.output)
).apply(i, Contents::new));
public static final DataComponentType<Contents> TYPE = DataComponentType.<Contents>builder().persistent(Contents.CODEC).cacheEncoding().build();
}
}

View file

@ -23,7 +23,7 @@ public class ExtractionModuleItem extends ModuleItem {
public final int filterSlots;
public ExtractionModuleItem(String name, ModuleTier tier) {
super(name, new Properties());
super(name);
this.maxExtraction = tier.forTier(1, 8, 64);
this.speed = tier.forTier(20, 15, 10);
this.filterSlots = tier.forTier(3, 6, 9);

View file

@ -13,7 +13,7 @@ import net.minecraft.world.item.ItemStack;
public class FilterIncreaseModuleItem extends ModuleItem {
public FilterIncreaseModuleItem() {
super("filter_increase_modifier", new Properties());
super("filter_increase_modifier");
}
@Override

View file

@ -14,7 +14,7 @@ public class FilterModuleGui extends AbstractPipeGui<FilterModuleContainer> {
@Override
protected void init() {
super.init();
var buttonsY = this.topPos + 17 + 32 + 18 * Mth.ceil(this.menu.filter.content.getSlots() / 9F) + 2;
var buttonsY = this.topPos + 17 + 32 + 18 * Mth.ceil(this.menu.filter.getSlots() / 9F) + 2;
for (var widget : this.menu.filter.getButtons(this, this.leftPos + this.imageWidth - 7, buttonsY, true))
this.addRenderableWidget(widget);
this.addRenderableWidget(this.menu.directionSelector.getButton(this.leftPos + 7, buttonsY));

View file

@ -20,7 +20,7 @@ public class FilterModuleItem extends ModuleItem {
private final boolean canPopulateFromInventories;
public FilterModuleItem(String name, ModuleTier tier) {
super(name, new Properties());
super(name);
this.filterSlots = tier.forTier(5, 9, 18);
this.canPopulateFromInventories = tier.forTier(false, false, true);
}

View file

@ -21,8 +21,8 @@ public class FilterModifierModuleContainer extends AbstractPipeContainer<FilterM
public List<ResourceLocation> getTags() {
Set<ResourceLocation> unsortedTags = new HashSet<>();
for (var filter : this.tile.getFilters(null)) {
for (var i = 0; i < filter.content.getSlots(); i++) {
var stack = filter.content.getStackInSlot(i);
for (var i = 0; i < filter.getSlots(); i++) {
var stack = filter.getStackInSlot(i);
stack.getTags().forEach(t -> unsortedTags.add(t.location()));
}
}

View file

@ -134,7 +134,7 @@ public class FilterModifierModuleGui extends AbstractPipeGui<FilterModifierModul
return false;
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 140 || mouseY >= this.y + 12)
return false;
PacketButton.sendAndExecute(FilterModifierModuleGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.TAG_FILTER, List.of(FilterModifierModuleGui.this.tags.indexOf(this.tag)));
PacketButton.sendAndExecute(FilterModifierModuleGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.TAG_FILTER, FilterModifierModuleGui.this.tags.indexOf(this.tag));
FilterModifierModuleGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true;
}

View file

@ -1,14 +1,12 @@
package de.ellpeck.prettypipes.pipe.modules.modifier;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.core.component.DataComponentType;
import joptsimple.internal.Strings;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
@ -19,7 +17,7 @@ public class FilterModifierModuleItem extends ModuleItem {
public final ItemEquality.Type type;
public FilterModifierModuleItem(String name, ItemEquality.Type type) {
super(name, new Properties());
super(name);
this.type = type;
}
@ -47,21 +45,15 @@ public class FilterModifierModuleItem extends ModuleItem {
}
public static ResourceLocation getFilterTag(ItemStack stack) {
var data = stack.get(Data.TYPE);
return data != null && data.filterTag != null ? ResourceLocation.parse(data.filterTag) : null;
if (!stack.hasTag())
return null;
var tag = stack.getTag().getString("filter_tag");
if (Strings.isNullOrEmpty(tag))
return null;
return new ResourceLocation(tag);
}
public static void setFilterTag(ItemStack stack, ResourceLocation tag) {
stack.set(Data.TYPE, new Data(tag.toString()));
stack.getOrCreateTag().putString("filter_tag", tag.toString());
}
public record Data(String filterTag) {
public static final Codec<Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Codec.STRING.fieldOf("filter_tag").forGetter(f -> f.filterTag)
).apply(i, Data::new));
public static final DataComponentType<Data> TYPE = DataComponentType.<Data>builder().persistent(Data.CODEC).cacheEncoding().build();
}
}

View file

@ -25,7 +25,7 @@ public class RetrievalModuleItem extends ModuleItem {
public final int filterSlots;
public RetrievalModuleItem(String name, ModuleTier tier) {
super(name, new Properties());
super(name);
this.maxExtraction = tier.forTier(1, 8, 16);
this.speed = tier.forTier(40, 20, 10);
this.filterSlots = tier.forTier(3, 6, 9);
@ -41,8 +41,8 @@ public class RetrievalModuleItem extends ModuleItem {
var equalityTypes = ItemFilter.getEqualityTypes(tile);
// loop through filters to see which items to pull
Arrays.stream(directions).flatMap(d -> tile.getFilters(d).stream()).distinct().forEach(f -> {
for (var i = 0; i < f.content.getSlots(); i++) {
var filtered = f.content.getStackInSlot(i);
for (var i = 0; i < f.getSlots(); i++) {
var filtered = f.getStackInSlot(i);
if (filtered.isEmpty())
continue;
var copy = filtered.copy();

View file

@ -11,7 +11,6 @@ import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory;
import java.util.List;
import java.util.function.Supplier;
public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer> {
@ -35,18 +34,17 @@ public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer
}
});
var data = this.menu.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT);
textField.setValue(String.valueOf(data.maxStackSize()));
textField.setValue(String.valueOf(StackSizeModuleItem.getMaxStackSizeForModule(this.menu.moduleStack)));
textField.setMaxLength(4);
textField.setResponder(s -> {
if (s.isEmpty())
return;
var amount = Integer.parseInt(s);
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_AMOUNT, List.of(amount));
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_AMOUNT, amount);
});
Supplier<Component> buttonText = () -> Component.translatable("info." + PrettyPipes.ID + ".limit_to_max_" + (data.limitToMaxStackSize() ? "on" : "off"));
Supplier<Component> buttonText = () -> Component.translatable("info." + PrettyPipes.ID + ".limit_to_max_" + (StackSizeModuleItem.getLimitToMaxStackSize(this.menu.moduleStack) ? "on" : "off"));
this.addRenderableWidget(Button.builder(buttonText.get(), b -> {
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON, List.of());
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON);
b.setMessage(buttonText.get());
}).bounds(this.leftPos + 7, this.topPos + 17 + 32 + 10 + 22, 120, 20).build());
}
@ -57,5 +55,4 @@ public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer
graphics.drawString(this.font, I18n.get("info." + PrettyPipes.ID + ".max_stack_size") + ":", 7, 17 + 32, 4210752, false);
}
}

View file

@ -1,7 +1,5 @@
package de.ellpeck.prettypipes.pipe.modules.stacksize;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem;
@ -9,7 +7,6 @@ import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
@ -18,15 +15,37 @@ import net.neoforged.neoforge.items.IItemHandler;
public class StackSizeModuleItem extends ModuleItem {
public StackSizeModuleItem() {
super("stack_size_module", new Properties());
super("stack_size_module");
}
public static int getMaxStackSizeForModule(ItemStack module) {
if (module.hasTag()) {
var amount = module.getTag().getInt("max_stack_size");
if (amount > 0)
return amount;
}
return 64;
}
public static void setMaxStackSize(ItemStack module, int amount) {
module.getOrCreateTag().putInt("max_stack_size", amount);
}
public static boolean getLimitToMaxStackSize(ItemStack module) {
if (module.hasTag())
return module.getTag().getBoolean("limit_to_max_stack_size");
return false;
}
public static void setLimitToMaxStackSize(ItemStack module, boolean yes) {
module.getOrCreateTag().putBoolean("limit_to_max_stack_size", yes);
}
@Override
public int getMaxInsertionAmount(ItemStack module, PipeBlockEntity tile, ItemStack stack, IItemHandler destination) {
var types = ItemFilter.getEqualityTypes(tile);
var data = module.getOrDefault(Data.TYPE, Data.DEFAULT);
var max = data.maxStackSize;
if (data.limitToMaxStackSize)
var max = StackSizeModuleItem.getMaxStackSizeForModule(module);
if (StackSizeModuleItem.getLimitToMaxStackSize(module))
max = Math.min(max, stack.getMaxStackSize());
var amount = 0;
for (var i = 0; i < destination.getSlots(); i++) {
@ -57,16 +76,4 @@ public class StackSizeModuleItem extends ModuleItem {
return new StackSizeModuleContainer(Registry.stackSizeModuleContainer, windowId, player, tile.getBlockPos(), moduleIndex);
}
public record Data(int maxStackSize, boolean limitToMaxStackSize) {
public static final Data DEFAULT = new Data(64, false);
public static final Codec<StackSizeModuleItem.Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Codec.INT.fieldOf("max_stack_size").forGetter(f -> f.maxStackSize),
Codec.BOOL.fieldOf("limit_to_max_stack_size").forGetter(f -> f.limitToMaxStackSize)
).apply(i, StackSizeModuleItem.Data::new));
public static final DataComponentType<StackSizeModuleItem.Data> TYPE = DataComponentType.<StackSizeModuleItem.Data>builder().persistent(StackSizeModuleItem.Data.CODEC).cacheEncoding().build();
}
}

View file

@ -6,11 +6,12 @@ import de.ellpeck.prettypipes.Utility;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.RenderShape;
@ -21,6 +22,7 @@ import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import javax.annotation.Nullable;
import java.util.List;
public class PressurizerBlock extends BaseEntityBlock {
@ -37,7 +39,7 @@ public class PressurizerBlock extends BaseEntityBlock {
}
@Override
public InteractionResult useWithoutItem(BlockState state, Level worldIn, BlockPos pos, Player player, BlockHitResult result) {
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(PressurizerBlockEntity.class, worldIn, pos);
if (tile == null)
return InteractionResult.PASS;
@ -58,8 +60,8 @@ public class PressurizerBlock extends BaseEntityBlock {
}
@Override
public void appendHoverText(ItemStack pStack, Item.TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), pTooltipComponents);
public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), tooltip);
}
@org.jetbrains.annotations.Nullable

View file

@ -8,7 +8,6 @@ import de.ellpeck.prettypipes.pipe.ConnectionType;
import de.ellpeck.prettypipes.pipe.IPipeConnectable;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
@ -52,30 +51,30 @@ public class PressurizerBlockEntity extends BlockEntity implements MenuProvider,
}
@Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) {
super.saveAdditional(compound, provider);
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.putInt("energy", this.getEnergy());
}
@Override
public void loadAdditional(CompoundTag nbt, HolderLookup.Provider provider) {
public void load(CompoundTag nbt) {
this.storage.setEnergyStored(nbt.getInt("energy"));
super.loadAdditional(nbt, provider);
super.load(nbt);
}
@Override
public CompoundTag getUpdateTag(HolderLookup.Provider provider) {
return this.saveWithoutMetadata(provider);
public CompoundTag getUpdateTag() {
return this.saveWithoutMetadata();
}
@Override
public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider provider) {
this.loadWithComponents(tag, provider);
public void handleUpdateTag(CompoundTag tag) {
this.load(tag);
}
@Override
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider provider) {
this.loadWithComponents(pkt.getTag(), provider);
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
this.load(pkt.getTag());
}
@Override

View file

@ -9,7 +9,7 @@ import net.minecraft.world.entity.player.Inventory;
public class PressurizerGui extends AbstractContainerScreen<PressurizerContainer> {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/pressurizer.png");
private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/pressurizer.png");
public PressurizerGui(PressurizerContainer screenContainer, Inventory inv, Component titleIn) {
super(screenContainer, inv, titleIn);

View file

@ -13,16 +13,13 @@ import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler;
@ -79,8 +76,8 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
var network = this.networkItems.get(new EquatableItemStack(stack, ItemEquality.NBT));
if (network != null) {
amount = network.getLocations().stream()
.mapToInt(l -> l.getItemAmount(this.level, stack, ItemEquality.NBT))
.sum();
.mapToInt(l -> l.getItemAmount(this.level, stack, ItemEquality.NBT))
.sum();
}
// check craftables
if (amount <= 0 && highestAmount <= 0) {
@ -100,8 +97,8 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
if (!this.level.isClientSide) {
List<PacketGhostSlot.Entry> clients = new ArrayList<>();
for (var i = 0; i < this.ghostItems.getSlots(); i++)
clients.add(PacketGhostSlot.Entry.fromStacks(this.level, List.of(this.ghostItems.getStackInSlot(i))));
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(this.getBlockPos()), new PacketGhostSlot(this.getBlockPos(), clients));
clients.add(new PacketGhostSlot.Entry(this.level, Collections.singletonList(this.ghostItems.getStackInSlot(i))));
PacketDistributor.TRACKING_CHUNK.with(this.level.getChunkAt(this.getBlockPos())).send(new PacketGhostSlot(this.getBlockPos(), clients));
}
}
@ -113,7 +110,7 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
network.startProfile("terminal_request_crafting");
this.updateItems();
// get the amount of crafts that we can do
var lowestAvailable = CraftingTerminalBlockEntity.getAvailableCrafts(pipe, this.craftItems.getSlots(), i -> this.getRequestedCraftItem(i).copyWithCount(1), this::isGhostItem, s -> {
var lowestAvailable = CraftingTerminalBlockEntity.getAvailableCrafts(pipe, this.craftItems.getSlots(), i -> ItemHandlerHelper.copyStackWithSize(this.getRequestedCraftItem(i), 1), this::isGhostItem, s -> {
var item = this.networkItems.get(s);
return item != null ? item.getLocations() : Collections.emptyList();
}, ItemTerminalBlockEntity.onItemUnavailable(player, force), new Stack<>(), ItemEquality.NBT);
@ -140,15 +137,15 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
}
@Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) {
super.saveAdditional(compound, provider);
compound.put("craft_items", this.craftItems.serializeNBT(provider));
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.put("craft_items", this.craftItems.serializeNBT());
}
@Override
public void loadAdditional(CompoundTag compound, HolderLookup.Provider provider) {
this.craftItems.deserializeNBT(provider, compound.getCompound("craft_items"));
super.loadAdditional(compound, provider);
public void load(CompoundTag compound) {
this.craftItems.deserializeNBT(compound.getCompound("craft_items"));
super.load(compound);
}
@Override
@ -173,7 +170,7 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
for (var i = 0; i < tile.craftItems.getSlots(); i++) {
var stack = tile.getRequestedCraftItem(i);
var count = tile.isGhostItem(i) ? 0 : stack.getCount();
if (!ItemStack.isSameItemSameComponents(stack, remain))
if (!ItemHandlerHelper.canItemStacksStack(stack, remain))
continue;
// ensure that a single non-stackable item can still enter a ghost slot
if (!stack.isStackable() && count >= 1)

View file

@ -7,11 +7,12 @@ import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.RenderShape;
@ -22,6 +23,7 @@ import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import javax.annotation.Nullable;
import java.util.List;
public class ItemTerminalBlock extends BaseEntityBlock {
@ -38,19 +40,19 @@ public class ItemTerminalBlock extends BaseEntityBlock {
}
@Override
protected InteractionResult useWithoutItem(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, BlockHitResult pHitResult) {
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, pLevel, pPos);
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, worldIn, pos);
if (tile == null)
return InteractionResult.PASS;
var reason = tile.getInvalidTerminalReason();
if (reason != null) {
if (!pLevel.isClientSide)
pPlayer.sendSystemMessage(Component.translatable(reason).withStyle(ChatFormatting.RED));
if (!worldIn.isClientSide)
player.sendSystemMessage(Component.translatable(reason).withStyle(ChatFormatting.RED));
return InteractionResult.SUCCESS;
}
if (!pLevel.isClientSide) {
pPlayer.openMenu(tile, pPos);
tile.updateItems(pPlayer);
if (!worldIn.isClientSide) {
player.openMenu(tile, pos);
tile.updateItems(player);
}
return InteractionResult.SUCCESS;
}
@ -77,8 +79,8 @@ public class ItemTerminalBlock extends BaseEntityBlock {
}
@Override
public void appendHoverText(ItemStack pStack, Item.TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), pTooltipComponents);
public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), tooltip);
}
@org.jetbrains.annotations.Nullable

View file

@ -17,7 +17,6 @@ import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
@ -109,8 +108,8 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
public String getInvalidTerminalReason() {
var network = PipeNetwork.get(this.level);
var pipes = Arrays.stream(Direction.values())
.map(d -> network.getPipe(this.worldPosition.relative(d)))
.filter(Objects::nonNull).count();
.map(d -> network.getPipe(this.worldPosition.relative(d)))
.filter(Objects::nonNull).count();
if (pipes <= 0)
return "info." + PrettyPipes.ID + ".no_pipe_connected";
if (pipes > 1)
@ -147,17 +146,17 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
}
}
public void requestItem(Player player, ItemStack stack, int componentsHash) {
public void requestItem(Player player, ItemStack stack, int nbtHash) {
var network = PipeNetwork.get(this.level);
network.startProfile("terminal_request_item");
this.updateItems();
if (componentsHash != 0) {
if (nbtHash != 0) {
var filter = stack;
stack = this.networkItems.values().stream()
.map(NetworkItem::asStack)
// don't compare with nbt equality here or the data hashing thing is pointless
.filter(s -> ItemEquality.compareItems(s, filter) && !s.isComponentsPatchEmpty() && s.getComponents().hashCode() == componentsHash)
.findFirst().orElse(filter);
.map(NetworkItem::asStack)
// don't compare with nbt equality here or the whole hashing thing is pointless
.filter(s -> ItemEquality.compareItems(s, filter) && s.hasTag() && s.getTag().hashCode() == nbtHash)
.findFirst().orElse(filter);
stack.setCount(filter.getCount());
}
var requested = this.requestItemImpl(stack, ItemTerminalBlockEntity.onItemUnavailable(player, false));
@ -229,18 +228,18 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
}
@Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider pRegistries) {
super.saveAdditional(compound, pRegistries);
compound.put("items", this.items.serializeNBT(pRegistries));
compound.put("requests", Utility.serializeAll(pRegistries, this.existingRequests));
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.put("items", this.items.serializeNBT());
compound.put("requests", Utility.serializeAll(this.existingRequests));
}
@Override
protected void loadAdditional(CompoundTag compound, HolderLookup.Provider pRegistries) {
this.items.deserializeNBT(pRegistries, compound.getCompound("items"));
public void load(CompoundTag compound) {
this.items.deserializeNBT(compound.getCompound("items"));
this.existingRequests.clear();
this.existingRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), l -> new NetworkLock(pRegistries, l)));
super.loadAdditional(compound, pRegistries);
this.existingRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), NetworkLock::new));
super.load(compound);
}
@Override

View file

@ -48,9 +48,9 @@ public class CraftingTerminalContainer extends ItemTerminalContainer {
super.slotsChanged(inventoryIn);
if (!this.player.level().isClientSide) {
var ret = ItemStack.EMPTY;
var optional = this.player.level().getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, this.craftInventory.asCraftInput(), this.player.level());
var optional = this.player.level().getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, this.craftInventory, this.player.level());
if (optional.isPresent())
ret = optional.get().value().assemble(this.craftInventory.asCraftInput(), this.player.level().registryAccess());
ret = optional.get().value().assemble(this.craftInventory, this.player.level().registryAccess());
this.craftResult.setItem(0, ret);
((ServerPlayer) this.player).connection.send(new ClientboundContainerSetSlotPacket(this.containerId, 0, 0, ret));
}

View file

@ -11,11 +11,9 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.neoforged.neoforge.network.PacketDistributor;
import java.util.Arrays;
public class CraftingTerminalGui extends ItemTerminalGui {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/crafting_terminal.png");
private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/crafting_terminal.png");
private Button requestButton;
public CraftingTerminalGui(ItemTerminalContainer screenContainer, Inventory inv, Component titleIn) {
@ -30,7 +28,7 @@ public class CraftingTerminalGui extends ItemTerminalGui {
var amount = ItemTerminalGui.requestModifier();
// also allow holding backspace instead of alt for people whose alt key is inaccessible (linux?)
var force = Screen.hasAltDown() || InputConstants.isKeyDown(this.minecraft.getWindow().getWindow(), 259) ? 1 : 0;
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, Arrays.asList(amount, force)));
PacketDistributor.SERVER.noArg().send(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, amount, force));
}).bounds(this.leftPos + 8, this.topPos + 100, 50, 20).build());
this.tick();
}

View file

@ -20,7 +20,6 @@ import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.neoforged.neoforge.network.PacketDistributor;
@ -30,10 +29,9 @@ import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@SuppressWarnings("ALL")
public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContainer> {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/item_terminal.png");
private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/item_terminal.png");
public List<ItemStack> currentlyCrafting;
public EditBox search;
@ -93,7 +91,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
return;
var stack = widget.get().stack.copy();
stack.setCount(1);
PacketDistributor.sendToServer(new PacketRequest(this.menu.tile.getBlockPos(), stack, this.requestAmount));
PacketDistributor.SERVER.noArg().send(new PacketRequest(this.menu.tile.getBlockPos(), stack, this.requestAmount));
this.requestAmount = 1;
}).bounds(this.leftPos + this.getXOffset() + 95 - 7 - 25, this.topPos + 115, 50, 20).build());
this.requestButton.active = false;
@ -161,7 +159,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
// and vanilla buttons are activated when the click starts, so we'll always invoke jei accidentally by default
if (button == 0 && this.cancelCraftingButton.visible && this.cancelCraftingButton.isHovered()) {
if (this.currentlyCrafting != null && !this.currentlyCrafting.isEmpty()) {
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING, List.of()));
PacketDistributor.SERVER.noArg().send(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING));
return true;
}
}
@ -234,7 +232,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
search = search.substring(1);
} else if (search.startsWith("#")) {
// search item description
var hoverText = s.getLeft().getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player,
var hoverText = s.getLeft().getTooltipLines(this.minecraft.player,
this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL);
toCompare = hoverText.stream().map(Component::getString).collect(Collectors.joining("\n"));
search = search.substring(1);