Compare commits

..

6 commits

Author SHA1 Message Date
Ell
a8d1a99e28 made it run! 2024-09-15 19:56:42 +02:00
Ell
375f5522f9 it compiles?? 2024-09-15 19:12:35 +02:00
Ell
3e70470e83 some work on components 2024-09-15 16:24:19 +02:00
Ell
bc710789c8 networking stuff 2024-09-15 15:17:16 +02:00
Ell
2e05cd7b70 bunch of work 2024-09-15 14:23:14 +02:00
Ell
68c68ae5b7 initial 1.21 build setup 2024-09-15 13:45:53 +02:00
64 changed files with 760 additions and 789 deletions

View file

@ -3,7 +3,16 @@ plugins {
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.neoforged.gradle.userdev' version '7.0.80'
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
}
// Enable the Jar-in-Jar system for your mod
@ -27,8 +36,8 @@ base {
archivesName = mod_name
}
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
runs {
@ -62,7 +71,7 @@ runs {
server {
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
programArgument '--nogui'
argument '--nogui'
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
@ -77,7 +86,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.
programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
arguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
}
}
@ -127,8 +136,8 @@ tasks.withType(ProcessResources).configureEach {
]
inputs.properties replaceProperties
filesMatching(['META-INF/mods.toml']) {
expand replaceProperties + [project: project]
filesMatching(['META-INF/neoforge.mods.toml']) {
expand replaceProperties
}
}
@ -154,3 +163,11 @@ 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,22 +1,24 @@
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.20.3
neogradle.subsystems.parchment.mappingsVersion=2023.12.31
neogradle.subsystems.parchment.minecraftVersion=1.21
neogradle.subsystems.parchment.mappingsVersion=2024.07.28
# 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.20.4
minecraft_version_range=[1.20.4,1.21)
minecraft_version=1.21.1
minecraft_version_range=[1.21.1,1.22)
# The Neo version must agree with the Minecraft version to get a valid artifact
neo_version=20.4.195
neo_version=21.1.45
# The Neo version range can use any version of Neo as bounds
neo_version_range=[20.4,)
neo_version_range=[21.1.0,)
# The loader version range can only use the major version of FML as bounds
loader_version_range=[2,)
loader_version_range=[4,)
jei_version=17.3.0.49
jei_version=19.18.3.204
jgt_version=1.5.2
jheaps_version=0.14
apfloat_version=1.10.1

Binary file not shown.

View file

@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-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,6 +15,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
@ -32,10 +34,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:
#
@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@ -80,13 +82,12 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# 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"'
# 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
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@ -133,22 +134,29 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
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.
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
@ -193,11 +201,15 @@ if "$cygwin" || "$msys" ; then
done
fi
# 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.
# 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.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
@ -205,6 +217,12 @@ 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,8 +13,10 @@
@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
@ -25,7 +27,8 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
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.
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
goto fail
@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
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.
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
goto fail
@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
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%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View file

@ -3,7 +3,9 @@ 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;
@ -47,7 +49,6 @@ 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;
@ -68,24 +69,26 @@ 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.Mod.EventBusSubscriber;
import net.neoforged.fml.common.Mod.EventBusSubscriber.Bus;
import net.neoforged.fml.common.EventBusSubscriber;
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.RegisterPayloadHandlerEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
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(new ResourceLocation(PrettyPipes.ID, "pipe_connectable"), IPipeConnectable.class);
public static BlockCapability<IPipeConnectable, Direction> pipeConnectableCapability = BlockCapability.createSided(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_connectable"), IPipeConnectable.class);
public static Item wrenchItem;
public static Item pipeFrameItem;
@ -119,19 +122,19 @@ public final class Registry {
@SubscribeEvent
public static void register(RegisterEvent event) {
event.register(Registries.BLOCK, h -> {
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)));
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)));
});
event.register(Registries.ITEM, h -> {
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());
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());
Registry.registerTieredModule(h, "extraction_module", ExtractionModuleItem::new);
Registry.registerTieredModule(h, "filter_module", FilterModuleItem::new);
@ -143,33 +146,33 @@ public final class Registry {
for (var type : ItemEquality.Type.values()) {
var name = type.name().toLowerCase(Locale.ROOT) + "_filter_modifier";
h.register(new ResourceLocation(PrettyPipes.ID, name), new FilterModifierModuleItem(name, type));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, name), new FilterModifierModuleItem(name, type));
}
for (var type : SortingModuleItem.Type.values()) {
var name = type.name().toLowerCase(Locale.ROOT) + "_sorting_modifier";
h.register(new ResourceLocation(PrettyPipes.ID, name), new SortingModuleItem(name, type));
h.register(ResourceLocation.fromNamespaceAndPath(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(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));
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));
});
event.register(Registries.ENTITY_TYPE, h ->
h.register(new ResourceLocation(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameEntity = EntityType.Builder.<PipeFrameEntity>of(PipeFrameEntity::new, MobCategory.MISC).build("pipe_frame")));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameEntity = EntityType.Builder.<PipeFrameEntity>of(PipeFrameEntity::new, MobCategory.MISC).build("pipe_frame")));
event.register(Registries.MENU, h -> {
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())));
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())));
Registry.extractionModuleContainer = Registry.registerPipeContainer(h, "extraction_module");
Registry.filterModuleContainer = Registry.registerPipeContainer(h, "filter_module");
@ -181,18 +184,27 @@ public final class Registry {
});
event.register(BuiltInRegistries.CREATIVE_MODE_TAB.key(), h -> {
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()
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()
);
});
event.register(Registries.RECIPE_SERIALIZER, h -> {
h.register(new ResourceLocation(PrettyPipes.ID, "module_clearing"), ModuleClearingRecipe.SERIALIZER);
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);
});
}
@ -207,14 +219,14 @@ public final class Registry {
}
@SubscribeEvent
public static void registerPayloads(final RegisterPayloadHandlerEvent event) {
public static void registerPayloads(final RegisterPayloadHandlersEvent event) {
var registrar = event.registrar(PrettyPipes.ID);
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);
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);
}
private static <T extends AbstractPipeContainer<?>> MenuType<T> registerPipeContainer(RegisterEvent.RegisterHelper<MenuType<?>> helper, String name) {
@ -224,13 +236,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(new ResourceLocation(PrettyPipes.ID, name), type);
helper.register(ResourceLocation.fromNamespaceAndPath(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(new ResourceLocation(PrettyPipes.ID, tier.name().toLowerCase(Locale.ROOT) + "_" + name), item.apply(name, tier));
helper.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, tier.name().toLowerCase(Locale.ROOT) + "_" + name), item.apply(name, tier));
}
@EventBusSubscriber(bus = Bus.MOD, value = Dist.CLIENT)
@ -240,18 +252,21 @@ public final class Registry {
public static void setup(FMLClientSetupEvent event) {
BlockEntityRenderers.register(Registry.pipeBlockEntity, PipeRenderer::new);
EntityRenderers.register(Registry.pipeFrameEntity, PipeFrameRenderer::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);
@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);
}
}

View file

@ -1,12 +1,17 @@
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;
@ -22,6 +27,7 @@ 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;
@ -29,9 +35,21 @@ 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;
@ -104,10 +122,10 @@ public final class Utility {
return ItemStack.EMPTY;
}
public static ListTag serializeAll(Collection<? extends INBTSerializable<CompoundTag>> items) {
public static ListTag serializeAll(HolderLookup.Provider provider, Collection<? extends INBTSerializable<CompoundTag>> items) {
var list = new ListTag();
for (INBTSerializable<CompoundTag> item : items)
list.add(item.serializeNBT());
list.add(item.serializeNBT(provider));
return list;
}
@ -140,8 +158,19 @@ 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,25 +4,21 @@ 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.IRecipeTransferHandler;
import mezz.jei.api.recipe.transfer.IUniversalRecipeTransferHandler;
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 IRecipeTransferHandler<CraftingModuleContainer, RecipeHolder<CraftingRecipe>> {
public class CraftingModuleTransferHandler implements IUniversalRecipeTransferHandler<CraftingModuleContainer> {
@Override
public Class<CraftingModuleContainer> getContainerClass() {
@ -35,21 +31,16 @@ public class CraftingModuleTransferHandler implements IRecipeTransferHandler<Cra
}
@Override
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) {
public @Nullable IRecipeTransferError transferRecipe(CraftingModuleContainer container, Object recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) {
if (!doTransfer)
return null;
var inputs = new ArrayList<ItemStack>();
var outputs = new ArrayList<ItemStack>();
for (var entry : slots.getSlotViews()) {
for (var entry : recipeSlots.getSlotViews()) {
var allIngredients = entry.getIngredients(VanillaTypes.ITEM_STACK).toList();
if (allIngredients.isEmpty())
continue;
var remain = allIngredients.get(0).copy();
var remain = allIngredients.getFirst().copy();
var toAdd = entry.getRole() == RecipeIngredientRole.INPUT ? inputs : outputs;
for (var stack : toAdd) {
if (ItemEquality.compareItems(stack, remain)) {
@ -63,7 +54,7 @@ public class CraftingModuleTransferHandler implements IRecipeTransferHandler<Cra
if (!remain.isEmpty())
toAdd.add(remain);
}
PacketDistributor.SERVER.noArg().send(new PacketCraftingModuleTransfer(inputs, outputs));
PacketDistributor.sendToServer(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(new PacketGhostSlot.Entry(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList())));
PacketDistributor.SERVER.noArg().send(new PacketGhostSlot(container.getTile().getBlockPos(), stacks));
stacks.add(PacketGhostSlot.Entry.fromStacks(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList())));
PacketDistributor.sendToServer(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 new ResourceLocation(PrettyPipes.ID, "jei_plugin");
return ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "jei_plugin");
}
@Override
@ -103,7 +103,7 @@ public class JEIPrettyPipesPlugin implements IModPlugin {
}
@SubscribeEvent
public void onClientTick(TickEvent.ClientTickEvent event) {
public void onClientTick(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.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
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() {
super.defineSynchedData();
this.entityData.define(PipeFrameEntity.AMOUNT, -1);
protected void defineSynchedData(SynchedEntityData.Builder pBuilder) {
super.defineSynchedData(pBuilder);
pBuilder.define(PipeFrameEntity.AMOUNT, -1);
}
@Override
@ -154,14 +154,15 @@ public class PipeFrameEntity extends ItemFrame implements IEntityWithComplexSpaw
}
@Override
public void writeSpawnData(FriendlyByteBuf buffer) {
public void writeSpawnData(RegistryFriendlyByteBuf buffer) {
buffer.writeBlockPos(this.pos);
buffer.writeInt(this.direction.ordinal());
}
@Override
public void readSpawnData(FriendlyByteBuf additionalData) {
public void readSpawnData(RegistryFriendlyByteBuf additionalData) {
this.pos = additionalData.readBlockPos();
this.direction = Direction.values()[additionalData.readInt()];
}
}

View file

@ -13,12 +13,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.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;
@ -28,16 +26,16 @@ public abstract class ModuleItem extends Item implements IModule {
private final String name;
public ModuleItem(String name) {
super(new Properties().stacksTo(16));
public ModuleItem(String name, Item.Properties properties) {
super(properties.stacksTo(16));
this.name = name;
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
super.appendHoverText(stack, worldIn, tooltip, flagIn);
Utility.addTooltip(this.name, tooltip);
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
super.appendHoverText(pStack, pContext, pTooltipComponents, pTooltipFlag);
Utility.addTooltip(this.name, pTooltipComponents);
}
@Override
@ -109,4 +107,5 @@ public abstract class ModuleItem extends Item implements IModule {
public DirectionSelector getDirectionSelector(ItemStack module, PipeBlockEntity tile) {
return null;
}
}

View file

@ -5,6 +5,7 @@ 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;
@ -14,10 +15,9 @@ 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,10 +40,9 @@ public class PipeFrameItem extends Item {
var world = context.getLevel();
HangingEntity hangingentity = new PipeFrameEntity(Registry.pipeFrameEntity, world, blockpos1, direction);
var compoundTag = itemstack.getTag();
if (compoundTag != null) {
EntityType.updateCustomEntityTag(world, playerentity, hangingentity, compoundTag);
}
var customdata = itemstack.getOrDefault(DataComponents.ENTITY_DATA, CustomData.EMPTY);
if (!customdata.isEmpty())
EntityType.updateCustomEntityTag(world, playerentity, hangingentity, customdata);
if (hangingentity.survives()) {
if (!world.isClientSide) {
@ -64,8 +63,9 @@ public class PipeFrameItem extends Item {
}
@Override
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);
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);
}
}

View file

@ -4,6 +4,7 @@ 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;
@ -17,7 +18,6 @@ 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 stack, Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), tooltip);
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), pTooltipComponents);
}
@Override
@ -122,7 +122,7 @@ public class WrenchItem extends Item {
}
@Override
public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) {
public boolean supportsEnchantment(ItemStack stack, Holder<Enchantment> enchantment) {
return enchantment == Enchantments.SILK_TOUCH;
}

View file

@ -1,11 +1,13 @@
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.nbt.CompoundTag;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.ItemStack;
import net.neoforged.api.distmarker.Dist;
@ -13,6 +15,8 @@ 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);
@ -33,7 +37,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)) {
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.DIRECTION_SELECTOR, List.of())) {
@Override
public Component getMessage() {
var pipe = DirectionSelector.this.pipe;
@ -64,18 +68,13 @@ public class DirectionSelector {
if (!this.modified)
return;
this.modified = false;
var tag = new CompoundTag();
if (this.direction != null)
tag.putString("direction", this.direction.getName());
this.stack.getOrCreateTag().put("direction_selector", tag);
this.stack.set(Data.TYPE, new Data(this.direction.getName()));
}
public void load() {
if (this.stack.hasTag()) {
var tag = this.stack.getTag().getCompound("direction_selector");
this.direction = Direction.byName(tag.getString("direction"));
}
var data = this.stack.get(Data.TYPE);
if (data != null)
this.direction = Direction.byName(data.direction);
}
public Direction[] directions() {
@ -92,9 +91,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 {
@ -102,4 +101,14 @@ 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,6 +15,7 @@ public record EquatableItemStack(ItemStack stack, ItemEquality... equalityTypes)
@Override
public int hashCode() {
return Objects.hash(this.stack.getItem(), this.stack.getTag());
return Objects.hash(this.stack.getItem(), this.stack.getComponents());
}
}

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.Mod;
import net.neoforged.fml.common.EventBusSubscriber;
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;
@Mod.EventBusSubscriber
@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.getTag(), filter.getTag()) && stack.areAttachmentsCompatible(filter), false, Type.NBT);
public static final ItemEquality NBT = new ItemEquality((stack, filter) -> Objects.equals(stack.getComponents(), filter.getComponents()), 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,6 +1,9 @@
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;
@ -10,7 +13,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.nbt.CompoundTag;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
@ -23,18 +26,26 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class ItemFilter extends ItemStackHandler {
public class ItemFilter {
public final ItemStackHandler content;
public boolean isWhitelist;
public boolean canPopulateFromInventories;
public boolean canModifyWhitelist = true;
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) {
super(size);
this.content = new ItemStackHandler(size) {
@Override
protected void onContentsChanged(int slot) {
ItemFilter.this.modified = true;
}
};
this.stack = stack;
this.pipe = pipe;
this.load();
@ -42,8 +53,8 @@ public class ItemFilter extends ItemStackHandler {
public List<Slot> getSlots(int x, int y) {
List<Slot> slots = new ArrayList<>();
for (var i = 0; i < this.getSlots(); i++)
slots.add(new FilterSlot(this, i, x + i % 9 * 18, y + i / 9 * 18, true));
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));
return slots;
}
@ -53,12 +64,12 @@ public class ItemFilter extends ItemStackHandler {
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, 0);
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, List.of(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, 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, List.of(1))).bounds(x - 42, y, 20, 20).tooltip(Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY))).build());
}
return buttons;
}
@ -84,7 +95,7 @@ public class ItemFilter extends ItemStackHandler {
copy.setCount(1);
// try inserting into ourselves and any filter increase modifiers
for (var filter : filters) {
if (ItemHandlerHelper.insertItem(filter, copy, false).isEmpty()) {
if (ItemHandlerHelper.insertItem(filter.content, copy, false).isEmpty()) {
changed = true;
filter.save();
break;
@ -104,9 +115,9 @@ public class ItemFilter extends ItemStackHandler {
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 (ItemStackHandler handler : this.pipe.getFilters(direction)) {
for (var i = 0; i < handler.getSlots(); i++) {
var filter = handler.getStackInSlot(i);
for (ItemFilter handler : this.pipe.getFilters(direction)) {
for (var i = 0; i < handler.content.getSlots(); i++) {
var filter = handler.content.getStackInSlot(i);
if (filter.isEmpty())
continue;
if (ItemEquality.compareItems(stack, filter, types))
@ -118,42 +129,27 @@ public class ItemFilter extends ItemStackHandler {
public void save() {
if (this.modified) {
this.stack.getOrCreateTag().put("filter", this.serializeNBT());
this.stack.set(Data.TYPE, new Data(this.content, this.isWhitelist));
this.pipe.setChanged();
this.modified = false;
}
}
public void load() {
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;
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;
}
}
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 {
@ -165,4 +161,14 @@ public class ItemFilter extends ItemStackHandler {
}
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,9 +1,7 @@
package de.ellpeck.prettypipes.misc;
import de.ellpeck.prettypipes.items.IModule;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.core.HolderLookup;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.Level;
@ -17,9 +15,10 @@ public class ModuleClearingRecipe extends CustomRecipe {
}
@Override
public boolean matches(CraftingContainer container, Level level) {
public boolean matches(CraftingInput container, Level level) {
var foundModule = false;
for (var stack : container.getItems()) {
for (var i = 0; i < container.size(); i++) {
var stack = container.getItem(i);
if (!foundModule && stack.getItem() instanceof IModule) {
foundModule = true;
} else if (!stack.isEmpty()) {
@ -30,11 +29,13 @@ public class ModuleClearingRecipe extends CustomRecipe {
}
@Override
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;
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;
}
@Override

View file

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

View file

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

View file

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

View file

@ -1,5 +1,6 @@
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;
@ -20,24 +21,24 @@ public class NetworkLock implements INBTSerializable<CompoundTag> {
this.stack = stack;
}
public NetworkLock(CompoundTag nbt) {
this.deserializeNBT(nbt);
public NetworkLock(HolderLookup.Provider provider, CompoundTag nbt) {
this.deserializeNBT(provider, nbt);
}
@Override
public CompoundTag serializeNBT() {
public CompoundTag serializeNBT(HolderLookup.Provider provider) {
var nbt = new CompoundTag();
nbt.putUUID("id", this.lockId);
nbt.put("location", this.location.serializeNBT());
nbt.put("stack", this.stack.save(new CompoundTag()));
nbt.put("location", this.location.serializeNBT(provider));
nbt.put("stack", this.stack.save(provider));
return nbt;
}
@Override
public void deserializeNBT(CompoundTag nbt) {
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) {
this.lockId = nbt.getUUID("id");
this.location = new NetworkLocation(nbt.getCompound("location"));
this.stack = ItemStack.of(nbt.getCompound("stack"));
this.location = new NetworkLocation(provider, nbt.getCompound("location"));
this.stack = ItemStack.parseOptional(provider, nbt.getCompound("stack"));
}
@Override
@ -56,4 +57,5 @@ public class NetworkLock implements INBTSerializable<CompoundTag> {
public String toString() {
return "NetworkLock{" + "location=" + this.location.pipePos + ", stack=" + this.stack + '}';
}
}

View file

@ -8,6 +8,7 @@ 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;
@ -33,7 +34,7 @@ import java.util.function.Consumer;
public class PipeItem implements IPipeItem {
public static final ResourceLocation TYPE = new ResourceLocation(PrettyPipes.ID, "pipe_item");
public static final ResourceLocation TYPE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_item");
public ItemStack stack;
public float speed;
@ -63,10 +64,10 @@ public class PipeItem implements IPipeItem {
this(PipeItem.TYPE, stack, speed);
}
public PipeItem(ResourceLocation type, CompoundTag nbt) {
public PipeItem(HolderLookup.Provider provider, ResourceLocation type, CompoundTag nbt) {
this.type = type;
this.path = new ArrayList<>();
this.deserializeNBT(nbt);
this.deserializeNBT(provider, nbt);
}
@Override
@ -221,12 +222,12 @@ public class PipeItem implements IPipeItem {
}
protected BlockPos getStartPipe() {
return this.path.get(0);
return this.path.getFirst();
}
@Override
public BlockPos getDestPipe() {
return this.path.get(this.path.size() - 1);
return this.path.getLast();
}
@Override
@ -240,10 +241,10 @@ public class PipeItem implements IPipeItem {
}
@Override
public CompoundTag serializeNBT() {
public CompoundTag serializeNBT(HolderLookup.Provider provider) {
var nbt = new CompoundTag();
nbt.putString("type", this.type.toString());
nbt.put("stack", this.stack.save(new CompoundTag()));
nbt.put("stack", this.stack.save(provider));
nbt.putFloat("speed", this.speed);
nbt.put("start_inv", NbtUtils.writeBlockPos(this.startInventory));
nbt.put("dest_inv", NbtUtils.writeBlockPos(this.destInventory));
@ -261,12 +262,12 @@ public class PipeItem implements IPipeItem {
}
@Override
public void deserializeNBT(CompoundTag nbt) {
this.stack = ItemStack.of(nbt.getCompound("stack"));
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) {
this.stack = ItemStack.parseOptional(provider, nbt.getCompound("stack"));
this.speed = nbt.getFloat("speed");
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.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.retryOnObstruction = nbt.getBoolean("drop_on_obstruction");
this.currentTile = nbt.getInt("tile");
this.x = nbt.getFloat("x");
@ -274,8 +275,8 @@ public class PipeItem implements IPipeItem {
this.z = nbt.getFloat("z");
this.path.clear();
var list = nbt.getList("path", Tag.TAG_COMPOUND);
for (var i = 0; i < list.size(); i++)
this.path.add(NbtUtils.readBlockPos(list.getCompound(i)));
for (var tag : list)
this.path.add(Utility.readBlockPos(tag));
}
@Override
@ -287,9 +288,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;
@ -308,9 +309,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();
@ -344,7 +345,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.get(0));
ret.add(nodes.getFirst());
return ret;
}
for (var i = 0; i < nodes.size() - 1; i++) {
@ -368,4 +369,5 @@ public class PipeItem implements IPipeItem {
}
return ret;
}
}

View file

@ -12,12 +12,14 @@ 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;
@ -60,17 +62,17 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
this.dijkstra = new DijkstraShortestPath<>(this.graph);
}
public PipeNetwork(CompoundTag nbt) {
public PipeNetwork(CompoundTag nbt, HolderLookup.Provider provider) {
this();
var nodes = nbt.getList("nodes", Tag.TAG_COMPOUND);
for (var i = 0; i < nodes.size(); i++)
this.graph.addVertex(NbtUtils.readBlockPos(nodes.getCompound(i)));
for (var node : nodes)
this.graph.addVertex(Utility.readBlockPos(node));
var edges = nbt.getList("edges", Tag.TAG_COMPOUND);
for (var i = 0; i < edges.size(); i++)
this.addEdge(new NetworkEdge(edges.getCompound(i)));
for (var item : Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load))
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.pipeItems.put(item.getCurrentPipe(), item);
for (var lock : Utility.deserializeAll(nbt.getList("locks", Tag.TAG_COMPOUND), NetworkLock::new))
for (var lock : Utility.deserializeAll(nbt.getList("locks", Tag.TAG_COMPOUND), t -> new NetworkLock(provider, t)))
this.createNetworkLock(lock);
}
@ -100,25 +102,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) {
public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) {
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());
edges.add(edge.serializeNBT(provider));
nbt.put("edges", edges);
nbt.put("items", Utility.serializeAll(this.pipeItems.values()));
nbt.put("locks", Utility.serializeAll(this.networkLocks.values()));
nbt.put("items", Utility.serializeAll(provider, this.pipeItems.values()));
nbt.put("locks", Utility.serializeAll(provider, this.networkLocks.values()));
return nbt;
}
@ -199,7 +201,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.TRACKING_CHUNK.with(this.level.getChunkAt(startPipePos)).send(new PacketItemEnterPipe(startPipePos, item));
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(startPipePos), new PacketItemEnterPipe(startPipePos, item.serializeNBT(this.level.registryAccess())));
return true;
}
@ -287,8 +289,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 {
@ -302,8 +304,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) {
@ -375,8 +377,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) {
@ -481,9 +483,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();
}
@ -513,8 +515,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,8 +13,10 @@ 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.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
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;
@ -22,64 +24,50 @@ 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.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
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 class PacketButton implements CustomPacketPayload {
public record PacketButton(BlockPos pos, int result, List<Integer> data) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "button");
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);
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();
public PacketButton(BlockPos pos, ButtonResult result, List<Integer> data) {
this(pos, result.ordinal(), data);
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeByte(this.result.ordinal());
buf.writeVarIntArray(this.data);
public Type<? extends CustomPacketPayload> type() {
return PacketButton.TYPE;
}
@Override
public ResourceLocation id() {
return PacketButton.ID;
public static void onMessage(PacketButton message, IPayloadContext ctx) {
var player = ctx.player();
ButtonResult.values()[message.result].action.accept(message.pos, message.data, player);
}
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));
public static void sendAndExecute(BlockPos pos, ButtonResult result, List<Integer> data) {
PacketDistributor.sendToServer(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[0] < 0) {
if (data.getFirst() < 0) {
player.openMenu(tile, pos);
} else {
var stack = tile.modules.getStackInSlot(data[0]);
var stack = tile.modules.getStackInSlot(data.getFirst());
player.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
@ -89,30 +77,32 @@ public class PacketButton implements CustomPacketPayload {
@Nullable
@Override
public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) {
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data[0]);
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data.getFirst());
}
}, buf -> {
buf.writeBlockPos(pos);
buf.writeInt(data[0]);
buf.writeInt(data.getFirst());
});
}
}),
FILTER_CHANGE((pos, data, player) -> {
if (player.containerMenu instanceof IFilteredContainer filtered)
filtered.getFilter().onButtonPacket(filtered, data[0]);
filtered.getFilter().onButtonPacket(filtered, data.getFirst());
}),
STACK_SIZE_MODULE_BUTTON((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu;
StackSizeModuleItem.setLimitToMaxStackSize(container.moduleStack, !StackSizeModuleItem.getLimitToMaxStackSize(container.moduleStack));
var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT);
container.moduleStack.set(StackSizeModuleItem.Data.TYPE, new StackSizeModuleItem.Data(moduleData.maxStackSize(), !moduleData.limitToMaxStackSize()));
}),
STACK_SIZE_AMOUNT((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu;
StackSizeModuleItem.setMaxStackSize(container.moduleStack, data[0]);
var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT);
container.moduleStack.set(StackSizeModuleItem.Data.TYPE, new StackSizeModuleItem.Data(data.getFirst(), moduleData.limitToMaxStackSize()));
}),
CRAFT_TERMINAL_REQUEST((pos, data, player) -> {
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), pos);
tile.requestCraftingItems(player, data[0], data[1] > 0);
tile.requestCraftingItems(player, data.getFirst(), data.get(1) > 0);
}),
CANCEL_CRAFTING((pos, data, player) -> {
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), pos);
@ -120,16 +110,16 @@ public class PacketButton implements CustomPacketPayload {
}),
TAG_FILTER((pos, data, player) -> {
var container = (FilterModifierModuleContainer) player.containerMenu;
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data[0]));
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data.getFirst()));
}),
DIRECTION_SELECTOR((pos, data, player) -> {
if (player.containerMenu instanceof IDirectionContainer filtered)
filtered.getSelector().onButtonPacket();
});
public final TriConsumer<BlockPos, int[], Player> action;
public final TriConsumer<BlockPos, List<Integer>, Player> action;
ButtonResult(TriConsumer<BlockPos, int[], Player> action) {
ButtonResult(TriConsumer<BlockPos, List<Integer>, Player> action) {
this.action = action;
}
}

View file

@ -2,63 +2,40 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
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.item.ItemStack;
import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import java.util.ArrayList;
import java.util.List;
public class PacketCraftingModuleTransfer implements CustomPacketPayload {
public record PacketCraftingModuleTransfer(List<ItemStack> inputs, List<ItemStack> outputs) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "crafting_module_transfer");
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 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());
}
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);
@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);
public Type<? extends CustomPacketPayload> type() {
return PacketCraftingModuleTransfer.TYPE;
}
@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();
}
});
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();
}
}
private static void copy(ItemStackHandler container, List<ItemStack> contents) {

View file

@ -7,7 +7,9 @@ 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.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
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.tags.TagKey;
@ -15,78 +17,45 @@ 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.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class PacketGhostSlot implements CustomPacketPayload {
public record PacketGhostSlot(BlockPos pos, List<Entry> stacks) implements CustomPacketPayload {
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));
}
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);
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeInt(this.stacks.size());
for (var entry : this.stacks)
entry.write(buf);
public Type<? extends CustomPacketPayload> type() {
return PacketGhostSlot.TYPE;
}
@Override
public ResourceLocation id() {
return PacketGhostSlot.ID;
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);
}
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 record Entry(List<ItemStack> stacks, TagKey<Item> tag) {
public static class Entry {
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);
private final List<ItemStack> stacks;
private final TagKey<Item> tag;
public Entry(Level level, List<ItemStack> stacks) {
public static Entry fromStacks(Level level, List<ItemStack> stacks) {
var tag = Entry.getTagForStacks(level, stacks);
if (tag != null) {
this.stacks = null;
this.tag = tag;
return new Entry(null, tag);
} else {
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()));
return new Entry(stacks, null);
}
}
@ -94,20 +63,8 @@ public class PacketGhostSlot implements CustomPacketPayload {
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());
}
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());
}
.filter(h -> h.value() != null & h.value() != Items.AIR)
.map(h -> new ItemStack(h.value())).collect(Collectors.toList());
}
private static TagKey<Item> getTagForStacks(Level level, List<ItemStack> stacks) {

View file

@ -7,49 +7,34 @@ 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.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
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.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
public class PacketItemEnterPipe implements CustomPacketPayload {
public record PacketItemEnterPipe(BlockPos tilePos, CompoundTag item) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "item_enter_pipe");
private final BlockPos tilePos;
private final CompoundTag item;
public PacketItemEnterPipe(BlockPos tilePos, IPipeItem item) {
this.tilePos = tilePos;
this.item = item.serializeNBT();
}
public PacketItemEnterPipe(FriendlyByteBuf buf) {
this.tilePos = buf.readBlockPos();
this.item = buf.readNbt();
}
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);
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.tilePos);
buf.writeNbt(this.item);
public Type<? extends CustomPacketPayload> type() {
return PacketItemEnterPipe.TYPE;
}
@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);
});
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);
}
}

View file

@ -3,76 +3,35 @@ 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.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
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.item.ItemStack;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import java.util.ArrayList;
import java.util.List;
public class PacketNetworkItems implements CustomPacketPayload {
public record PacketNetworkItems(List<ItemStack> items, List<ItemStack> craftables, List<ItemStack> currentlyCrafting) implements CustomPacketPayload {
public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "network_items");
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 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());
}
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);
@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);
public Type<? extends CustomPacketPayload> type() {
return PacketNetworkItems.TYPE;
}
@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);
}
});
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);
}
}

View file

@ -4,59 +4,39 @@ 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.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
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.item.ItemStack;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadContext;
public class PacketRequest implements CustomPacketPayload {
public record PacketRequest(BlockPos pos, ItemStack stack, int componentsHash, int amount) implements CustomPacketPayload {
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 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 PacketRequest(BlockPos pos, ItemStack stack, int 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();
this(pos, stack, !stack.isComponentsPatchEmpty() ? stack.getComponents().hashCode() : 0, amount);
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeItem(this.stack);
buf.writeVarInt(this.nbtHash);
buf.writeVarInt(this.amount);
public Type<? extends CustomPacketPayload> type() {
return PacketRequest.TYPE;
}
@Override
public ResourceLocation id() {
return PacketRequest.ID;
}
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);
@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,6 +5,7 @@ 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;
@ -12,18 +13,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, BiFunction<ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>(
Collections.singletonMap(PipeItem.TYPE, PipeItem::new));
Map<ResourceLocation, TriFunction<HolderLookup.Provider, ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>(
Collections.singletonMap(PipeItem.TYPE, PipeItem::new));
ItemStack getContent();
@ -44,9 +45,10 @@ 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(CompoundTag nbt) {
var type = new ResourceLocation(nbt.getString("type"));
static IPipeItem load(HolderLookup.Provider provider, CompoundTag nbt) {
var type = ResourceLocation.parse(nbt.getString("type"));
var func = IPipeItem.TYPES.get(type);
return func != null ? func.apply(type, nbt) : null;
return func != null ? func.apply(provider, 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.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
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 InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
public ItemInteractionResult useItemOn(ItemStack pStack, BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos);
if (tile == null)
return InteractionResult.PASS;
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
if (!tile.canHaveModules())
return InteractionResult.PASS;
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
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 InteractionResult.SUCCESS;
return ItemInteractionResult.SUCCESS;
}
} else if (handIn == InteractionHand.MAIN_HAND && stack.isEmpty()) {
if (!worldIn.isClientSide)
player.openMenu(tile, pos);
return InteractionResult.SUCCESS;
return ItemInteractionResult.SUCCESS;
}
return InteractionResult.PASS;
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
}
@Override

View file

@ -11,6 +11,7 @@ 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;
@ -92,60 +93,60 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
}
@Override
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.put("modules", this.modules.serializeNBT());
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) {
super.saveAdditional(compound, provider);
compound.put("modules", this.modules.serializeNBT(provider));
compound.putInt("module_drop_check", this.moduleDropCheck);
compound.put("requests", Utility.serializeAll(this.craftIngredientRequests));
compound.put("requests", Utility.serializeAll(provider, 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(new CompoundTag()));
nbt.put("item", triple.getRight().save(provider));
results.add(nbt);
}
compound.put("craft_results", results);
}
@Override
public void load(CompoundTag compound) {
this.modules.deserializeNBT(compound.getCompound("modules"));
public void loadAdditional(CompoundTag compound, HolderLookup.Provider provider) {
this.modules.deserializeNBT(provider, 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), NetworkLock::new));
this.craftIngredientRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), l -> new NetworkLock(provider, l)));
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.of(nbt.getCompound("item"))));
BlockPos.of(nbt.getLong("dest_pipe")),
ItemStack.parseOptional(provider, nbt.getCompound("item"))));
}
super.load(compound);
super.loadAdditional(compound, provider);
}
@Override
public CompoundTag getUpdateTag() {
public CompoundTag getUpdateTag(HolderLookup.Provider provider) {
// sync pipe items on load
var nbt = this.saveWithoutMetadata();
nbt.put("items", Utility.serializeAll(this.getItems()));
var nbt = this.saveWithoutMetadata(provider);
nbt.put("items", Utility.serializeAll(provider, this.getItems()));
return nbt;
}
@Override
public void handleUpdateTag(CompoundTag nbt) {
this.load(nbt);
public void handleUpdateTag(CompoundTag nbt, HolderLookup.Provider provider) {
this.loadWithComponents(nbt, provider);
var items = this.getItems();
items.clear();
items.addAll(Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load));
items.addAll(Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), d -> IPipeItem.load(provider, d)));
}
@Override
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
this.load(pkt.getTag());
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider provider) {
this.loadWithComponents(pkt.getTag(), provider);
}
public List<IPipeItem> getItems() {
@ -279,8 +280,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) {
@ -373,8 +374,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 = new ResourceLocation(PrettyPipes.ID, "textures/gui/pipe.png");
protected static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(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.SERVER.noArg().send(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, this.index));
PacketDistributor.sendToServer(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, List.of(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);
super(name, new Properties());
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);
super(name, new Properties());
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");
super("redstone_module", new Properties());
}
@Override
@ -25,4 +25,5 @@ public class RedstoneModuleItem extends ModuleItem {
public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false;
}
}

View file

@ -1,9 +1,12 @@
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;
@ -13,7 +16,7 @@ public class SortingModuleItem extends ModuleItem {
private final Type type;
public SortingModuleItem(String name, Type type) {
super(name);
super(name, new Properties());
this.type = type;
}
@ -32,8 +35,9 @@ public class SortingModuleItem extends ModuleItem {
switch (this.type) {
case ROUND_ROBIN:
// store an ever-increasing index and choose destinations based on that
var next = module.hasTag() ? module.getTag().getInt("last") + 1 : 0;
module.getOrCreateTag().putInt("last", next);
var prevData = module.get(Data.TYPE);
var next = prevData != null ? prevData.last + 1 : 0;
module.set(Data.TYPE, new Data(next));
return next % nodes.size();
case RANDOM:
return tile.getLevel().random.nextInt(nodes.size());
@ -45,4 +49,12 @@ 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);
super(name, new Properties());
this.speedIncrease = tier.forTier(0.05F, 0.1F, 0.2F);
}
@ -29,4 +29,5 @@ public class SpeedModuleItem extends ModuleItem {
public float getItemSpeedIncrease(ItemStack module, PipeBlockEntity tile) {
return this.speedIncrease;
}
}

View file

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

View file

@ -1,6 +1,9 @@
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;
@ -14,6 +17,7 @@ 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;
@ -29,14 +33,10 @@ 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);
this.inputSlots = tier.forTier(1, 4, 9);
this.outputSlots = tier.forTier(1, 2, 4);
super(name, new Properties().component(Contents.TYPE, new Contents(new ItemStackHandler(tier.forTier(1, 4, 9)), new ItemStackHandler(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 = this.getOutput(module);
var output = module.get(Contents.TYPE).output;
for (var i = 0; i < output.getSlots(); i++) {
var stack = output.getStackInSlot(i);
if (!stack.isEmpty())
@ -141,15 +141,14 @@ public class CraftingModuleItem extends ModuleItem {
var network = PipeNetwork.get(tile.getLevel());
var items = network.getOrderedNetworkItems(tile.getBlockPos());
var equalityTypes = ItemFilter.getEqualityTypes(tile);
var input = this.getInput(module);
var content = module.get(Contents.TYPE);
var craftable = 0;
var output = this.getOutput(module);
for (var i = 0; i < output.getSlots(); i++) {
var out = output.getStackInSlot(i);
for (var i = 0; i < content.output.getSlots(); i++) {
var out = content.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, input.getSlots(), input::getStackInSlot, k -> true, s -> items, unavailableConsumer, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes);
var availableCrafts = CraftingTerminalBlockEntity.getAvailableCrafts(tile, content.input.getSlots(), content.input::getStackInSlot, k -> true, s -> items, unavailableConsumer, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes);
if (availableCrafts > 0)
craftable += out.getCount() * availableCrafts;
}
@ -174,7 +173,7 @@ public class CraftingModuleItem extends ModuleItem {
var craftableCrafts = Mth.ceil(craftableAmount / (float) resultAmount);
var toCraft = Math.min(craftableCrafts, requiredCrafts);
var input = this.getInput(module);
var input = module.get(Contents.TYPE).input;
for (var i = 0; i < input.getSlots(); i++) {
var in = input.getStackInSlot(i);
if (in.isEmpty())
@ -195,30 +194,8 @@ 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 = this.getOutput(module);
var output = module.get(Contents.TYPE).output;
var resultAmount = 0;
for (var i = 0; i < output.getSlots(); i++) {
var out = output.getStackInSlot(i);
@ -233,4 +210,15 @@ 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);
super(name, new Properties());
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");
super("filter_increase_modifier", new Properties());
}
@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.getSlots() / 9F) + 2;
var buttonsY = this.topPos + 17 + 32 + 18 * Mth.ceil(this.menu.filter.content.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);
super(name, new Properties());
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.getSlots(); i++) {
var stack = filter.getStackInSlot(i);
for (var i = 0; i < filter.content.getSlots(); i++) {
var stack = filter.content.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, FilterModifierModuleGui.this.tags.indexOf(this.tag));
PacketButton.sendAndExecute(FilterModifierModuleGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.TAG_FILTER, List.of(FilterModifierModuleGui.this.tags.indexOf(this.tag)));
FilterModifierModuleGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true;
}

View file

@ -1,12 +1,14 @@
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 joptsimple.internal.Strings;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
@ -17,7 +19,7 @@ public class FilterModifierModuleItem extends ModuleItem {
public final ItemEquality.Type type;
public FilterModifierModuleItem(String name, ItemEquality.Type type) {
super(name);
super(name, new Properties());
this.type = type;
}
@ -45,15 +47,21 @@ public class FilterModifierModuleItem extends ModuleItem {
}
public static ResourceLocation getFilterTag(ItemStack stack) {
if (!stack.hasTag())
return null;
var tag = stack.getTag().getString("filter_tag");
if (Strings.isNullOrEmpty(tag))
return null;
return new ResourceLocation(tag);
var data = stack.get(Data.TYPE);
return data != null && data.filterTag != null ? ResourceLocation.parse(data.filterTag) : null;
}
public static void setFilterTag(ItemStack stack, ResourceLocation tag) {
stack.getOrCreateTag().putString("filter_tag", tag.toString());
stack.set(Data.TYPE, new Data(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);
super(name, new Properties());
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.getSlots(); i++) {
var filtered = f.getStackInSlot(i);
for (var i = 0; i < f.content.getSlots(); i++) {
var filtered = f.content.getStackInSlot(i);
if (filtered.isEmpty())
continue;
var copy = filtered.copy();

View file

@ -11,6 +11,7 @@ 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> {
@ -34,17 +35,18 @@ public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer
}
});
textField.setValue(String.valueOf(StackSizeModuleItem.getMaxStackSizeForModule(this.menu.moduleStack)));
var data = this.menu.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT);
textField.setValue(String.valueOf(data.maxStackSize()));
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, amount);
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_AMOUNT, List.of(amount));
});
Supplier<Component> buttonText = () -> Component.translatable("info." + PrettyPipes.ID + ".limit_to_max_" + (StackSizeModuleItem.getLimitToMaxStackSize(this.menu.moduleStack) ? "on" : "off"));
Supplier<Component> buttonText = () -> Component.translatable("info." + PrettyPipes.ID + ".limit_to_max_" + (data.limitToMaxStackSize() ? "on" : "off"));
this.addRenderableWidget(Button.builder(buttonText.get(), b -> {
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON);
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON, List.of());
b.setMessage(buttonText.get());
}).bounds(this.leftPos + 7, this.topPos + 17 + 32 + 10 + 22, 120, 20).build());
}
@ -55,4 +57,5 @@ 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,5 +1,7 @@
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;
@ -7,6 +9,7 @@ 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;
@ -15,37 +18,15 @@ import net.neoforged.neoforge.items.IItemHandler;
public class StackSizeModuleItem extends ModuleItem {
public StackSizeModuleItem() {
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);
super("stack_size_module", new Properties());
}
@Override
public int getMaxInsertionAmount(ItemStack module, PipeBlockEntity tile, ItemStack stack, IItemHandler destination) {
var types = ItemFilter.getEqualityTypes(tile);
var max = StackSizeModuleItem.getMaxStackSizeForModule(module);
if (StackSizeModuleItem.getLimitToMaxStackSize(module))
var data = module.getOrDefault(Data.TYPE, Data.DEFAULT);
var max = data.maxStackSize;
if (data.limitToMaxStackSize)
max = Math.min(max, stack.getMaxStackSize());
var amount = 0;
for (var i = 0; i < destination.getSlots(); i++) {
@ -76,4 +57,16 @@ 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,12 +6,11 @@ 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;
@ -22,7 +21,6 @@ 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 {
@ -39,7 +37,7 @@ public class PressurizerBlock extends BaseEntityBlock {
}
@Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
public InteractionResult useWithoutItem(BlockState state, Level worldIn, BlockPos pos, Player player, BlockHitResult result) {
var tile = Utility.getBlockEntity(PressurizerBlockEntity.class, worldIn, pos);
if (tile == null)
return InteractionResult.PASS;
@ -60,8 +58,8 @@ public class PressurizerBlock extends BaseEntityBlock {
}
@Override
public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), tooltip);
public void appendHoverText(ItemStack pStack, Item.TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), pTooltipComponents);
}
@org.jetbrains.annotations.Nullable

View file

@ -8,6 +8,7 @@ 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;
@ -51,30 +52,30 @@ public class PressurizerBlockEntity extends BlockEntity implements MenuProvider,
}
@Override
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) {
super.saveAdditional(compound, provider);
compound.putInt("energy", this.getEnergy());
}
@Override
public void load(CompoundTag nbt) {
public void loadAdditional(CompoundTag nbt, HolderLookup.Provider provider) {
this.storage.setEnergyStored(nbt.getInt("energy"));
super.load(nbt);
super.loadAdditional(nbt, provider);
}
@Override
public CompoundTag getUpdateTag() {
return this.saveWithoutMetadata();
public CompoundTag getUpdateTag(HolderLookup.Provider provider) {
return this.saveWithoutMetadata(provider);
}
@Override
public void handleUpdateTag(CompoundTag tag) {
this.load(tag);
public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider provider) {
this.loadWithComponents(tag, provider);
}
@Override
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
this.load(pkt.getTag());
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider provider) {
this.loadWithComponents(pkt.getTag(), provider);
}
@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 = new ResourceLocation(PrettyPipes.ID, "textures/gui/pressurizer.png");
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/pressurizer.png");
public PressurizerGui(PressurizerContainer screenContainer, Inventory inv, Component titleIn) {
super(screenContainer, inv, titleIn);

View file

@ -13,13 +13,16 @@ 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;
@ -76,8 +79,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) {
@ -97,8 +100,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(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));
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));
}
}
@ -110,7 +113,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 -> ItemHandlerHelper.copyStackWithSize(this.getRequestedCraftItem(i), 1), this::isGhostItem, s -> {
var lowestAvailable = CraftingTerminalBlockEntity.getAvailableCrafts(pipe, this.craftItems.getSlots(), i -> this.getRequestedCraftItem(i).copyWithCount(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);
@ -137,15 +140,15 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
}
@Override
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.put("craft_items", this.craftItems.serializeNBT());
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) {
super.saveAdditional(compound, provider);
compound.put("craft_items", this.craftItems.serializeNBT(provider));
}
@Override
public void load(CompoundTag compound) {
this.craftItems.deserializeNBT(compound.getCompound("craft_items"));
super.load(compound);
public void loadAdditional(CompoundTag compound, HolderLookup.Provider provider) {
this.craftItems.deserializeNBT(provider, compound.getCompound("craft_items"));
super.loadAdditional(compound, provider);
}
@Override
@ -170,7 +173,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 (!ItemHandlerHelper.canItemStacksStack(stack, remain))
if (!ItemStack.isSameItemSameComponents(stack, remain))
continue;
// ensure that a single non-stackable item can still enter a ghost slot
if (!stack.isStackable() && count >= 1)

View file

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

View file

@ -17,6 +17,7 @@ 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;
@ -108,8 +109,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)
@ -146,17 +147,17 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
}
}
public void requestItem(Player player, ItemStack stack, int nbtHash) {
public void requestItem(Player player, ItemStack stack, int componentsHash) {
var network = PipeNetwork.get(this.level);
network.startProfile("terminal_request_item");
this.updateItems();
if (nbtHash != 0) {
if (componentsHash != 0) {
var filter = stack;
stack = this.networkItems.values().stream()
.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);
.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);
stack.setCount(filter.getCount());
}
var requested = this.requestItemImpl(stack, ItemTerminalBlockEntity.onItemUnavailable(player, false));
@ -228,18 +229,18 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
}
@Override
public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound);
compound.put("items", this.items.serializeNBT());
compound.put("requests", Utility.serializeAll(this.existingRequests));
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));
}
@Override
public void load(CompoundTag compound) {
this.items.deserializeNBT(compound.getCompound("items"));
protected void loadAdditional(CompoundTag compound, HolderLookup.Provider pRegistries) {
this.items.deserializeNBT(pRegistries, compound.getCompound("items"));
this.existingRequests.clear();
this.existingRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), NetworkLock::new));
super.load(compound);
this.existingRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), l -> new NetworkLock(pRegistries, l)));
super.loadAdditional(compound, pRegistries);
}
@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, this.player.level());
var optional = this.player.level().getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, this.craftInventory.asCraftInput(), this.player.level());
if (optional.isPresent())
ret = optional.get().value().assemble(this.craftInventory, this.player.level().registryAccess());
ret = optional.get().value().assemble(this.craftInventory.asCraftInput(), this.player.level().registryAccess());
this.craftResult.setItem(0, ret);
((ServerPlayer) this.player).connection.send(new ClientboundContainerSetSlotPacket(this.containerId, 0, 0, ret));
}

View file

@ -11,9 +11,11 @@ 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 = new ResourceLocation(PrettyPipes.ID, "textures/gui/crafting_terminal.png");
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/crafting_terminal.png");
private Button requestButton;
public CraftingTerminalGui(ItemTerminalContainer screenContainer, Inventory inv, Component titleIn) {
@ -28,7 +30,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.SERVER.noArg().send(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, amount, force));
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, Arrays.asList(amount, force)));
}).bounds(this.leftPos + 8, this.topPos + 100, 50, 20).build());
this.tick();
}

View file

@ -20,6 +20,7 @@ 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;
@ -29,9 +30,10 @@ 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 = new ResourceLocation(PrettyPipes.ID, "textures/gui/item_terminal.png");
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/item_terminal.png");
public List<ItemStack> currentlyCrafting;
public EditBox search;
@ -91,7 +93,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
return;
var stack = widget.get().stack.copy();
stack.setCount(1);
PacketDistributor.SERVER.noArg().send(new PacketRequest(this.menu.tile.getBlockPos(), stack, this.requestAmount));
PacketDistributor.sendToServer(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;
@ -159,7 +161,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.SERVER.noArg().send(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING));
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING, List.of()));
return true;
}
}
@ -232,7 +234,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
search = search.substring(1);
} else if (search.startsWith("#")) {
// search item description
var hoverText = s.getLeft().getTooltipLines(this.minecraft.player,
var hoverText = s.getLeft().getTooltipLines(Item.TooltipContext.of(this.minecraft.level), 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);