diff --git a/Makefile b/Makefile index cfce1a2..0c908b1 100644 --- a/Makefile +++ b/Makefile @@ -30,30 +30,30 @@ default: mod all: clean clean-all mod | install mod: - @echo "[1.18] Building mod using gradle ..." + @echo "[1.19] Building mod using gradle ..." @$(GRADLE) build $(GRADLE_OPTS) run: - @echo "[1.18] Run client ..." + @echo "[1.19] Run client ..." @$(GRADLE) runClient assets: - @echo "[1.18] Running asset generators ..." + @echo "[1.19] Running asset generators ..." @$(TASK) assets data: - @echo "[1.18] Running data generators ..." + @echo "[1.19] Running data generators ..." @$(TASK) datagen clean: - @echo "[1.18] Cleaning ..." + @echo "[1.19] Cleaning ..." @rm -rf src/generated @rm -rf mcmodsrepo @rm -f build/libs/* @$(GRADLE) clean clean-all: - @echo "[1.18] Cleaning using gradle ..." + @echo "[1.19] Cleaning using gradle ..." @rm -rf mcmodsrepo @rm -f dist/* @rm -rf run/logs/ @@ -68,12 +68,12 @@ mrproper: clean-all @rm -f .classpath init: - @echo "[1.18] Initialising eclipse workspace using gradle ..." + @echo "[1.19] Initialising eclipse workspace using gradle ..." @$(GRADLE) eclipse -@$(GRADLE) hideOfficialWarningUntilChanged sanitize: - @echo "[1.18] Running sanitising tasks ..." + @echo "[1.19] Running sanitising tasks ..." @$(TASK) sanitize @$(TASK) sync-languages @$(TASK) version-check @@ -87,11 +87,11 @@ start-server: install @$(TASK) start-server dist-check: - @echo "[1.18] Running dist checks ..." + @echo "[1.19] Running dist checks ..." @$(TASK) dist-check dist-files: clean-all init mod - @echo "[1.18] Distribution files ..." + @echo "[1.19] Distribution files ..." @mkdir -p dist @cp build/libs/$(MOD_JAR_PREFIX)* dist/ @$(TASK) dist diff --git a/build.gradle b/build.gradle index 3ae1b19..d6552f6 100644 --- a/build.gradle +++ b/build.gradle @@ -1,17 +1,10 @@ // @file build.gradle // Engineer's decor mod gradle build. -buildscript { - repositories { - maven { url = 'https://maven.minecraftforge.net' } - mavenCentral() - } - dependencies { - classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true - } +plugins { + id 'eclipse' + id 'maven-publish' + id 'net.minecraftforge.gradle' version '5.1.+' } -apply plugin: 'net.minecraftforge.gradle' -apply plugin: 'eclipse' -apply plugin: 'maven-publish' java.toolchain.languageVersion = JavaLanguageVersion.of(17) //----------------------------------------------------------------------------- version = "${version_engineersdecor}" @@ -43,8 +36,8 @@ minecraft { dependencies { minecraft "net.minecraftforge:forge:${version_forge_minecraft}" - compileOnly fg.deobf("mezz.jei:jei-${version_jei}:api") - runtimeOnly fg.deobf("mezz.jei:jei-${version_jei}") + //compileOnly fg.deobf("mezz.jei:jei-${version_jei}:api") + //runtimeOnly fg.deobf("mezz.jei:jei-${version_jei}") } processResources { @@ -86,3 +79,7 @@ project.afterEvaluate { } reobfJar.finalizedBy('signJar') } + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' +} diff --git a/gradle.properties b/gradle.properties index 765dd8c..2f90b0c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ org.gradle.jvmargs=-Xmx8G meta_modid=engineersdecor meta_issues=https://github.com/stfwi/engineers-decor/issues meta_download=https://www.curseforge.com/minecraft/mc-mods/engineers-decor/ -version_minecraft=1.18.2 -version_forge_minecraft=1.18.2-40.1.51 -version_jei=1.18.2:9.5.4.171 -version_engineersdecor=1.1.23 +version_minecraft=1.19 +version_forge_minecraft=1.19-41.0.35 +version_jei=1.19:11.0.0.206 +version_engineersdecor=1.1.24-b1 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180..41d9927 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e750102..aa991fc 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 744e882..1b6c787 100644 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or 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. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# 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». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# 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 +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +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"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MSYS* | MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + 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. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + 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. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/meta/update.json b/meta/update.json index 2de83d7..002d1f3 100644 --- a/meta/update.json +++ b/meta/update.json @@ -1,6 +1,7 @@ { "homepage": "https://www.curseforge.com/minecraft/mc-mods/engineers-decor/", - "1.18.2": { + "1.19": { + "1.1.24-b1": "[U] Initial 1.19 port.\n[D] Metal/Treated Wood Crafting Table dropped in favour of IE Engineer's Crafting Table.\n[D] Labeled Crate dropped.\n[D] Obsolete wood blocks dropped.", "1.1.23": "[R] Release build.\n[F] Updated Forge and re-enabled JSON tags (issue #217, ty snarkbait66).", "1.1.23-b1": "[A] Added ability to install inset lights in top-aligned catwalks (PR#215, Sergii).\n[A] Iron Hatch improved (PR#216, Sergii).", "1.1.22": "[R] Release build v1.1.22.\n[M] Factory Dropper stack size ignored for un-stackable items (issue #209, ty LesBeans).", @@ -57,7 +58,7 @@ "1.1.2-b1": "[U] Ported to MC1.16.2." }, "promos": { - "1.18.2-recommended": "1.1.23", - "1.18.2-latest": "1.1.23" + "1.19-recommended": "1.1.23", + "1.19-latest": "1.1.24-b1" } } \ No newline at end of file diff --git a/readme.md b/readme.md index e432d84..c274204 100644 --- a/readme.md +++ b/readme.md @@ -11,6 +11,11 @@ Mod sources for Minecraft version 1.18.x. ## Version history + - v1.1.24-b1 [U] Initial 1.19 port. + [D] Metal/Treated Wood Crafting Table dropped in favour of IE Engineer's Crafting Table. + [D] Labeled Crate dropped. + [D] Obsolete wood blocks dropped. + - v1.1.23 [R] Release build. [F] Updated Forge and re-enabled JSON tags (issue #217, ty snarkbait66). diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..fb61b26 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,6 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { url = 'https://maven.minecraftforge.net/' } + } +} \ No newline at end of file diff --git a/src/main/java/wile/engineersdecor/ModConfig.java b/src/main/java/wile/engineersdecor/ModConfig.java index f3bca66..b07d44f 100644 --- a/src/main/java/wile/engineersdecor/ModConfig.java +++ b/src/main/java/wile/engineersdecor/ModConfig.java @@ -16,7 +16,6 @@ import net.minecraftforge.common.ForgeConfigSpec; import org.apache.commons.lang3.tuple.Pair; import wile.engineersdecor.blocks.*; import wile.engineersdecor.libmc.blocks.SlabSliceBlock; -import wile.engineersdecor.libmc.blocks.StandardBlocks; import wile.engineersdecor.libmc.blocks.VariantSlabBlock; import wile.engineersdecor.libmc.detail.Auxiliaries; import wile.engineersdecor.libmc.detail.OptionalRecipeCondition; @@ -324,7 +323,7 @@ public class ModConfig { return (block==null) || isOptedOut(block.asItem()); } public static boolean isOptedOut(final @Nullable Item item) - { return (item!=null) && optouts_.contains(item.getRegistryName().getPath()); } + { return (item!=null) && optouts_.contains(Auxiliaries.getResourceLocation(item).getPath()); } public static boolean withExperimental() { return with_experimental_features_; } @@ -385,14 +384,9 @@ public class ModConfig try { if(!with_experimental_features_) { if(block instanceof Auxiliaries.IExperimentalFeature) return true; - if(ModContent.isExperimentalBlock(block)) return true; - } - // Hard IE dependent blocks - if(!immersiveengineering_installed) { - if((block instanceof StandardBlocks.IStandardBlock) && ((((StandardBlocks.IStandardBlock)block).config() & DecorBlock.CFG_HARD_IE_DEPENDENT)!=0)) return true; } // Force-include/exclude pattern matching - final String rn = block.getRegistryName().getPath(); + final String rn = Auxiliaries.getResourceLocation(block).getPath(); try { for(String e : includes) { if(rn.matches(e)) { @@ -416,7 +410,7 @@ public class ModConfig } return false; }).forEach( - e -> optouts.add(e.getRegistryName().getPath()) + e -> optouts.add(Auxiliaries.getResourceLocation(e).getPath()) ); optouts_ = optouts; } @@ -439,8 +433,6 @@ public class ModConfig EdLadderBlock.on_config(SERVER.without_ladder_speed_boost.get()); VariantSlabBlock.on_config(!SERVER.without_direct_slab_pickup.get()); SlabSliceBlock.on_config(!SERVER.without_direct_slab_pickup.get()); - EdLabeledCrate.on_config(false); - EdCraftingTable.on_config(SERVER.without_crafting_table_history.get(), false, SERVER.without_crafting_mouse_scrolling.get()); EdFluidBarrel.on_config(12000, 1000); EdFluidFunnel.on_config(with_experimental_features_); EdPipeValve.on_config(SERVER.pipevalve_max_flowrate.get(), SERVER.pipevalve_redstone_gain.get()); diff --git a/src/main/java/wile/engineersdecor/ModContent.java b/src/main/java/wile/engineersdecor/ModContent.java index 087ebbd..f105ef1 100644 --- a/src/main/java/wile/engineersdecor/ModContent.java +++ b/src/main/java/wile/engineersdecor/ModContent.java @@ -15,7 +15,6 @@ package wile.engineersdecor; import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.entity.EntityRenderers; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -40,7 +39,6 @@ import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import wile.engineersdecor.blocks.*; import wile.engineersdecor.detail.ModRenderers; @@ -292,10 +290,6 @@ public class ModContent StandardBlocks.CFG_DEFAULT, BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 8f).sound(SoundType.METAL).noOcclusion() )); - Registries.addBlock("treated_wood_ladder", ()->new EdLadderBlock( - StandardBlocks.CFG_DEFAULT, - BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.3f, 8f).sound(SoundType.WOOD).noOcclusion() - )); Registries.addBlock("iron_hatch", ()->new EdHatchBlock( StandardBlocks.CFG_LOOK_PLACEMENT, BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 2000f).sound(SoundType.METAL), @@ -356,11 +350,6 @@ public class ModContent // ------------------------------------------------------------------------------------------------------------------- - Registries.addBlock("treated_wood_table", ()->new StandardBlocks.WaterLoggable( - StandardBlocks.CFG_CUTOUT, - BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.5f, 5f).sound(SoundType.WOOD).noOcclusion(), - Auxiliaries.getPixeledAABB(1,0,1, 15,15.9,15) - )); Registries.addBlock("treated_wood_stool", ()->new EdChair.ChairBlock( StandardBlocks.CFG_CUTOUT|StandardBlocks.CFG_HORIZIONTAL|StandardBlocks.CFG_LOOK_PLACEMENT, BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.5f, 5f).sound(SoundType.WOOD).noOcclusion(), @@ -371,16 +360,6 @@ public class ModContent Auxiliaries.getPixeledAABB(7,0,4, 9,1,12), } )); - Registries.addBlock("treated_wood_windowsill", ()->new StandardBlocks.DirectedWaterLoggable( - StandardBlocks.CFG_CUTOUT|StandardBlocks.CFG_HORIZIONTAL|StandardBlocks.CFG_FACING_PLACEMENT|StandardBlocks.CFG_AI_PASSABLE, - BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.5f, 5f).sound(SoundType.WOOD).noOcclusion(), - Auxiliaries.getPixeledAABB(0.5,15,10.5, 15.5,16,16) - )); - Registries.addBlock("treated_wood_broad_windowsill", ()->new StandardBlocks.DirectedWaterLoggable( - StandardBlocks.CFG_CUTOUT|StandardBlocks.CFG_HORIZIONTAL|StandardBlocks.CFG_FACING_PLACEMENT, - BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.5f, 5f).sound(SoundType.WOOD).noOcclusion(), - Auxiliaries.getPixeledAABB(0,14.5,4, 16,16,16) - )); // ------------------------------------------------------------------------------------------------------------------- @@ -432,11 +411,6 @@ public class ModContent // ------------------------------------------------------------------------------------------------------------------- - Registries.addBlock("treated_wood_window", ()->new EdWindowBlock( - StandardBlocks.CFG_LOOK_PLACEMENT, - BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.5f, 8f).sound(SoundType.WOOD).noOcclusion(), - Auxiliaries.getPixeledAABB(0,0,7, 16,16,9) - )); Registries.addBlock("steel_framed_window", ()->new EdWindowBlock( StandardBlocks.CFG_LOOK_PLACEMENT, BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.5f, 8f).sound(SoundType.METAL).noOcclusion(), @@ -642,37 +616,9 @@ public class ModContent BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.2f, 1f).sound(SoundType.WOOD).noOcclusion(), Auxiliaries.getPixeledAABB(2,2,15.6, 14,14,16) )); - Registries.addBlock("sign_factoryarea", ()->new StandardBlocks.DirectedWaterLoggable( - StandardBlocks.CFG_CUTOUT|StandardBlocks.CFG_FACING_PLACEMENT|StandardBlocks.CFG_HORIZIONTAL|StandardBlocks.CFG_AI_PASSABLE, - BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.2f, 1f).sound(SoundType.WOOD).noOcclusion(), - Auxiliaries.getPixeledAABB(2,2,15.6, 14,14,16) - )); // ------------------------------------------------------------------------------------------------------------------- - Registries.addBlock("labeled_crate", - ()->new EdLabeledCrate.LabeledCrateBlock( - StandardBlocks.CFG_HORIZIONTAL|StandardBlocks.CFG_LOOK_PLACEMENT|StandardBlocks.CFG_OPPOSITE_PLACEMENT, - BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.3f, 32f).sound(SoundType.METAL).noOcclusion(), - Auxiliaries.getPixeledAABB(0,0,0, 16,16,16) - ), - EdLabeledCrate.LabeledCrateTileEntity::new, - EdLabeledCrate.LabeledCrateContainer::new - ); - Registries.addBlock("metal_crafting_table", - ()->new EdCraftingTable.CraftingTableBlock( - StandardBlocks.CFG_CUTOUT|StandardBlocks.CFG_HORIZIONTAL|StandardBlocks.CFG_LOOK_PLACEMENT|StandardBlocks.CFG_OPPOSITE_PLACEMENT, - BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 12f).sound(SoundType.METAL).noOcclusion(), - new AABB[]{ - Auxiliaries.getPixeledAABB(0,15,0, 16,16,16), - Auxiliaries.getPixeledAABB(1, 0,1, 15,16,15) - } - ), - EdCraftingTable.CraftingTableTileEntity::new, - EdCraftingTable.CraftingTableUiContainer::new - //MenuScreens.register(CT_TREATED_WOOD_CRAFTING_TABLE, EdCraftingTable.CraftingTableGui::new); - ); - Registries.addBlock("small_lab_furnace", ()->new EdFurnace.FurnaceBlock( StandardBlocks.CFG_CUTOUT|StandardBlocks.CFG_HORIZIONTAL|StandardBlocks.CFG_LOOK_PLACEMENT|StandardBlocks.CFG_OPPOSITE_PLACEMENT, @@ -902,6 +848,7 @@ public class ModContent Auxiliaries.getPixeledAABB(2,15,0, 14,16,16), } ), + EdFluidBarrel.FluidBarrelItem::new, EdFluidBarrel.FluidBarrelTileEntity::new ); Registries.addBlock("small_fluid_funnel", @@ -919,35 +866,6 @@ public class ModContent // ------------------------------------------------------------------------------------------------------------------- - if(Auxiliaries.isModLoaded("immersiveengineeringharddependent")) { - //Registries.addBlock("halfslab_treated_wood", ()->new SlabSliceBlock( - // StandardBlocks.CFG_CUTOUT|DecorBlock.CFG_HARD_IE_DEPENDENT, - // BlockBehaviour.Properties.of(Material.WOOD, MaterialColor.WOOD).strength(0.3f, 4f).sound(SoundType.WOOD).noOcclusion() - //)); - //Registries.addBlock("halfslab_sheetmetal_iron", ()->new SlabSliceBlock( - // StandardBlocks.CFG_CUTOUT|DecorBlock.CFG_HARD_IE_DEPENDENT, - // BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 8f).sound(SoundType.METAL).noOcclusion() - //)); - //Registries.addBlock("halfslab_sheetmetal_steel", ()->new SlabSliceBlock( - // StandardBlocks.CFG_CUTOUT|DecorBlock.CFG_HARD_IE_DEPENDENT, - // BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 8f).sound(SoundType.METAL).noOcclusion() - //)); - //Registries.addBlock("halfslab_sheetmetal_copper", ()->new SlabSliceBlock( - // StandardBlocks.CFG_CUTOUT|DecorBlock.CFG_HARD_IE_DEPENDENT, - // BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 8f).sound(SoundType.METAL).noOcclusion() - //)); - //Registries.addBlock("halfslab_sheetmetal_gold", ()->new SlabSliceBlock( - // StandardBlocks.CFG_CUTOUT|DecorBlock.CFG_HARD_IE_DEPENDENT, - // BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 8f).sound(SoundType.METAL).noOcclusion() - //)); - //Registries.addBlock("halfslab_sheetmetal_aluminum", ()->new SlabSliceBlock( - // StandardBlocks.CFG_CUTOUT|DecorBlock.CFG_HARD_IE_DEPENDENT, - // BlockBehaviour.Properties.of(Material.METAL, MaterialColor.METAL).strength(0.3f, 8f).sound(SoundType.METAL).noOcclusion() - //)); - } - - // ------------------------------------------------------------------------------------------------------------------- - Registries.addBlock("test_block", ()->new EdTestBlock.TestBlock( StandardBlocks.CFG_LOOK_PLACEMENT, @@ -994,16 +912,15 @@ public class ModContent public static BlockEntityType getBlockEntityTypeOfBlock(String block_name) { return Registries.getBlockEntityTypeOfBlock(block_name); } + public static BlockEntityType getBlockEntityTypeOfBlock(Block block) + { return Registries.getBlockEntityTypeOfBlock(block); } + public static EntityType getEntityType(String name) { return Registries.getEntityType(name); } public static MenuType getMenuType(String block_name) { return Registries.getMenuTypeOfBlock(block_name); } - @SuppressWarnings("deprecation") - public static boolean isExperimentalBlock(Block block) - { return (block instanceof StandardBlocks.IStandardBlock) && (((((StandardBlocks.IStandardBlock)block).config() & DecorBlock.CFG_EXPERIMENTAL))!=0); } - @Nonnull public static List getRegisteredBlocks() { return Registries.getRegisteredBlocks(); } @@ -1016,31 +933,10 @@ public class ModContent // Initialisation events //-------------------------------------------------------------------------------------------------------------------- - public static void registerBlocks(final RegistryEvent.Register event) - { - final boolean ie_available = Auxiliaries.isModLoaded("immersiveengineering"); - if(ie_available) Auxiliaries.logInfo("Immersive Engineering also installed ..."); - Registries.onBlockRegistry((rl, block)->event.getRegistry().register(block)); - } - - public static void registerItems(final RegistryEvent.Register event) - { Registries.onItemRegistry((rl, item)->event.getRegistry().register(item)); } - - public static void registerBlockEntityTypes(final RegistryEvent.Register> event) - { Registries.onBlockEntityRegistry((rl, tet)->event.getRegistry().register(tet)); } - - public static void registerEntityTypes(final RegistryEvent.Register> event) - { Registries.onEntityRegistry((rl, et)->event.getRegistry().register(et)); } - - public static void registerMenuTypes(final RegistryEvent.Register> event) - { Registries.onMenuTypeRegistry((rl, ct)->event.getRegistry().register(ct)); } - @OnlyIn(Dist.CLIENT) @SuppressWarnings("unchecked") public static void registerMenuGuis(final FMLClientSetupEvent event) { - MenuScreens.register((MenuType)Registries.getMenuTypeOfBlock("metal_crafting_table"), EdCraftingTable.CraftingTableGui::new); - MenuScreens.register((MenuType)Registries.getMenuTypeOfBlock("labeled_crate"), EdLabeledCrate.LabeledCrateGui::new); MenuScreens.register((MenuType)Registries.getMenuTypeOfBlock("factory_dropper"), EdDropper.DropperGui::new); MenuScreens.register((MenuType)Registries.getMenuTypeOfBlock("factory_placer"), EdPlacer.PlacerGui::new); MenuScreens.register((MenuType)Registries.getMenuTypeOfBlock("factory_hopper"), EdHopper.HopperGui::new); @@ -1053,8 +949,6 @@ public class ModContent @SuppressWarnings("unchecked") public static void registerBlockEntityRenderers(final FMLClientSetupEvent event) { - BlockEntityRenderers.register((BlockEntityType)Registries.getBlockEntityTypeOfBlock("metal_crafting_table"), wile.engineersdecor.detail.ModRenderers.CraftingTableTer::new); - BlockEntityRenderers.register((BlockEntityType)Registries.getBlockEntityTypeOfBlock("labeled_crate"), wile.engineersdecor.detail.ModRenderers.DecorLabeledCrateTer::new); } @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/wile/engineersdecor/ModEngineersDecor.java b/src/main/java/wile/engineersdecor/ModEngineersDecor.java index 4a7accb..0b7d541 100644 --- a/src/main/java/wile/engineersdecor/ModEngineersDecor.java +++ b/src/main/java/wile/engineersdecor/ModEngineersDecor.java @@ -1,14 +1,8 @@ package wile.engineersdecor; -import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; @@ -17,8 +11,7 @@ import net.minecraftforge.fml.event.config.ModConfigEvent; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; import wile.engineersdecor.blocks.EdLadderBlock; import wile.engineersdecor.libmc.detail.Auxiliaries; import wile.engineersdecor.libmc.detail.OptionalRecipeCondition; @@ -31,13 +24,13 @@ public class ModEngineersDecor public static final String MODID = "engineersdecor"; public static final String MODNAME = "Engineer's Decor"; public static final int VERSION_DATAFIXER = 0; - private static final Logger LOGGER = LogManager.getLogger(); + private static final Logger LOGGER = com.mojang.logging.LogUtils.getLogger(); public ModEngineersDecor() { Auxiliaries.init(MODID, LOGGER, ModConfig::getServerConfig); Auxiliaries.logGitVersion(MODNAME); - Registries.init(MODID, "sign_decor"); + Registries.init(MODID, "sign_decor", (reg)->reg.register(FMLJavaModLoadingContext.get().getModEventBus())); ModContent.init(MODID); OptionalRecipeCondition.init(MODID, LOGGER); ModLoadingContext.get().registerConfig(net.minecraftforge.fml.config.ModConfig.Type.SERVER, ModConfig.SERVER_CONFIG_SPEC); @@ -68,26 +61,6 @@ public class ModEngineersDecor @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) public static class ForgeEvents { - @SubscribeEvent - public static void onRegisterBlocks(final RegistryEvent.Register event) - { ModContent.registerBlocks(event); } - - @SubscribeEvent - public static void onRegisterItems(final RegistryEvent.Register event) - { ModContent.registerItems(event); } - - @SubscribeEvent - public static void onRegisterBlockEntityTypes(final RegistryEvent.Register> event) - { ModContent.registerBlockEntityTypes(event); } - - @SubscribeEvent - public static void onRegisterEntityTypes(final RegistryEvent.Register> event) - { ModContent.registerEntityTypes(event); } - - @SubscribeEvent - public static void onRegisterMenuTypes(final RegistryEvent.Register> event) - { ModContent.registerMenuTypes(event); } - @SubscribeEvent public static void onConfigLoad(final ModConfigEvent.Loading event) { ModConfig.apply(); } diff --git a/src/main/java/wile/engineersdecor/blocks/DecorBlock.java b/src/main/java/wile/engineersdecor/blocks/DecorBlock.java deleted file mode 100644 index 9c46917..0000000 --- a/src/main/java/wile/engineersdecor/blocks/DecorBlock.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * @file DecorBlock.java - * @author Stefan Wilhelm (wile) - * @copyright (C) 2020 Stefan Wilhelm - * @license MIT (see https://opensource.org/licenses/MIT) - * - * Common functionality class for decor blocks. - * Mainly needed for: - * - MC block defaults. - * - Tooltip functionality - * - Model initialisation - */ -package wile.engineersdecor.blocks; - -import wile.engineersdecor.libmc.blocks.StandardBlocks; - -public class DecorBlock -{ - public static final long CFG_DEFAULT = StandardBlocks.CFG_DEFAULT; - public static final long CFG_CUTOUT = StandardBlocks.CFG_CUTOUT; - public static final long CFG_MIPPED = StandardBlocks.CFG_MIPPED; - public static final long CFG_TRANSLUCENT = StandardBlocks.CFG_TRANSLUCENT; - public static final long CFG_WATERLOGGABLE = StandardBlocks.CFG_WATERLOGGABLE; - public static final long CFG_HORIZIONTAL = StandardBlocks.CFG_HORIZIONTAL; - public static final long CFG_LOOK_PLACEMENT = StandardBlocks.CFG_LOOK_PLACEMENT; - public static final long CFG_FACING_PLACEMENT = StandardBlocks.CFG_FACING_PLACEMENT; - public static final long CFG_OPPOSITE_PLACEMENT = StandardBlocks.CFG_OPPOSITE_PLACEMENT; - public static final long CFG_FLIP_PLACEMENT_IF_SAME = StandardBlocks.CFG_FLIP_PLACEMENT_IF_SAME; - public static final long CFG_FLIP_PLACEMENT_SHIFTCLICK = StandardBlocks.CFG_FLIP_PLACEMENT_SHIFTCLICK; - public static final long CFG_STRICT_CONNECTIONS = StandardBlocks.CFG_STRICT_CONNECTIONS; - public static final long CFG_AI_PASSABLE = StandardBlocks.CFG_AI_PASSABLE; - public static final long CFG_HARD_IE_DEPENDENT = 0x8000000000000000L; - @Deprecated public static final long CFG_EXPERIMENTAL = 0x4000000000000000L; -} diff --git a/src/main/java/wile/engineersdecor/blocks/EdBreaker.java b/src/main/java/wile/engineersdecor/blocks/EdBreaker.java index 04a005c..7dcd8dc 100644 --- a/src/main/java/wile/engineersdecor/blocks/EdBreaker.java +++ b/src/main/java/wile/engineersdecor/blocks/EdBreaker.java @@ -12,7 +12,6 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; @@ -93,10 +92,6 @@ public class EdBreaker public BreakerBlock(long config, BlockBehaviour.Properties builder, final AABB[] unrotatedAABBs) { super(config, builder, unrotatedAABBs); } - @Override - public ResourceLocation getBlockRegistryName() - { return getRegistryName(); } - @Override public boolean isBlockEntityTicking(Level world, BlockState state) { return true; } @@ -195,7 +190,7 @@ public class EdBreaker private final LazyOptional energy_handler_ = battery_.createEnergyHandler(); public BreakerTileEntity(BlockPos pos, BlockState state) - { super(ModContent.getBlockEntityTypeOfBlock(state.getBlock().getRegistryName().getPath()), pos, state); } + { super(ModContent.getBlockEntityTypeOfBlock(state.getBlock()), pos, state); } public void block_updated() { if(tick_timer_ > 2) tick_timer_ = 2; } diff --git a/src/main/java/wile/engineersdecor/blocks/EdChair.java b/src/main/java/wile/engineersdecor/blocks/EdChair.java index 7562469..f2bde9c 100644 --- a/src/main/java/wile/engineersdecor/blocks/EdChair.java +++ b/src/main/java/wile/engineersdecor/blocks/EdChair.java @@ -13,6 +13,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.network.protocol.Packet; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; @@ -35,8 +36,6 @@ import wile.engineersdecor.ModContent; import wile.engineersdecor.libmc.blocks.StandardBlocks; import java.util.List; -import java.util.Random; - public class EdChair @@ -81,7 +80,7 @@ public class EdChair @Override @SuppressWarnings("deprecation") - public void tick(BlockState state, ServerLevel world, BlockPos pos, Random rnd) + public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource rnd) { if((!sitting_enabled) || (sitting_probability < 1e-6)) return; final List entities = world.getEntitiesOfClass(Mob.class, new AABB(pos).inflate(2,1,2).expandTowards(0,1,0), e->true); diff --git a/src/main/java/wile/engineersdecor/blocks/EdChimneyBlock.java b/src/main/java/wile/engineersdecor/blocks/EdChimneyBlock.java index d3d08a4..2bf8260 100644 --- a/src/main/java/wile/engineersdecor/blocks/EdChimneyBlock.java +++ b/src/main/java/wile/engineersdecor/blocks/EdChimneyBlock.java @@ -11,6 +11,7 @@ package wile.engineersdecor.blocks; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; @@ -30,7 +31,6 @@ import net.minecraftforge.api.distmarker.OnlyIn; import wile.engineersdecor.libmc.blocks.StandardBlocks; import javax.annotation.Nullable; -import java.util.Random; public class EdChimneyBlock extends StandardBlocks.Cutout { @@ -78,7 +78,7 @@ public class EdChimneyBlock extends StandardBlocks.Cutout @Override @OnlyIn(Dist.CLIENT) - public void animateTick(BlockState state, Level world, BlockPos pos, Random rnd) + public void animateTick(BlockState state, Level world, BlockPos pos, RandomSource rnd) { if(state.getBlock() != this) return; final int p = state.getValue(POWER); diff --git a/src/main/java/wile/engineersdecor/blocks/EdCraftingTable.java b/src/main/java/wile/engineersdecor/blocks/EdCraftingTable.java deleted file mode 100644 index f9fc1f4..0000000 --- a/src/main/java/wile/engineersdecor/blocks/EdCraftingTable.java +++ /dev/null @@ -1,1631 +0,0 @@ -/* - * @file EdCraftingTable.java - * @author Stefan Wilhelm (wile) - * @copyright (C) 2020 Stefan Wilhelm - * @license MIT (see https://opensource.org/licenses/MIT) - * - * Crafting table - */ -package wile.engineersdecor.blocks; - -import com.google.common.collect.ImmutableList; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.ImageButton; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.NonNullList; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.Connection; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TextComponent; -import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.Mth; -import net.minecraft.util.Tuple; -import net.minecraft.world.*; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.*; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.crafting.*; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.ticks.TickPriority; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.registries.ForgeRegistries; -import wile.engineersdecor.ModConfig; -import wile.engineersdecor.ModContent; -import wile.engineersdecor.ModEngineersDecor; -import wile.engineersdecor.libmc.blocks.StandardBlocks; -import wile.engineersdecor.libmc.blocks.StandardEntityBlocks; -import wile.engineersdecor.libmc.detail.Auxiliaries; -import wile.engineersdecor.libmc.detail.Inventories; -import wile.engineersdecor.libmc.detail.Inventories.InventoryRange; -import wile.engineersdecor.libmc.detail.Inventories.StorageInventory; -import wile.engineersdecor.libmc.detail.Networking; -import wile.engineersdecor.libmc.detail.TooltipDisplay.TipRange; -import wile.engineersdecor.libmc.ui.Guis; - -import javax.annotation.Nullable; -import java.util.*; -import java.util.stream.Collectors; - - -public class EdCraftingTable -{ - public static boolean with_assist = true; - public static boolean with_assist_direct_history_refab = false; - public static boolean with_crafting_slot_mouse_scrolling = true; - public static boolean with_outslot_defined_refab = true; - - public static void on_config(boolean without_crafting_assist, boolean with_assist_immediate_history_refab, boolean without_crafting_slot_mouse_scrolling) - { - with_assist = !without_crafting_assist; - with_assist_direct_history_refab = with_assist_immediate_history_refab; - with_crafting_slot_mouse_scrolling = !without_crafting_slot_mouse_scrolling; - with_outslot_defined_refab = with_assist; - CraftingHistory.max_history_size(32); - ModConfig.log("Config crafting table: assist:" + with_assist + ", direct-refab:" + with_assist_direct_history_refab + - ", scrolling:"+with_crafting_slot_mouse_scrolling); - } - - //-------------------------------------------------------------------------------------------------------------------- - // Block - //-------------------------------------------------------------------------------------------------------------------- - - public static final class CraftingTableBlock extends StandardBlocks.HorizontalWaterLoggable implements StandardEntityBlocks.IStandardEntityBlock - { - public CraftingTableBlock(long config, BlockBehaviour.Properties builder, final AABB[] unrotatedAABBs) - { super(config, builder, unrotatedAABBs); } - - @Override - public ResourceLocation getBlockRegistryName() - { return getRegistryName(); } - - @Override - public boolean isBlockEntityTicking(Level world, BlockState state) - { return false; } - - @Override - public boolean shouldCheckWeakPower(BlockState state, LevelReader world, BlockPos pos, Direction side) - { return false; } - - @Override - @SuppressWarnings("deprecation") - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult rayTraceResult) - { return useOpenGui(state, world, pos, player); } - - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) - { - if(world.isClientSide) return; - if((!stack.hasTag()) || (!stack.getTag().contains("inventory"))) return; - final CompoundTag inventory_nbt = stack.getTag().getCompound("inventory"); - if(inventory_nbt.isEmpty()) return; - if(!(world.getBlockEntity(pos) instanceof final CraftingTableTileEntity te)) return; - te.readnbt(inventory_nbt); - te.setChanged(); - } - - @Override - public boolean hasDynamicDropList() - { return true; } - - @Override - public List dropList(BlockState state, Level world, final BlockEntity te, boolean explosion) - { - final List stacks = new ArrayList<>(); - if(world.isClientSide) return stacks; - if(!(te instanceof CraftingTableTileEntity)) return stacks; - if(!explosion) { - ItemStack stack = new ItemStack(this, 1); - CompoundTag inventory_nbt = new CompoundTag(); - ((CraftingTableTileEntity)te).mainInventory().save(inventory_nbt, false); - if(!inventory_nbt.isEmpty()) { - CompoundTag nbt = new CompoundTag(); - nbt.put("inventory", inventory_nbt); - stack.setTag(nbt); - } - ((CraftingTableTileEntity) te).mainInventory().clearContent(); - stacks.add(stack); - } else { - for(ItemStack stack: ((CraftingTableTileEntity)te).mainInventory()) { - if(!stack.isEmpty()) stacks.add(stack); - } - ((CraftingTableTileEntity)te).reset(); - } - return stacks; - } - - @Override - @SuppressWarnings("deprecation") - public void tick(BlockState state, ServerLevel world, BlockPos pos, Random rand) - { - BlockEntity te = world.getBlockEntity(pos); - if(!(te instanceof CraftingTableTileEntity)) return; - ((CraftingTableTileEntity)te).sync(); - } - } - - //-------------------------------------------------------------------------------------------------------------------- - // Tile entity - //-------------------------------------------------------------------------------------------------------------------- - - public static class CraftingTableTileEntity extends StandardEntityBlocks.StandardBlockEntity implements MenuProvider, Nameable, Networking.IPacketTileNotifyReceiver - { - public static final int NUM_OF_STORAGE_SLOTS = 18; - public static final int NUM_OF_STORAGE_ROWS = 2; - public static final int NUM_OF_SLOTS = 9+NUM_OF_STORAGE_SLOTS+1; - public static final int CRAFTING_RESULT_SLOT = NUM_OF_SLOTS-1; - - protected Inventories.StorageInventory inventory_; - protected CompoundTag history = new CompoundTag(); - - public CraftingTableTileEntity(BlockPos pos, BlockState state) - { - super(ModContent.getBlockEntityTypeOfBlock(state.getBlock().getRegistryName().getPath()), pos, state); - inventory_ = new StorageInventory(this, NUM_OF_SLOTS, 1); - inventory_.setCloseAction((player)->{ - if(getLevel() instanceof Level) { - scheduleSync(); - getLevel().sendBlockUpdated(getBlockPos(), state, state, 1|2|16); - } - }); - inventory_.setSlotChangeAction((slot_index,stack)-> { - if(slot_index < 9) scheduleSync(); - }); - } - - public void reset() - { inventory_.clearContent(); } - - public void readnbt(CompoundTag nbt) - { reset(); inventory_.load(nbt); history = nbt.getCompound("history"); } - - private void writenbt(CompoundTag nbt) - { - inventory_.save(nbt); - if(!history.isEmpty()) nbt.put("history", history); - } - - public Inventories.StorageInventory mainInventory() - { return inventory_; } - - // BlockEntity ------------------------------------------------------------------------------ - - @Override - public void load(CompoundTag nbt) - { super.load(nbt); readnbt(nbt); } - - @Override - protected void saveAdditional(CompoundTag nbt) - { super.saveAdditional(nbt); writenbt(nbt); } - - @Override - public CompoundTag getUpdateTag() - { CompoundTag nbt = super.getUpdateTag(); writenbt(nbt); return nbt; } - - @Override - @Nullable - public ClientboundBlockEntityDataPacket getUpdatePacket() - { return ClientboundBlockEntityDataPacket.create(this); } - - @Override - public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) // on client - { super.onDataPacket(net, pkt); if(pkt.getTag() != null) { readnbt(pkt.getTag()); } } - - @Override - public void handleUpdateTag(CompoundTag tag) // on client - { load(tag); } - - @OnlyIn(Dist.CLIENT) - public double getViewDistance() - { return 400; } - - // Nameable ---------------------------------------------------------------------------- - - @Override - public Component getName() - { final Block block=getBlockState().getBlock(); return new TextComponent((block!=null) ? block.getDescriptionId() : "Treated wood crafting table"); } - - @Override - public boolean hasCustomName() - { return false; } - - @Override - public Component getCustomName() - { return getName(); } - - // INamedContainerProvider ------------------------------------------------------------------------------ - - @Override - public Component getDisplayName() - { return Nameable.super.getDisplayName(); } - - @Override - public AbstractContainerMenu createMenu( int id, Inventory inventory, Player player ) - { return new CraftingTableUiContainer(id, inventory, inventory_, ContainerLevelAccess.create(level, worldPosition)); } - - @Override - public void onServerPacketReceived(CompoundTag nbt) - { readnbt(nbt); } - - public void sync() - { - if(getLevel().isClientSide()) return; - CompoundTag nbt = new CompoundTag(); - writenbt(nbt); - Networking.PacketTileNotifyServerToClient.sendToPlayers(this, nbt); - } - - public void scheduleSync() - { - if(level.isClientSide()) return; - final Block crafting_table_block = getBlockState().getBlock(); - if(!(crafting_table_block instanceof CraftingTableBlock)) return; - if(level.getBlockTicks().hasScheduledTick(getBlockPos(), crafting_table_block)) return; - level.scheduleTick(getBlockPos(), crafting_table_block, 10, TickPriority.LOW); - } - } - - //-------------------------------------------------------------------------------------------------------------------- - // Crafting container - //-------------------------------------------------------------------------------------------------------------------- - - public static class CraftingTableUiContainer extends AbstractContainerMenu implements Networking.INetworkSynchronisableContainer - { - protected static final String BUTTON_NEXT = "next"; - protected static final String BUTTON_PREV = "prev"; - protected static final String BUTTON_CLEAR_GRID = "clear"; - protected static final String BUTTON_NEXT_COLLISION_RECIPE = "next-recipe"; - protected static final String ACTION_PLACE_CURRENT_HISTORY_SEL = "place-refab"; - protected static final String ACTION_PLACE_SHIFTCLICKED_STACK = "place-stack"; - protected static final String ACTION_MOVE_ALL_STACKS = "move-stacks"; - protected static final String ACTION_MOVE_STACK = "move-stack"; - protected static final String ACTION_INCREASE_CRAFTING_STACKS = "inc-crafting-stacks"; - protected static final String ACTION_DECREASE_CRAFTING_STACKS = "dec-crafting-stacks"; - - public static final int CRAFTING_SLOTS_BEGIN = 0; - public static final int CRAFTING_SLOTS_SIZE = 9; - public static final int NUM_OF_STORAGE_SLOTS = CraftingTableTileEntity.NUM_OF_STORAGE_SLOTS; - public static final int NUM_OF_STORAGE_ROWS = CraftingTableTileEntity.NUM_OF_STORAGE_ROWS; - - public final ImmutableList> CRAFTING_SLOT_COORDINATES; - private final Player player_; - private final Container inventory_; - private final ContainerLevelAccess wpc_; - private final CraftingHistory history_; - private final CraftingTableGrid matrix_; - private final CraftOutputInventory result_; - private final CraftingOutputSlot crafting_output_slot_; - private boolean has_recipe_collision_; - private boolean crafting_matrix_changed_now_; - private final InventoryRange crafting_grid_range_; - private final InventoryRange crafting_result_range_; - private final InventoryRange block_storage_range_; - private final InventoryRange player_storage_range_; - private final InventoryRange player_hotbar_range_; - private final InventoryRange player_inventory_range_; - private final @Nullable CraftingTableTileEntity te_; - - public CraftingTableUiContainer(int cid, Inventory pinv) - { this(cid, pinv, new SimpleContainer(CraftingTableTileEntity.NUM_OF_SLOTS), ContainerLevelAccess.NULL); } - - private CraftingTableUiContainer(int cid, Inventory pinv, Container block_inventory, ContainerLevelAccess wpc) - { - super(ModContent.getMenuType("metal_crafting_table"), cid); // @todo: class mapping, this stuff is continuously changed to break mods. - wpc_ = wpc; - player_ = pinv.player; - inventory_ = block_inventory; - inventory_.startOpen(player_); - Level world = player_.level; - if((inventory_ instanceof StorageInventory) && ((((StorageInventory)inventory_).getTileEntity()) instanceof final CraftingTableTileEntity te)) { - te_ = te; - } else { - te_ = null; - } - crafting_grid_range_ = new InventoryRange(inventory_, 0, 9, 3); - block_storage_range_ = new InventoryRange(inventory_, CRAFTING_SLOTS_SIZE, NUM_OF_STORAGE_SLOTS, NUM_OF_STORAGE_ROWS); - crafting_result_range_= new InventoryRange(inventory_, CraftingTableTileEntity.CRAFTING_RESULT_SLOT, 1, 1); - player_storage_range_ = InventoryRange.fromPlayerStorage(player_); - player_hotbar_range_ = InventoryRange.fromPlayerHotbar(player_); - player_inventory_range_= InventoryRange.fromPlayerInventory(player_); - matrix_ = new CraftingTableGrid(this, inventory_); - result_ = new CraftOutputInventory(crafting_result_range_); - history_ = new CraftingHistory(world); - // container slotId 0 === crafting output - addSlot(crafting_output_slot_=(new CraftingOutputSlot(this, pinv.player, matrix_, result_, 0, 118, 27))); - ArrayList> slotpositions = new ArrayList<>(); - slotpositions.add(new Tuple<>(118, 27)); - // container slotId 1..9 === TE slots 0..8 - for(int y=0; y<3; ++y) { - for(int x=0; x<3; ++x) { - int xpos = 44+x*18; - int ypos = 9+y*18; - addSlot(new CraftingGridSlot(matrix_, x+y*3, xpos, ypos)); - slotpositions.add(new Tuple<>(xpos, ypos)); - } - } - // container slotId 10..36 === player slots: 9..35 - for(int y=0; y<3; ++y) { - for(int x=0; x<9; ++x) { - addSlot(new Slot(pinv, x+y*9+9, 8+x*18, 110+y*18)); - } - } - // container slotId 37..45 === player slots: 0..8 - for(int x=0; x<9; ++x) { - addSlot(new Slot(pinv, x, 8+x*18, 168)); - } - // container slotId 46..63 === TE slots 9..27 (storage) - for(int y=0; y<2; ++y) { - for(int x=0; x<9; ++x) { - addSlot(new Slot(inventory_, 9+x+y*9, 8+x*18, 65+y*18)); - } - } - if((!player_.level.isClientSide()) && (te_ != null)) { - history_.read(te_.history.copy()); - } - CRAFTING_SLOT_COORDINATES = ImmutableList.copyOf(slotpositions); - onCraftMatrixChanged(); - } - - @Override - public boolean stillValid(Player player) - { return inventory_.stillValid(player); } - - public void onCraftMatrixChanged() - { slotsChanged(matrix_); } - - @Override - public void slotsChanged(Container inv) - { - wpc_.execute((world,pos)->{ - if(world.isClientSide()) return; - try { - crafting_matrix_changed_now_ = true; - ServerPlayer player = (ServerPlayer) player_; - ItemStack stack = ItemStack.EMPTY; - List recipes = world.getServer().getRecipeManager().getRecipesFor(RecipeType.CRAFTING, matrix_, world); - has_recipe_collision_ = false; - if(recipes.size() > 0) { - CraftingRecipe recipe = recipes.get(0); - Recipe currently_used = result_.getRecipeUsed(); - has_recipe_collision_ = (recipes.size() > 1); - if((recipes.size() > 1) && (currently_used instanceof CraftingRecipe) && (recipes.contains(currently_used))) { - recipe = (CraftingRecipe)currently_used; - } - if(result_.setRecipeUsed(world, player, recipe)) { - broadcastChanges(); - stack = recipe.assemble(matrix_); - } - } - result_.setItem(0, stack); - broadcastChanges(); - } catch(Throwable exc) { - Auxiliaries.logger().error("Recipe failed:", exc); - } - }); - } - - @Override - public void removed(Player player) - { inventory_.stopOpen(player); } - - @Override - public boolean canTakeItemForPickAll(ItemStack stack, Slot slot) - { return (slot.container != result_) && (super.canTakeItemForPickAll(stack, slot)); } - - @Override - public ItemStack quickMoveStack(Player player, int index) - { - Slot slot = slots.get(index); - if((slot == null) || (!slot.hasItem())) return ItemStack.EMPTY; - ItemStack slotstack = slot.getItem(); - ItemStack stack = slotstack.copy(); - if(index == 0) { - if(!this.moveItemStackTo(slotstack, 10, 46+NUM_OF_STORAGE_SLOTS, false)) return ItemStack.EMPTY; - wpc_.execute((world, pos)->slotstack.getItem().onCraftedBy(slotstack, world, player)); - slot.onQuickCraft(slotstack, stack); - } else if(index >= 10 && (index < 46)) { - if(!this.moveItemStackTo(slotstack, 46, 46+NUM_OF_STORAGE_SLOTS, false)) return ItemStack.EMPTY; - } else if((index >= 46) && (index < 46+NUM_OF_STORAGE_SLOTS)) { - if(!this.moveItemStackTo(slotstack, 10, 46, false)) return ItemStack.EMPTY; - } else if(!this.moveItemStackTo(slotstack, 10, 46, false)) { - return ItemStack.EMPTY; - } - if(slotstack.isEmpty()) slot.set(ItemStack.EMPTY); - slot.setChanged(); - if((index != 0) && (slotstack.getCount() == stack.getCount())) return ItemStack.EMPTY; - slot.onTake(player, slotstack); - return stack; - } - - @Override - public void clicked(int slotId, int button, ClickType clickType, Player player) - { - crafting_matrix_changed_now_ = false; - super.clicked(slotId, button, clickType, player); - if((with_outslot_defined_refab) && (slotId == 0) && (clickType == ClickType.PICKUP)) { - if((!crafting_matrix_changed_now_) && (!player.level.isClientSide()) && (crafting_grid_empty())) { - final ItemStack dragged = getCarried(); - if((dragged != null) && (!dragged.isEmpty())) { - try_result_stack_refab(dragged, player.level); - } else if(!history().current().isEmpty()) { - try_result_stack_refab(history().current_recipe().getResultItem(), player.level); - } - } - } - } - - // Container client/server synchronisation -------------------------------------------------- - - @OnlyIn(Dist.CLIENT) - public void onGuiAction(String message, CompoundTag nbt) - { - nbt.putString("action", message); - Networking.PacketContainerSyncClientToServer.sendToServer(containerId, nbt); - } - - @Override - public void onServerPacketReceived(int windowId, CompoundTag nbt) - { - if(nbt.contains("history")) { - history_.read(nbt.getCompound("history")); - } - if(nbt.contains("hascollision")) { - has_recipe_collision_ = nbt.getBoolean("hascollision"); - } - if(nbt.contains("inventory")) { - Inventories.readNbtStacks(nbt, "inventory", inventory_); - this.slotsChanged(matrix_); - } - } - - @Override - public void onClientPacketReceived(int windowId, Player player, CompoundTag nbt) - { - boolean changed = false; - boolean player_inventory_changed = false; - if(with_assist && nbt.contains("action")) { - switch(nbt.getString("action")) { - case BUTTON_NEXT -> { - history_.next(); - // implicitly clear the grid, so that the player can see the refab, and that no recipe is active. - if (crafting_grid_range_.move(block_storage_range_)) changed = true; - if (crafting_grid_range_.move(player_inventory_range_)) { - changed = true; - player_inventory_changed = true; - } - sync(); - } - case BUTTON_PREV -> { - history_.prev(); - if (crafting_grid_range_.move(block_storage_range_)) changed = true; - if (crafting_grid_range_.move(player_inventory_range_)) { - changed = true; - player_inventory_changed = true; - } - sync(); - } - case BUTTON_CLEAR_GRID -> { - history_.reset_selection(); - sync(); - if(crafting_grid_range_.move(block_storage_range_)) changed = true; - if(crafting_grid_range_.move(player_inventory_range_)) { - changed = true; - player_inventory_changed = true; - } - } - case ACTION_PLACE_CURRENT_HISTORY_SEL -> { - if(place_stacks( - new InventoryRange[]{block_storage_range_, player_storage_range_, player_hotbar_range_}, - refab_crafting_stacks()) != PlacementResult.UNCHANGED) { - changed = true; - } - } - case ACTION_PLACE_SHIFTCLICKED_STACK -> { - final int container_slot_id = nbt.getInt("containerslot"); - if((container_slot_id < 10) || (container_slot_id > (46 + NUM_OF_STORAGE_SLOTS))) { - break; // out of range - } - if(container_slot_id >= 46) { - // from storage - PlacementResult stat = distribute_stack(block_storage_range_, container_slot_id - 46); - if (stat != PlacementResult.UNCHANGED) changed = true; - } else { - // from player - int player_slot = (container_slot_id >= 37) ? (container_slot_id - 37) : (container_slot_id - 10 + 9); - final ItemStack reference_stack = player.getInventory().getItem(player_slot).copy(); - if((!reference_stack.isEmpty()) && (distribute_stack(player.getInventory(), player_slot) != PlacementResult.UNCHANGED)) { - player_inventory_changed = true; - changed = true; - if(nbt.contains("move-all")) { - for(int i = 0; i < player.getInventory().getContainerSize(); ++i) { - final ItemStack stack = player.getInventory().getItem(i); - if(!Inventories.areItemStacksIdentical(reference_stack, stack)) continue; - if(distribute_stack(player.getInventory(), i) == PlacementResult.UNCHANGED) break; // grid is full - } - } - } - } - } - case ACTION_MOVE_STACK -> { - final int container_slot_id = nbt.getInt("containerslot"); - if((container_slot_id < 1) || (container_slot_id >= (46 + NUM_OF_STORAGE_SLOTS))) { - break; // out of range - } else if (container_slot_id < 10) { - ItemStack remaining = Inventories.insert( - new InventoryRange[]{block_storage_range_, player_storage_range_, player_hotbar_range_}, - inventory_.getItem(container_slot_id - 1) - ); - changed = player_inventory_changed = (remaining.getCount() != inventory_.getItem(container_slot_id - 1).getCount()); - inventory_.setItem(container_slot_id - 1, remaining); - } - } - case ACTION_MOVE_ALL_STACKS -> { - final int container_slot_id = nbt.getInt("containerslot"); - if ((container_slot_id < 1) || (container_slot_id >= (46 + NUM_OF_STORAGE_SLOTS))) { - break; // out of range - } else if (container_slot_id < 10) { - // from crafting grid to player inventory, we clear the grid here as this is most likely - // what is wanted in the end. Saves clicking the other grid stacks. - if (crafting_grid_range_.move(player_inventory_range_, true)) { - crafting_grid_range_.move(player_inventory_range_, false, false, true); - changed = true; - player_inventory_changed = true; - } - if (crafting_grid_range_.move(block_storage_range_)) changed = true; - if (crafting_grid_range_.move(player_inventory_range_, true)) { - changed = true; - player_inventory_changed = true; - } - break; - } - Container from_inventory; - InventoryRange[] to_ranges; - int from_slot; - if (container_slot_id >= 46) { - // from storage to player inventory - from_inventory = inventory_; - from_slot = container_slot_id - 46 + CRAFTING_SLOTS_SIZE; - to_ranges = new InventoryRange[]{player_storage_range_, player_hotbar_range_}; - } else { - // from player to storage (otherwise ACTION_PLACE_SHIFTCLICKED_STACK would have been used) - from_inventory = player.getInventory(); - from_slot = (container_slot_id >= 37) ? (container_slot_id - 37) : (container_slot_id - 10 + 9); - to_ranges = new InventoryRange[]{block_storage_range_}; - } - final ItemStack reference_stack = from_inventory.getItem(from_slot).copy(); - if (!reference_stack.isEmpty()) { - boolean abort = false; - for (int i = 0; (i < from_inventory.getContainerSize()) && (!abort); ++i) { - final ItemStack stack = from_inventory.getItem(i); - if (Inventories.areItemStacksDifferent(reference_stack, stack)) continue; - ItemStack remaining = Inventories.insert(to_ranges, from_inventory.getItem(i)); - changed = player_inventory_changed = (remaining.getCount() != from_inventory.getItem(i).getCount()); - from_inventory.setItem(i, remaining); - } - } - } - case BUTTON_NEXT_COLLISION_RECIPE -> select_next_collision_recipe(inventory_); - case ACTION_DECREASE_CRAFTING_STACKS -> changed = player_inventory_changed = decrease_grid_stacks( - new InventoryRange[]{block_storage_range_, player_storage_range_, player_hotbar_range_}, - Mth.clamp(nbt.getInt("limit"), 1, 8)); - case ACTION_INCREASE_CRAFTING_STACKS -> changed = player_inventory_changed = increase_grid_stacks( - new InventoryRange[]{block_storage_range_, player_storage_range_, player_hotbar_range_}, - Mth.clamp(nbt.getInt("limit"), 1, 8)); - } - } - if(changed) inventory_.setChanged(); - if(player_inventory_changed) player.getInventory().setChanged(); - if(changed || player_inventory_changed) { - this.onCraftMatrixChanged(); - this.broadcastChanges(); - } - } - - public CraftingHistory history() - { return history_; } - - private void sync() - { - this.wpc_.execute((world,pos)->{ - if(world.isClientSide()) return; - inventory_.setChanged(); - final CompoundTag nbt = new CompoundTag(); - if(te_ != null) nbt.put("inventory", te_.mainInventory().save(false)); - if(with_assist) { - CompoundTag hist_nbt = history_.write(); - if(te_ != null) { - te_.history = hist_nbt.copy(); - } - nbt.put("history", hist_nbt); - nbt.putBoolean("hascollision", has_recipe_collision_); - } - Networking.PacketContainerSyncServerToClient.sendToListeners(world, this, nbt); - }); - } - - // private aux methods --------------------------------------------------------------------- - - public boolean has_recipe_collision() - { return has_recipe_collision_; } - - public void select_next_collision_recipe(Container inv) - { - wpc_.execute((world,pos)->{ - if(world.isClientSide) return; - try { - ServerPlayer player = (ServerPlayer) player_; - final List matching_recipes = world.getServer().getRecipeManager().getRecipesFor(RecipeType.CRAFTING, matrix_, world); - if(matching_recipes.size() < 2) return; // nothing to change - Recipe currently_used = result_.getRecipeUsed(); - List usable_recipes = matching_recipes.stream() - .filter((r)->result_.setRecipeUsed(world,player,r)) - .sorted(Comparator.comparingInt(a -> a.getId().hashCode())) - .collect(Collectors.toList()); - for(int i=0; i= usable_recipes.size()) i=0; - currently_used = usable_recipes.get(i); - ItemStack stack = ((CraftingRecipe)currently_used).assemble(matrix_); - result_.setItem(0, stack); - result_.setRecipeUsed(currently_used); - break; - } - } - onCraftMatrixChanged(); - } catch(Throwable exc) { - Auxiliaries.logger().error("Recipe failed:", exc); - } - }); - } - - @Nullable - private CraftingRecipe find_first_recipe_for(Level world, ItemStack stack) - { - return (CraftingRecipe)world.getServer().getRecipeManager().getRecipes().stream() - .filter(r->(r.getType()==RecipeType.CRAFTING) && (r.getResultItem().sameItem(stack))) - .findFirst().orElse(null); - } - - private Optional search_inventory(ItemStack match_stack) { - InventoryRange[] search_ranges = new InventoryRange[]{block_storage_range_, player_storage_range_, player_hotbar_range_}; - for(InventoryRange range: search_ranges) { - for(int i=0; i search_inventory(ItemStack[] match_stacks) { - for(ItemStack match_stack: match_stacks) { - Optional stack = search_inventory(match_stack); - if(stack.isPresent()) return stack; - } - return Optional.empty(); - } - - private ArrayList placement_stacks(CraftingRecipe recipe) - { - final Level world = player_.level; - final ArrayList grid = new ArrayList<>(); - if(recipe.getIngredients().size() > 9) { - return grid; - } else if(recipe instanceof ShapedRecipe) { - final int endw = ((ShapedRecipe)recipe).getWidth(); - final int endh = ((ShapedRecipe)recipe).getHeight(); - int ingredient_index = 0; - for(int i=3-endh; i>0; --i) for(int w=0; w<3; ++w) { - grid.add(ItemStack.EMPTY); - } - for(int h=3-endh; h<3; ++h) for(int w=0; w<3; ++w) { - if((w >= endw) || (ingredient_index >= recipe.getIngredients().size())) { grid.add(ItemStack.EMPTY); continue; } - ItemStack[] match_stacks = recipe.getIngredients().get(ingredient_index++).getItems(); - if(match_stacks.length == 0) { grid.add(ItemStack.EMPTY); continue; } - ItemStack preferred = search_inventory(match_stacks).orElse(match_stacks[0]); - if(preferred.isEmpty()) { grid.add(ItemStack.EMPTY); continue; } - grid.add(preferred); - } - } else if(recipe instanceof ShapelessRecipe) { - // todo: check if a collision resolver with shaped recipes makes sense here. - for(int ingredient_index=0; ingredient_index grid_stacks) - { - boolean changed = false; - final List ingredients = recipe.getIngredients(); - for(int stack_index=0; stack_index < grid_stacks.size(); ++stack_index) { - ItemStack to_replace = grid_stacks.get(stack_index); - ItemStack replacement = to_replace; - if(to_replace.isEmpty() || (search_inventory(to_replace).isPresent())) continue; // no replacement needed - for(int ingredient_index=0; ingredient_indexInventories.areItemStacksIdentical(s, to_replace))) { - replacement = search_inventory(match_stacks).orElse(to_replace); - changed = true; - break; - } - } - grid_stacks.set(stack_index, replacement); - } - return changed; - } - - private void try_result_stack_refab(ItemStack output_stack, Level world) - { - CraftingRecipe recipe; - int history_index = history().find(output_stack); - if(history_index >= 0) { - history().selection(history_index); - recipe = history().current_recipe(); - List grid_stacks = history().current().subList(1, history().current().size()); - if(adapt_recipe_placement(recipe, grid_stacks)) { - history().stash(grid_stacks, recipe); - recipe = history().current_recipe(); - } - } else if((recipe=find_first_recipe_for(world, output_stack)) != null) { - ArrayList stacks = placement_stacks(recipe); - if(stacks.isEmpty()) { - recipe = null; - } else { - history().stash(stacks, recipe); - recipe = history().current_recipe(); - } - } - if(recipe != null) { - sync(); - onCraftMatrixChanged(); - } else { - history().reset_current(); - sync(); - } - } - - private boolean crafting_grid_empty() - { for(int i=0; i<10; ++i) { if(getSlot(i).hasItem()) return false; } return true; } - - private boolean itemstack_recipe_match(ItemStack grid_stack, ItemStack history_stack) - { - if(history_.current_recipe()!=null) { - final NonNullList ingredients = history_.current_recipe().getIngredients(); - boolean grid_match, dist_match; - for(Ingredient ingredient: ingredients) { - grid_match = false; - dist_match = false; - for(final ItemStack match: ingredient.getItems()) { - if(match.sameItemStackIgnoreDurability(grid_stack)) dist_match = true; - if(match.sameItemStackIgnoreDurability(history_stack)) grid_match = true; - if(dist_match && grid_match) return true; - } - } - } - return false; - } - - private List refab_crafting_stacks() - { - final ArrayList slots = new ArrayList<>(); - final List tocraft = history_.current(); - final int[] stack_sizes = {-1,-1,-1,-1,-1,-1,-1,-1,-1}; - if(tocraft.isEmpty()) return slots; - for(int i=0; i<9; ++i) { - if((i+CraftingHistory.INPUT_STACKS_BEGIN) >= tocraft.size()) break; - final ItemStack needed = tocraft.get(i+CraftingHistory.INPUT_STACKS_BEGIN); - final ItemStack palced = inventory_.getItem(i+CRAFTING_SLOTS_BEGIN); - if(needed.isEmpty() && (!palced.isEmpty())) return slots; // history vs grid mismatch. - if((!palced.isEmpty()) && (!itemstack_recipe_match(needed, palced))) return slots; // also mismatch - if(!needed.isEmpty()) stack_sizes[i] = palced.getCount(); - } - int min_placed = 64, max_placed=0; - for(int i=0; i<9; ++i) { - if(stack_sizes[i] < 0) continue; - min_placed = Math.min(min_placed, stack_sizes[i]); - max_placed = Math.max(max_placed, stack_sizes[i]); - } - int fillup_size = (max_placed <= min_placed) ? (min_placed + 1) : max_placed; - for(int i=0; i<9; ++i) { - if(stack_sizes[i] < 0) continue; - if(fillup_size > inventory_.getItem(i+CRAFTING_SLOTS_BEGIN).getMaxStackSize()) return slots; // can't fillup all - } - for(int i=0; i<9; ++i) { - if(stack_sizes[i] < 0) { - slots.add(ItemStack.EMPTY); - } else { - ItemStack st = inventory_.getItem(i+CRAFTING_SLOTS_BEGIN).copy(); - if(st.isEmpty()) { - st = tocraft.get(i+CraftingHistory.INPUT_STACKS_BEGIN).copy(); - st.setCount(Math.min(st.getMaxStackSize(), fillup_size)); - } else { - st.setCount(Mth.clamp(fillup_size-st.getCount(), 0, st.getMaxStackSize())); - } - slots.add(st); - } - } - return slots; - } - - private List incr_crafting_grid_stacks(int count) - { - final ArrayList stacks = new ArrayList<>(); - for(int i=0; i<9; ++i) { - final ItemStack palced = crafting_grid_range_.getItem(i).copy(); - if(!palced.isEmpty()) palced.setCount(count); - stacks.add(palced); - } - return stacks; - } - - private PlacementResult place_stacks(final InventoryRange[] ranges, final List to_fill) - { - if(history_.current_recipe() != null) result_.setRecipeUsed(history_.current_recipe()); - boolean slots_changed = false; - if(!to_fill.isEmpty()) { - for(InventoryRange slot_range: ranges) { - for(int it_guard=63; it_guard>=0; --it_guard) { - boolean slots_updated = false; - for(int i = 0; i < 9; ++i) { - if(to_fill.get(i).isEmpty()) continue; - ItemStack grid_stack = crafting_grid_range_.getItem(i).copy(); - if(grid_stack.getCount() >= grid_stack.getMaxStackSize()) continue; - final ItemStack req_stack = to_fill.get(i).copy(); - req_stack.setCount(1); - final ItemStack mv_stack = slot_range.extract(req_stack); - if(mv_stack.isEmpty()) continue; - to_fill.get(i).shrink(1); - if(grid_stack.isEmpty()) { - grid_stack = mv_stack.copy(); - } else { - grid_stack.grow(mv_stack.getCount()); - } - crafting_grid_range_.setItem(i, grid_stack); - slots_changed = true; - slots_updated = true; - } - if(!slots_updated) break; - } - } - } - boolean missing_item = false; - for(ItemStack st:to_fill) { - if(!st.isEmpty()) { - missing_item = true; - break; - } - } - if(!slots_changed) { - return PlacementResult.UNCHANGED; - } else if(missing_item) { - return PlacementResult.INCOMPLETE; - } else { - return PlacementResult.PLACED; - } - } - - private PlacementResult distribute_stack(Container inventory, final int slot_index) - { - List to_refab = refab_crafting_stacks(); - if(history_.current_recipe() != null) result_.setRecipeUsed(history_.current_recipe()); - ItemStack to_distribute = inventory.getItem(slot_index).copy(); - if(to_distribute.isEmpty()) return PlacementResult.UNCHANGED; - int[] matching_grid_stack_sizes = {-1,-1,-1,-1,-1,-1,-1,-1,-1}; - int max_matching_stack_size = -1; - int min_matching_stack_size = 65; - int total_num_missing_stacks = 0; - for(int i=0; i<9; ++i) { - final ItemStack grid_stack = crafting_grid_range_.getItem(i); - final ItemStack refab_stack = to_refab.isEmpty() ? ItemStack.EMPTY : to_refab.get(i).copy(); - if((!grid_stack.isEmpty()) && Inventories.areItemStacksIdentical(grid_stack, to_distribute)) { - matching_grid_stack_sizes[i] = grid_stack.getCount(); - total_num_missing_stacks += grid_stack.getMaxStackSize()-grid_stack.getCount(); - if(max_matching_stack_size < matching_grid_stack_sizes[i]) max_matching_stack_size = matching_grid_stack_sizes[i]; - if(min_matching_stack_size > matching_grid_stack_sizes[i]) min_matching_stack_size = matching_grid_stack_sizes[i]; - } else if((!refab_stack.isEmpty()) && (Inventories.areItemStacksIdentical(refab_stack, to_distribute))) { - matching_grid_stack_sizes[i] = 0; - total_num_missing_stacks += grid_stack.getMaxStackSize(); - if(max_matching_stack_size < matching_grid_stack_sizes[i]) max_matching_stack_size = matching_grid_stack_sizes[i]; - if(min_matching_stack_size > matching_grid_stack_sizes[i]) min_matching_stack_size = matching_grid_stack_sizes[i]; - } else if(grid_stack.isEmpty() && (!refab_stack.isEmpty())) { - if(itemstack_recipe_match(to_distribute, refab_stack)) { - matching_grid_stack_sizes[i] = 0; - total_num_missing_stacks += grid_stack.getMaxStackSize(); - if(max_matching_stack_size < matching_grid_stack_sizes[i]) max_matching_stack_size = matching_grid_stack_sizes[i]; - if(min_matching_stack_size > matching_grid_stack_sizes[i]) min_matching_stack_size = matching_grid_stack_sizes[i]; - } - } - } - if(min_matching_stack_size < 0) return PlacementResult.UNCHANGED; - final int stack_limit_size = Math.min(to_distribute.getMaxStackSize(), crafting_grid_range_.getMaxStackSize()); - if(min_matching_stack_size >= stack_limit_size) return PlacementResult.UNCHANGED; - int n_to_distribute = to_distribute.getCount(); - for(int it_guard=63; it_guard>=0; --it_guard) { - if(n_to_distribute <= 0) break; - for(int i=0; i<9; ++i) { - if(n_to_distribute <= 0) break; - if(matching_grid_stack_sizes[i] == min_matching_stack_size) { - ++matching_grid_stack_sizes[i]; - --n_to_distribute; - } - } - if(min_matching_stack_size < max_matching_stack_size) { - ++min_matching_stack_size; // distribute short stacks - } else { - ++min_matching_stack_size; // stacks even, increase all - max_matching_stack_size = min_matching_stack_size; - } - if(min_matching_stack_size >= stack_limit_size) break; // all full - } - if(n_to_distribute == to_distribute.getCount()) return PlacementResult.UNCHANGED; // was already full - if(n_to_distribute <= 0) { - inventory.setItem(slot_index, ItemStack.EMPTY); - } else { - to_distribute.setCount(n_to_distribute); - inventory.setItem(slot_index, to_distribute); - } - for(int i=0; i<9; ++i) { - if(matching_grid_stack_sizes[i] < 0) continue; - ItemStack grid_stack = crafting_grid_range_.getItem(i).copy(); - if(grid_stack.isEmpty()) grid_stack = to_distribute.copy(); - grid_stack.setCount(matching_grid_stack_sizes[i]); - crafting_grid_range_.setItem(i, grid_stack); - } - return PlacementResult.PLACED; - } - - private boolean decrease_grid_stacks(InventoryRange[] ranges, int limit) - { - boolean changed = false; - for(int i=0; i<9; ++i) { - ItemStack stack = crafting_grid_range_.getItem(i).copy(); - if(stack.isEmpty()) continue; - for(InventoryRange range:ranges) { - ItemStack remaining = range.insert(stack, false, limit, false, false); - if(remaining.getCount() < stack.getCount()) changed = true; - boolean stop = (remaining.getCount() <= Math.max(0, (stack.getCount()-limit))); - stack = remaining; - if(stop) break; - } - crafting_grid_range_.setItem(i, stack.isEmpty() ? ItemStack.EMPTY : stack); - } - return changed; - } - - private boolean increase_grid_stacks(InventoryRange[] ranges, int limit) - { return place_stacks(ranges, incr_crafting_grid_stacks(limit)) != PlacementResult.UNCHANGED; } - - } - - //-------------------------------------------------------------------------------------------------------------------- - // GUI - //-------------------------------------------------------------------------------------------------------------------- - - @OnlyIn(Dist.CLIENT) - public static class CraftingTableGui extends Guis.ContainerGui - { - protected final ArrayList