diff --git a/.gitattributes b/.gitattributes index dfe0770..f811f6a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ -# Auto detect text files and perform LF normalization -* text=auto +# Disable autocrlf on generated files, they always generate with LF +# Add any extra files or paths here to make git stop saying they +# are changed when only line endings change. +src/generated/**/.cache/cache text eol=lf +src/generated/**/*.json text eol=lf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..bf864e1 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,24 @@ +name: Build + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1000 + fetch-tags: true + + - name: Setup JDK 17 + uses: actions/setup-java@v2 + with: + java-version: '17' + distribution: 'temurin' + + - name: Build with Gradle + uses: gradle/gradle-build-action@v2 + with: + arguments: build diff --git a/.gitignore b/.gitignore index ec1c3e3..31d2550 100644 --- a/.gitignore +++ b/.gitignore @@ -20,12 +20,7 @@ build # other eclipse run +runs +run-data -# Files from Forge MDK -forge*changelog.txt -runData.launch -runClient.launch -runServer.launch -runClient.launch -*.launch -*.launch +repo \ No newline at end of file diff --git a/CREDITS.txt b/CREDITS.txt deleted file mode 100644 index a70c53d..0000000 --- a/CREDITS.txt +++ /dev/null @@ -1,65 +0,0 @@ -Minecraft Forge: Credits/Thank You - -Forge is a set of tools and modifications to the Minecraft base game code to assist -mod developers in creating new and exciting content. It has been in development for -several years now, but I would like to take this time thank a few people who have -helped it along it's way. - -First, the people who originally created the Forge projects way back in Minecraft -alpha. Eloraam of RedPower, and SpaceToad of Buildcraft, without their acceptiance -of me taking over the project, who knows what Minecraft modding would be today. - -Secondly, someone who has worked with me, and developed some of the core features -that allow modding to be as functional, and as simple as it is, cpw. For developing -FML, which stabelized the client and server modding ecosystem. As well as the base -loading system that allows us to modify Minecraft's code as elegently as possible. - -Mezz, who has stepped up as the issue and pull request manager. Helping to keep me -sane as well as guiding the community into creating better additions to Forge. - -Searge, Bspks, Fesh0r, ProfMobious, and all the rest over on the MCP team {of which -I am a part}. For creating some of the core tools needed to make Minecraft modding -both possible, and as stable as can be. - On that note, here is some specific information of the MCP data we use: - * Minecraft Coder Pack (MCP) * - Forge Mod Loader and Minecraft Forge have permission to distribute and automatically - download components of MCP and distribute MCP data files. This permission is not - transitive and others wishing to redistribute the Minecraft Forge source independently - should seek permission of MCP or remove the MCP data files and request their users - to download MCP separately. - -And lastly, the countless community members who have spent time submitting bug reports, -pull requests, and just helping out the community in general. Thank you. - ---LexManos - -========================================================================= - -This is Forge Mod Loader. - -You can find the source code at all times at https://github.com/MinecraftForge/MinecraftForge/tree/1.12.x/src/main/java/net/minecraftforge/fml - -This minecraft mod is a clean open source implementation of a mod loader for minecraft servers -and minecraft clients. - -The code is authored by cpw. - -It began by partially implementing an API defined by the client side ModLoader, authored by Risugami. -http://www.minecraftforum.net/topic/75440- -This support has been dropped as of Minecraft release 1.7, as Risugami no longer maintains ModLoader. - -It also contains suggestions and hints and generous helpings of code from LexManos, author of MinecraftForge. -http://www.minecraftforge.net/ - -Additionally, it contains an implementation of topological sort based on that -published at http://keithschwarz.com/interesting/code/?dir=topological-sort - -It also contains code from the Maven project for performing versioned dependency -resolution. http://maven.apache.org/ - -It also contains a partial repackaging of the javaxdelta library from http://sourceforge.net/projects/javaxdelta/ -with credit to it's authors. - -Forge Mod Loader downloads components from the Minecraft Coder Pack -(http://mcp.ocean-labs.de/index.php/Main_Page) with kind permission from the MCP team. - diff --git a/README.txt b/README.txt deleted file mode 100644 index e9ab7dc..0000000 --- a/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -Village Pest Control. - -https://www.curseforge.com/minecraft/mc-mods/guard-villagers diff --git a/build.gradle b/build.gradle index 9269a43..4b5845a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,149 +1,113 @@ -buildscript { - repositories { - maven { url = 'https://maven.minecraftforge.net/' } - maven { url = 'https://maven.parchmentmc.org' } - maven { url = 'https://repo.spongepowered.org/repository/maven-public/' } - jcenter() - mavenCentral() - } - dependencies { - classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '[6.0.14,6.2)', changing: true - classpath 'org.parchmentmc:librarian:1.+' - classpath group: 'org.spongepowered', name: 'mixingradle', version: '0.7-SNAPSHOT' - } -} -apply plugin: 'net.minecraftforge.gradle' -// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. -apply plugin: 'eclipse' -apply plugin: 'maven-publish' -apply plugin: 'org.parchmentmc.librarian.forgegradle' -apply plugin: 'org.spongepowered.mixin' - -mixin { - add sourceSets.main, "guardvillagers.refmap.json" +plugins { + id 'java-library' + id 'eclipse' + id 'idea' + id 'maven-publish' + id 'net.neoforged.gradle.userdev' version '7.0.45' } +version = mod_version +group = mod_group_id -version = '1.20.2-1.6.4' -group = 'tallestegg.guardvillagers' // http://maven.apache.org/guides/mini/guide-naming-conventions.html -archivesBaseName = 'guardvillagers' - -java.toolchain.languageVersion = JavaLanguageVersion.of(17) - -minecraft { - // The mappings can be changed at any time, and must be in the following format. - // snapshot_YYYYMMDD Snapshot are built nightly. - // stable_# Stables are built at the discretion of the MCP team. - // Use non-default mappings at your own risk. they may not always work. - // Simply re-run your setup task after changing the mappings to update your workspace. - mappings channel: 'parchment', version: "1.20.1-2023.06.26-1.20.2" - // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. - - accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') - - // Default run configurations. - // These can be tweaked, removed, or duplicated as needed. - runs { - client { - workingDirectory project.file('run') - - // Recommended logging data for a userdev environment - property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' - - // Recommended logging level for the console - property 'forge.logging.console.level', 'debug' - arg "-mixin.config=guardvillagers.mixins.json" - - mods { - examplemod { - source sourceSets.main - } - } - } - - server { - workingDirectory project.file('run') +repositories { + mavenLocal() +} - // Recommended logging data for a userdev environment - property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' +base { + archivesName = mod_id +} - // Recommended logging level for the console - property 'forge.logging.console.level', 'debug' - arg "-mixin.config=guardvillagers.mixins.json" +// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. +java.toolchain.languageVersion = JavaLanguageVersion.of(17) - mods { - examplemod { - source sourceSets.main - } - } - } +minecraft.accessTransformers.file rootProject.file('src/main/resources/META-INF/accesstransformer.cfg') + +// Default run configurations. +// These can be tweaked, removed, or duplicated as needed. +runs { + // applies to all the run configs below + configureEach { + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + systemProperty 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + systemProperty 'forge.logging.console.level', 'debug' + + modSource project.sourceSets.main + } - data { - workingDirectory project.file('run') + client { + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + } - // Recommended logging data for a userdev environment - property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + server { + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + programArgument '--nogui' + } - // Recommended logging level for the console - property 'forge.logging.console.level', 'debug' - arg "-mixin.config=guardvillagers.mixins.json" + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + } - args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/') + data { + // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it + // workingDirectory project.file('run-data') - mods { - examplemod { - source sourceSets.main - } - } - } + // 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() } } -dependencies { - minecraft 'net.minecraftforge:forge:1.20.2-48.0.34' - annotationProcessor "org.spongepowered:mixin:0.8.5:processor" -} +// Include resources generated by data generators. +sourceSets.main.resources { srcDir 'src/generated/resources' } -repositories { - maven { - url "https://www.cursemaven.com" - } -} -// Example for how to get properties into the manifest for reading by the runtime.. -jar { - manifest { - attributes([ - "Specification-Title": "examplemod", - "Specification-Vendor": "examplemodsareus", - "Specification-Version": "1", // We are version 1 of ourselves - "Implementation-Title": project.name, - "Implementation-Version": "${version}", - "Implementation-Vendor" :"examplemodsareus", - "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), - "MixinConfigs": "guardvillagers.mixins.json" - ]) - } +dependencies { + implementation "net.neoforged:neoforge:${neo_version}" } -// Example configuration to allow publishing using the maven-publish task -// we define a custom artifact that is sourced from the reobfJar output task -// and then declare that to be published -// Note you'll need to add a repository here -def reobfFile = file("$buildDir/reobfJar/output.jar") -def reobfArtifact = artifacts.add('default', reobfFile) { - type 'jar' - builtBy 'reobfJar' +// This block of code expands all declared replace properties in the specified resource targets. +// A missing property will result in an error. Properties are expanded using ${} Groovy notation. +// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments. +// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html +tasks.withType(ProcessResources).configureEach { + var replaceProperties = [ + minecraft_version : minecraft_version, minecraft_version_range: minecraft_version_range, + neo_version : neo_version, neo_version_range: neo_version_range, + loader_version_range: loader_version_range, + mod_id : mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version, + mod_authors : mod_authors, mod_description: mod_description, pack_format_number: pack_format_number, + ] + inputs.properties replaceProperties + + filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { + expand replaceProperties + [project: project] + } } +// Example configuration to allow publishing using the maven-publish plugin publishing { publications { - mavenJava(MavenPublication) { - artifact reobfArtifact + register('mavenJava', MavenPublication) { + from components.java } } repositories { maven { - url "file:///${project.projectDir}/mcmodsrepo" + url "file://${project.projectDir}/repo" } } -} \ No newline at end of file +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation +} diff --git a/gradle.properties b/gradle.properties index 42fba16..98f4cad 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,4 +2,58 @@ # This is required to provide enough memory for the Minecraft decompilation process. org.gradle.jvmargs=-Xmx3G org.gradle.daemon=false -distributionUrl=https://services.gradle.org/distributions/gradle-7.2-bin.zip +org.gradle.debug=false + +## Environment Properties + +# The Minecraft version must agree with the Neo version to get a valid artifact +minecraft_version=1.20.2 +# The Minecraft version range can use any release version of Minecraft as bounds. +# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly +# as they do not follow standard versioning conventions. +minecraft_version_range=[1.20.2,1.21) +# The Neo version must agree with the Minecraft version to get a valid artifact +neo_version=20.2.59-beta +# The Neo version range can use any version of Neo as bounds or match the loader version range +neo_version_range=[20.2,) +# The loader version range can only use the major version of Neo/FML as bounds +loader_version_range=[1,) +# The mapping channel to use for mappings. +# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"]. +# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin. +# +# | Channel | Version | | +# |-----------|----------------------|--------------------------------------------------------------------------------| +# | official | MCVersion | Official field/method names from Mojang mapping files | +# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official | +# +# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings. +# See more information here: https://github.com/neoforged/NeoForm/blob/main/Mojang.md +# +# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge. +# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started +mapping_channel=official +# The mapping version to query from the mapping channel. +# This must match the format required by the mapping channel. +mapping_version=1.20.2 + + +## Mod Properties + +# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63} +# Must match the String constant located in the main mod class annotated with @Mod. +mod_id=guardvillagers +# The human-readable display name for the mod. +mod_name=Guard Villagers +# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. +mod_license=MIT for code, assets are ARR +# The mod version. See https://semver.org/ +mod_version=2.0.0-1.20.2 +# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. +# This should match the base package used for the mod sources. +# See https://maven.apache.org/guides/mini/guide-naming-conventions.html +mod_group_id=tallestegg.guardvillagers +# The authors of the mod. This is a simple text string that is used for display purposes in the mod list. +mod_authors=TallestEgg, HadeZ/SadNya69 for the textures. +mod_description=Need some help with pest control? The Guards are ready to help! +pack_format_number=18 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7a3265e..943f0cb 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 59bc51a..37aef8d 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index cccdd3d..65dcd68 100644 --- a/gradlew +++ b/gradlew @@ -1,78 +1,129 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# 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. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## -## -## 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/HEAD/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_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +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 - ;; - 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 + # Determine the Java command to use to start the JVM. 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 @@ -81,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 @@ -89,84 +140,105 @@ 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 +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=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=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac 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 +# 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. + +# 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" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; 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\"" + 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 - i=$((i+1)) + # 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 - 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" ;; - 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, 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" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# 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 \ + "$@" + +# 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. +# +# 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/gradlew.bat b/gradlew.bat index f955316..93e3f59 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,4 +1,20 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -9,19 +25,23 @@ 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% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +55,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,38 +65,26 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :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 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..fc113ae --- /dev/null +++ b/settings.gradle @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + maven { url = 'https://maven.neoforged.net/releases' } + maven { url = 'https://maven.parchmentmc.org' } + } +} + +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' +} diff --git a/src/main/java/tallestegg/guardvillagers/GuardEntityType.java b/src/main/java/tallestegg/guardvillagers/GuardEntityType.java index 9794d84..b6a01e2 100644 --- a/src/main/java/tallestegg/guardvillagers/GuardEntityType.java +++ b/src/main/java/tallestegg/guardvillagers/GuardEntityType.java @@ -1,15 +1,15 @@ package tallestegg.guardvillagers; +import net.minecraft.core.registries.Registries; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; import tallestegg.guardvillagers.entities.Guard; -@Mod.EventBusSubscriber(modid = GuardVillagers.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) +//@Mod.EventBusSubscriber(modid = GuardVillagers.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) public class GuardEntityType { - public static final DeferredRegister> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, GuardVillagers.MODID); - public static final RegistryObject> GUARD = ENTITIES.register("guard", () -> EntityType.Builder.of(Guard::new, MobCategory.MISC).sized(0.6F, 1.95F).setShouldReceiveVelocityUpdates(true).build(GuardVillagers.MODID + "guard")); + public static final DeferredRegister> ENTITIES = DeferredRegister.create(Registries.ENTITY_TYPE, GuardVillagers.MODID); + public static final DeferredHolder, EntityType> GUARD = ENTITIES.register("guard", () -> EntityType.Builder.of(Guard::new, MobCategory.MISC).sized(0.6F, 1.95F).setShouldReceiveVelocityUpdates(true).build(GuardVillagers.MODID + "guard")); } diff --git a/src/main/java/tallestegg/guardvillagers/GuardItems.java b/src/main/java/tallestegg/guardvillagers/GuardItems.java index 3c2a0e8..933ec15 100644 --- a/src/main/java/tallestegg/guardvillagers/GuardItems.java +++ b/src/main/java/tallestegg/guardvillagers/GuardItems.java @@ -1,24 +1,24 @@ package tallestegg.guardvillagers; import com.google.common.base.Predicate; - +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.SpawnEggItem; -import net.minecraftforge.common.ForgeSpawnEggItem; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.DeferredSpawnEggItem; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; -@Mod.EventBusSubscriber(modid = GuardVillagers.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) +//@Mod.EventBusSubscriber(modid = GuardVillagers.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) public class GuardItems { - public static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, GuardVillagers.MODID); - public static final RegistryObject GUARD_SPAWN_EGG = ITEMS.register("guard_spawn_egg", () -> new ForgeSpawnEggItem(GuardEntityType.GUARD, 5651507, 9804699, new Item.Properties())); - public static final RegistryObject ILLUSIONER_SPAWN_EGG = ITEMS.register("illusioner_spawn_egg", () -> new SpawnEggItem(EntityType.ILLUSIONER, 9804699, 4547222, new Item.Properties())); + public static final DeferredRegister ITEMS = DeferredRegister.create(Registries.ITEM, GuardVillagers.MODID); + public static final DeferredHolder GUARD_SPAWN_EGG = ITEMS.register("guard_spawn_egg", () -> new DeferredSpawnEggItem(GuardEntityType.GUARD, 5651507, 9804699, new Item.Properties())); + public static final DeferredHolder ILLUSIONER_SPAWN_EGG = ITEMS.register("illusioner_spawn_egg", () -> new SpawnEggItem(EntityType.ILLUSIONER, 9804699, 4547222, new Item.Properties())); public static InteractionHand getHandWith(LivingEntity livingEntity, Predicate itemPredicate) { return itemPredicate.test(livingEntity.getMainHandItem().getItem()) ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; diff --git a/src/main/java/tallestegg/guardvillagers/GuardLootTables.java b/src/main/java/tallestegg/guardvillagers/GuardLootTables.java index 4a4791f..33fb9d8 100644 --- a/src/main/java/tallestegg/guardvillagers/GuardLootTables.java +++ b/src/main/java/tallestegg/guardvillagers/GuardLootTables.java @@ -1,28 +1,25 @@ package tallestegg.guardvillagers; -import java.util.function.Consumer; - import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; - import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import java.util.function.Consumer; + public class GuardLootTables { public static final BiMap REGISTRY = HashBiMap.create(); public static final LootContextParamSet SLOT = register("slot", (p_216252_0_) -> { p_216252_0_.required(LootContextParams.THIS_ENTITY); }); - public static final ResourceLocation GUARD_MAIN_HAND = new ResourceLocation(GuardVillagers.MODID, "entities/guard_main_hand"); public static final ResourceLocation GUARD_OFF_HAND = new ResourceLocation(GuardVillagers.MODID, "entities/guard_off_hand"); public static final ResourceLocation GUARD_HELMET = new ResourceLocation(GuardVillagers.MODID, "entities/guard_helmet"); public static final ResourceLocation GUARD_CHEST = new ResourceLocation(GuardVillagers.MODID, "entities/guard_chestplate"); public static final ResourceLocation GUARD_LEGGINGS = new ResourceLocation(GuardVillagers.MODID, "entities/guard_legs"); public static final ResourceLocation GUARD_FEET = new ResourceLocation(GuardVillagers.MODID, "entities/guard_feet"); - + public static LootContextParamSet register(String p_81429_, Consumer p_81430_) { LootContextParamSet.Builder lootcontextparamset$builder = new LootContextParamSet.Builder(); p_81430_.accept(lootcontextparamset$builder); @@ -30,9 +27,9 @@ public static LootContextParamSet register(String p_81429_, Consumer PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals); public static void registerPackets() { INSTANCE.messageBuilder(GuardOpenInventoryPacket.class, 0).encoder(GuardOpenInventoryPacket::encode).decoder(GuardOpenInventoryPacket::decode).consumerMainThread(GuardOpenInventoryPacket::handle).add(); @@ -42,4 +40,4 @@ public static void openGuardInventory(GuardOpenInventoryPacket packet) { } } } -} +} \ No newline at end of file diff --git a/src/main/java/tallestegg/guardvillagers/GuardVillagers.java b/src/main/java/tallestegg/guardvillagers/GuardVillagers.java index 8b95cb3..3fc220e 100644 --- a/src/main/java/tallestegg/guardvillagers/GuardVillagers.java +++ b/src/main/java/tallestegg/guardvillagers/GuardVillagers.java @@ -5,16 +5,19 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.raid.Raid; import net.minecraft.world.item.CreativeModeTabs; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; -import net.minecraftforge.event.entity.EntityAttributeCreationEvent; -import net.minecraftforge.fml.ModLoadingContext; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.config.ModConfig; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.fml.loading.FMLPaths; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.ModLoadingContext; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.config.ModConfig; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.fml.javafmlmod.FMLJavaModLoadingContext; +import net.neoforged.fml.loading.FMLPaths; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; +import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent; import tallestegg.guardvillagers.client.GuardSounds; import tallestegg.guardvillagers.configuration.GuardConfig; import tallestegg.guardvillagers.entities.Guard; @@ -23,18 +26,18 @@ public class GuardVillagers { public static final String MODID = "guardvillagers"; - public GuardVillagers() { + public GuardVillagers(IEventBus modEventBus, Dist dist) { ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, GuardConfig.COMMON_SPEC); GuardConfig.loadConfig(GuardConfig.COMMON_SPEC, FMLPaths.CONFIGDIR.get().resolve(MODID + "-common.toml").toString()); ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, GuardConfig.CLIENT_SPEC); - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff); - MinecraftForge.EVENT_BUS.register(this); - GuardEntityType.ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus()); - GuardItems.ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); - GuardSounds.SOUNDS.register(FMLJavaModLoadingContext.get().getModEventBus()); - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::addAttributes); - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::addCreativeTabs); + modEventBus.addListener(this::setup); + NeoForge.EVENT_BUS.register(HandlerEvents.class); + NeoForge.EVENT_BUS.register(VillagerToGuard.class); + GuardEntityType.ENTITIES.register(modEventBus); + GuardItems.ITEMS.register(modEventBus); + GuardSounds.SOUNDS.register(modEventBus); + modEventBus.addListener(this::addAttributes); + modEventBus.addListener(this::addCreativeTabs); GuardPacketHandler.registerPackets(); } @@ -43,6 +46,7 @@ public static boolean hotvChecker(Player player, Guard guard) { || !GuardConfig.giveGuardStuffHOTV || guard.getPlayerReputation(player) > GuardConfig.reputationRequirement && !player.level().isClientSide(); } + @SubscribeEvent private void addCreativeTabs(final BuildCreativeModeTabContentsEvent event) { if (event.getTabKey() == CreativeModeTabs.SPAWN_EGGS) { event.accept(GuardItems.GUARD_SPAWN_EGG.get()); @@ -50,15 +54,14 @@ private void addCreativeTabs(final BuildCreativeModeTabContentsEvent event) { } } + @SubscribeEvent private void setup(final FMLCommonSetupEvent event) { if (GuardConfig.IllusionerRaids) Raid.RaiderType.create("thebluemengroup", EntityType.ILLUSIONER, new int[]{0, 0, 0, 0, 0, 1, 1, 2}); } + @SubscribeEvent private void addAttributes(final EntityAttributeCreationEvent event) { event.put(GuardEntityType.GUARD.get(), Guard.createAttributes().build()); } - - private void doClientStuff(final FMLClientSetupEvent event) { - } } diff --git a/src/main/java/tallestegg/guardvillagers/HandlerEvents.java b/src/main/java/tallestegg/guardvillagers/HandlerEvents.java index 6b64e13..41e4c57 100644 --- a/src/main/java/tallestegg/guardvillagers/HandlerEvents.java +++ b/src/main/java/tallestegg/guardvillagers/HandlerEvents.java @@ -18,12 +18,12 @@ import net.minecraft.world.entity.npc.Villager; import net.minecraft.world.entity.raid.Raider; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.event.entity.EntityJoinLevelEvent; -import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; -import net.minecraftforge.event.entity.living.LivingEvent; -import net.minecraftforge.event.entity.living.LivingHurtEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent; +import net.neoforged.neoforge.event.entity.living.LivingChangeTargetEvent; +import net.neoforged.neoforge.event.entity.living.LivingEvent; +import net.neoforged.neoforge.event.entity.living.LivingHurtEvent; import tallestegg.guardvillagers.configuration.GuardConfig; import tallestegg.guardvillagers.entities.Guard; import tallestegg.guardvillagers.entities.ai.goals.AttackEntityDaytimeGoal; @@ -129,7 +129,7 @@ public static void onLivingSpawned(EntityJoinLevelEvent event) { if (mob instanceof IronGolem golem) { HurtByTargetGoal tolerateFriendlyFire = new HurtByTargetGoal(golem, Guard.class).setAlertOthers(); - golem.targetSelector.availableGoals.stream().map(it -> it.goal).filter(it -> it instanceof HurtByTargetGoal).findFirst().ifPresent(angerGoal -> { + golem.targetSelector.getAvailableGoals().stream().map(it -> it.getGoal()).filter(it -> it instanceof HurtByTargetGoal).findFirst().ifPresent(angerGoal -> { golem.targetSelector.removeGoal(angerGoal); golem.targetSelector.addGoal(2, tolerateFriendlyFire); }); diff --git a/src/main/java/tallestegg/guardvillagers/VillagerToGuard.java b/src/main/java/tallestegg/guardvillagers/VillagerToGuard.java index e01b547..9c54dc6 100644 --- a/src/main/java/tallestegg/guardvillagers/VillagerToGuard.java +++ b/src/main/java/tallestegg/guardvillagers/VillagerToGuard.java @@ -1,25 +1,24 @@ package tallestegg.guardvillagers; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.gossip.GossipType; import net.minecraft.world.entity.ai.memory.MemoryModuleType; -import net.minecraft.world.entity.ai.village.ReputationEventType; import net.minecraft.world.entity.npc.Villager; import net.minecraft.world.entity.npc.VillagerProfession; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.item.CrossbowItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.SwordItem; -import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.world.effect.MobEffects; -import net.minecraft.world.InteractionHand; -import net.minecraft.sounds.SoundEvents; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; import tallestegg.guardvillagers.configuration.GuardConfig; import tallestegg.guardvillagers.entities.Guard; diff --git a/src/main/java/tallestegg/guardvillagers/client/GuardClientEvents.java b/src/main/java/tallestegg/guardvillagers/client/GuardClientEvents.java index 04a41ab..2e892ef 100644 --- a/src/main/java/tallestegg/guardvillagers/client/GuardClientEvents.java +++ b/src/main/java/tallestegg/guardvillagers/client/GuardClientEvents.java @@ -2,10 +2,10 @@ import net.minecraft.client.model.geom.ModelLayerLocation; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.EntityRenderersEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.client.event.EntityRenderersEvent; import tallestegg.guardvillagers.GuardEntityType; import tallestegg.guardvillagers.GuardVillagers; import tallestegg.guardvillagers.client.models.GuardArmorModel; diff --git a/src/main/java/tallestegg/guardvillagers/client/GuardSounds.java b/src/main/java/tallestegg/guardvillagers/client/GuardSounds.java index 93715e7..4197366 100644 --- a/src/main/java/tallestegg/guardvillagers/client/GuardSounds.java +++ b/src/main/java/tallestegg/guardvillagers/client/GuardSounds.java @@ -1,17 +1,20 @@ package tallestegg.guardvillagers.client; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.NeoForgeMod; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; +import net.neoforged.neoforge.registries.NeoForgeRegistriesSetup; import tallestegg.guardvillagers.GuardVillagers; -@Mod.EventBusSubscriber(modid = GuardVillagers.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) +//@Mod.EventBusSubscriber(modid = GuardVillagers.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) public class GuardSounds { - public static final DeferredRegister SOUNDS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, GuardVillagers.MODID); - public static final RegistryObject GUARD_AMBIENT = SOUNDS.register("entity.guard.ambient", () -> SoundEvent.createVariableRangeEvent(new ResourceLocation(GuardVillagers.MODID, "entity.guard.ambient"))); - public static final RegistryObject GUARD_DEATH = SOUNDS.register("entity.guard.death", () -> SoundEvent.createVariableRangeEvent(new ResourceLocation(GuardVillagers.MODID, "entity.guard.death"))); - public static final RegistryObject GUARD_HURT = SOUNDS.register("entity.guard.hurt", () -> SoundEvent.createVariableRangeEvent(new ResourceLocation(GuardVillagers.MODID, "entity.guard.hurt"))); + public static final DeferredRegister SOUNDS = DeferredRegister.create(Registries.SOUND_EVENT, GuardVillagers.MODID); + public static final Holder GUARD_AMBIENT = SOUNDS.register("entity.guard.ambient", () -> SoundEvent.createVariableRangeEvent(new ResourceLocation(GuardVillagers.MODID, "entity.guard.ambient"))); + public static final Holder GUARD_DEATH = SOUNDS.register("entity.guard.death", () -> SoundEvent.createVariableRangeEvent(new ResourceLocation(GuardVillagers.MODID, "entity.guard.death"))); + public static final Holder GUARD_HURT = SOUNDS.register("entity.guard.hurt", () -> SoundEvent.createVariableRangeEvent(new ResourceLocation(GuardVillagers.MODID, "entity.guard.hurt"))); } diff --git a/src/main/java/tallestegg/guardvillagers/client/gui/GuardInventoryScreen.java b/src/main/java/tallestegg/guardvillagers/client/gui/GuardInventoryScreen.java index 30e505f..893befe 100644 --- a/src/main/java/tallestegg/guardvillagers/client/gui/GuardInventoryScreen.java +++ b/src/main/java/tallestegg/guardvillagers/client/gui/GuardInventoryScreen.java @@ -47,13 +47,13 @@ public void init() { super.init(); if (GuardConfig.followHero && player.hasEffect(MobEffects.HERO_OF_THE_VILLAGE) || !GuardConfig.followHero) { this.addRenderableWidget(new GuardGuiButton(this.leftPos + 100, this.height / 2 - 40, 20, 18, GUARD_FOLLOWING_ICONS, GUARD_NOT_FOLLOWING_ICONS, true, (p_214086_1_) -> { - GuardPacketHandler.INSTANCE.send(new GuardFollowPacket(guard.getId()), Minecraft.getInstance().getConnection().getConnection()); + GuardPacketHandler.INSTANCE.sendToServer(new GuardFollowPacket(guard.getId())); })); } if (GuardConfig.setGuardPatrolHotv && player.hasEffect(MobEffects.HERO_OF_THE_VILLAGE) || !GuardConfig.setGuardPatrolHotv) { this.addRenderableWidget(new GuardGuiButton(this.leftPos + 120, this.height / 2 - 40, 20, 18, GUARD_PATROLLING_ICONS, GUARD_NOT_PATROLLING_ICONS, false, (p_214086_1_) -> { buttonPressed = !buttonPressed; - GuardPacketHandler.INSTANCE.send(new GuardSetPatrolPosPacket(guard.getId(), buttonPressed), Minecraft.getInstance().getConnection().getConnection()); + GuardPacketHandler.INSTANCE.sendToServer(new GuardSetPatrolPosPacket(guard.getId(), buttonPressed)); })); } } diff --git a/src/main/java/tallestegg/guardvillagers/configuration/GuardConfig.java b/src/main/java/tallestegg/guardvillagers/configuration/GuardConfig.java index 13dc47d..6479c05 100644 --- a/src/main/java/tallestegg/guardvillagers/configuration/GuardConfig.java +++ b/src/main/java/tallestegg/guardvillagers/configuration/GuardConfig.java @@ -3,10 +3,10 @@ import com.electronwill.nightconfig.core.file.CommentedFileConfig; import com.electronwill.nightconfig.core.io.WritingMode; import com.google.common.collect.Lists; -import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.event.config.ModConfigEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.event.config.ModConfigEvent; +import net.neoforged.neoforge.common.ModConfigSpec; import org.apache.commons.lang3.tuple.Pair; import tallestegg.guardvillagers.GuardVillagers; @@ -14,11 +14,11 @@ import java.util.ArrayList; import java.util.List; -@EventBusSubscriber(modid = GuardVillagers.MODID, bus = EventBusSubscriber.Bus.MOD) +@Mod.EventBusSubscriber(modid = GuardVillagers.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) public class GuardConfig { - public static final ForgeConfigSpec COMMON_SPEC; + public static final ModConfigSpec COMMON_SPEC; public static final CommonConfig COMMON; - public static final ForgeConfigSpec CLIENT_SPEC; + public static final ModConfigSpec CLIENT_SPEC; public static final ClientConfig CLIENT; public static boolean RaidAnimals; public static boolean WitchesVillager; @@ -46,10 +46,10 @@ public class GuardConfig { public static List MobBlackList; static { - final Pair specPair = new ForgeConfigSpec.Builder().configure(CommonConfig::new); + final Pair specPair = new ModConfigSpec.Builder().configure(CommonConfig::new); COMMON = specPair.getLeft(); COMMON_SPEC = specPair.getRight(); - final Pair specPair1 = new ForgeConfigSpec.Builder().configure(ClientConfig::new); + final Pair specPair1 = new ModConfigSpec.Builder().configure(ClientConfig::new); CLIENT = specPair1.getLeft(); CLIENT_SPEC = specPair1.getRight(); } @@ -57,7 +57,7 @@ public class GuardConfig { /* *Thanks to AzureDoom and Tslat for letting me know that this is possible on the MMD discord */ - public static void loadConfig(ForgeConfigSpec config, String path) { + public static void loadConfig(ModConfigSpec config, String path) { final CommentedFileConfig file = CommentedFileConfig.builder(new File(path)).sync().autosave() .writingMode(WritingMode.REPLACE).build(); file.load(); @@ -104,37 +104,37 @@ public static void onModConfigEvent(final ModConfigEvent.Loading configEvent) { } public static class CommonConfig { - public final ForgeConfigSpec.BooleanValue RaidAnimals; - public final ForgeConfigSpec.BooleanValue WitchesVillager; - public final ForgeConfigSpec.BooleanValue IllusionerRaids; - public final ForgeConfigSpec.BooleanValue AttackAllMobs; - public final ForgeConfigSpec.BooleanValue VillagersRunFromPolarBears; - public final ForgeConfigSpec.BooleanValue IllagersRunFromPolarBears; - public final ForgeConfigSpec.BooleanValue GuardsRunFromPolarBears; - public final ForgeConfigSpec.BooleanValue GuardsOpenDoors; - public final ForgeConfigSpec.BooleanValue GuardRaiseShield; - public final ForgeConfigSpec.BooleanValue GuardFormation; - public final ForgeConfigSpec.BooleanValue FriendlyFire; - public final ForgeConfigSpec.BooleanValue ConvertVillagerIfHaveHOTV; - public final ForgeConfigSpec.BooleanValue BlacksmithHealing; - public final ForgeConfigSpec.BooleanValue ClericHealing; - public final ForgeConfigSpec.DoubleValue GuardVillagerHelpRange; - public final ForgeConfigSpec.DoubleValue amountOfHealthRegenerated; - public final ForgeConfigSpec.DoubleValue healthModifier; - public final ForgeConfigSpec.DoubleValue speedModifier; - public final ForgeConfigSpec.DoubleValue followRangeModifier; - public final ForgeConfigSpec.BooleanValue guardArrowsHurtVillagers; - public final ForgeConfigSpec.BooleanValue armorersRepairGuardArmor; - public final ForgeConfigSpec.ConfigValue> MobBlackList; - public final ForgeConfigSpec.ConfigValue> MobWhiteList; - public final ForgeConfigSpec.BooleanValue giveGuardStuffHOTV; - public final ForgeConfigSpec.BooleanValue setGuardPatrolHotv; - public final ForgeConfigSpec.BooleanValue followHero; - public final ForgeConfigSpec.IntValue reputationRequirement; - public final ForgeConfigSpec.IntValue reputationRequirementToBeAttacked; - public final ForgeConfigSpec.DoubleValue chanceToDropEquipment; + public final ModConfigSpec.BooleanValue RaidAnimals; + public final ModConfigSpec.BooleanValue WitchesVillager; + public final ModConfigSpec.BooleanValue IllusionerRaids; + public final ModConfigSpec.BooleanValue AttackAllMobs; + public final ModConfigSpec.BooleanValue VillagersRunFromPolarBears; + public final ModConfigSpec.BooleanValue IllagersRunFromPolarBears; + public final ModConfigSpec.BooleanValue GuardsRunFromPolarBears; + public final ModConfigSpec.BooleanValue GuardsOpenDoors; + public final ModConfigSpec.BooleanValue GuardRaiseShield; + public final ModConfigSpec.BooleanValue GuardFormation; + public final ModConfigSpec.BooleanValue FriendlyFire; + public final ModConfigSpec.BooleanValue ConvertVillagerIfHaveHOTV; + public final ModConfigSpec.BooleanValue BlacksmithHealing; + public final ModConfigSpec.BooleanValue ClericHealing; + public final ModConfigSpec.DoubleValue GuardVillagerHelpRange; + public final ModConfigSpec.DoubleValue amountOfHealthRegenerated; + public final ModConfigSpec.DoubleValue healthModifier; + public final ModConfigSpec.DoubleValue speedModifier; + public final ModConfigSpec.DoubleValue followRangeModifier; + public final ModConfigSpec.BooleanValue guardArrowsHurtVillagers; + public final ModConfigSpec.BooleanValue armorersRepairGuardArmor; + public final ModConfigSpec.ConfigValue> MobBlackList; + public final ModConfigSpec.ConfigValue> MobWhiteList; + public final ModConfigSpec.BooleanValue giveGuardStuffHOTV; + public final ModConfigSpec.BooleanValue setGuardPatrolHotv; + public final ModConfigSpec.BooleanValue followHero; + public final ModConfigSpec.IntValue reputationRequirement; + public final ModConfigSpec.IntValue reputationRequirementToBeAttacked; + public final ModConfigSpec.DoubleValue chanceToDropEquipment; - public CommonConfig(ForgeConfigSpec.Builder builder) { + public CommonConfig(ModConfigSpec.Builder builder) { builder.push("raids and illagers"); RaidAnimals = builder.comment("Illagers In Raids Attack Animals?").translation(GuardVillagers.MODID + ".config.RaidAnimals").define("Illagers in raids attack animals?", false); WitchesVillager = builder.comment("Witches Attack Villagers?").translation(GuardVillagers.MODID + ".config.WitchesVillager").define("Witches attack villagers?", true); @@ -179,10 +179,10 @@ public CommonConfig(ForgeConfigSpec.Builder builder) { } public static class ClientConfig { - public final ForgeConfigSpec.BooleanValue GuardSteve; - public final ForgeConfigSpec.BooleanValue bigHeadBabyVillager; + public final ModConfigSpec.BooleanValue GuardSteve; + public final ModConfigSpec.BooleanValue bigHeadBabyVillager; - public ClientConfig(ForgeConfigSpec.Builder builder) { + public ClientConfig(ModConfigSpec.Builder builder) { GuardSteve = builder.comment("Textures not included, make your own textures by making a resource pack that adds guard_steve_0 - 6").translation(GuardVillagers.MODID + ".config.steveModel").define("Have guards use the steve model?", false); bigHeadBabyVillager = builder.define("Have baby villagers have big heads like in bedrock?", true); } diff --git a/src/main/java/tallestegg/guardvillagers/entities/Guard.java b/src/main/java/tallestegg/guardvillagers/entities/Guard.java index d3f17dd..03c3841 100644 --- a/src/main/java/tallestegg/guardvillagers/entities/Guard.java +++ b/src/main/java/tallestegg/guardvillagers/entities/Guard.java @@ -59,10 +59,12 @@ import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.AABB; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.event.entity.player.PlayerContainerEvent; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.common.NeoForgeEventHandler; +import net.neoforged.neoforge.common.ToolActions; +import net.neoforged.neoforge.event.EventHooks; +import net.neoforged.neoforge.event.entity.player.PlayerContainerEvent; +import net.neoforged.neoforge.network.PacketDistributor; import tallestegg.guardvillagers.GuardItems; import tallestegg.guardvillagers.GuardLootTables; import tallestegg.guardvillagers.GuardPacketHandler; @@ -74,6 +76,7 @@ import javax.annotation.Nullable; import java.util.*; import java.util.function.Predicate; +import java.util.function.Supplier; public class Guard extends PathfinderMob implements CrossbowAttackMob, RangedAttackMob, NeutralMob, ContainerListener, ReputationEventHandler { protected static final EntityDataAccessor> OWNER_UNIQUE_ID = SynchedEntityData.defineId(Guard.class, EntityDataSerializers.OPTIONAL_UUID); @@ -107,12 +110,10 @@ public class Guard extends PathfinderMob implements CrossbowAttackMob, RangedAtt protected boolean spawnWithArmor; private int remainingPersistentAngerTime; private UUID persistentAngerTarget; - private net.minecraftforge.common.util.LazyOptional itemHandler; public Guard(EntityType type, Level world) { super(type, world); this.guardInventory.addListener(this); - this.itemHandler = net.minecraftforge.common.util.LazyOptional.of(() -> new net.minecraftforge.items.wrapper.InvWrapper(this.guardInventory)); this.setPersistenceRequired(); if (GuardConfig.GuardsOpenDoors) ((GroundPathNavigation) this.getNavigation()).setCanOpenDoors(true); } @@ -186,7 +187,7 @@ public void setPatrolPos(BlockPos position) { @Override protected SoundEvent getAmbientSound() { - return GuardSounds.GUARD_AMBIENT.get(); + return GuardSounds.GUARD_AMBIENT.value(); } @Override @@ -194,13 +195,13 @@ protected SoundEvent getHurtSound(DamageSource damageSourceIn) { if (this.isBlocking()) { return SoundEvents.SHIELD_BLOCK; } else { - return GuardSounds.GUARD_HURT.get(); + return GuardSounds.GUARD_HURT.value(); } } @Override protected SoundEvent getDeathSound() { - return GuardSounds.GUARD_DEATH.get(); + return GuardSounds.GUARD_DEATH.value(); } @Override @@ -321,7 +322,7 @@ protected void completeUsingItem() { if (!this.useItem.isEmpty() && this.isUsingItem()) { this.triggerItemUseEffects(this.useItem, 16); ItemStack copy = this.useItem.copy(); - ItemStack itemstack = net.minecraftforge.event.ForgeEventFactory.onItemUseFinish(this, copy, getUseItemRemainingTicks(), this.useItem.finishUsingItem(level(), this)); + ItemStack itemstack = net.neoforged.neoforge.event.EventHooks.onItemUseFinish(this, copy, getUseItemRemainingTicks(), this.useItem.finishUsingItem(this.level(), this)); if (itemstack != this.useItem) { this.setItemInHand(interactionhand, itemstack); } @@ -413,7 +414,7 @@ public boolean isImmobile() { @Override public void die(DamageSource source) { - if ((level().getDifficulty() == Difficulty.NORMAL || level().getDifficulty() == Difficulty.HARD) && source.getEntity() instanceof Zombie && net.minecraftforge.event.ForgeEventFactory.canLivingConvert((LivingEntity) source.getEntity(), EntityType.ZOMBIE_VILLAGER, (timer) -> { + if ((level().getDifficulty() == Difficulty.NORMAL || level().getDifficulty() == Difficulty.HARD) && source.getEntity() instanceof Zombie && EventHooks.canLivingConvert((LivingEntity) source.getEntity(), EntityType.ZOMBIE_VILLAGER, (timer) -> { })) { ZombieVillager zombieguard = this.convertTo(EntityType.ZOMBIE_VILLAGER, true); if (level().getDifficulty() != Difficulty.HARD && this.random.nextBoolean() || zombieguard == null) { @@ -484,7 +485,7 @@ protected void blockUsingShield(LivingEntity entityIn) { @Override protected void hurtCurrentlyUsedShield(float damage) { - if (this.useItem.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) { + if (this.useItem.canPerformAction(ToolActions.SHIELD_BLOCK)) { if (damage >= 3.0F) { int i = 1 + Mth.floor(damage); InteractionHand hand = this.getUsedItemHand(); @@ -506,7 +507,7 @@ protected void hurtCurrentlyUsedShield(float damage) { public void startUsingItem(InteractionHand hand) { super.startUsingItem(hand); ItemStack itemstack = this.getItemInHand(hand); - if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) { + if (itemstack.canPerformAction(ToolActions.SHIELD_BLOCK)) { AttributeInstance modifiableattributeinstance = this.getAttribute(Attributes.MOVEMENT_SPEED); modifiableattributeinstance.removeModifier(USE_ITEM_SPEED_PENALTY.getId()); modifiableattributeinstance.addTransientModifier(USE_ITEM_SPEED_PENALTY); @@ -832,7 +833,7 @@ protected void hurtArmor(DamageSource damageSource, float damage) { @Override public void thunderHit(ServerLevel p_241841_1_, LightningBolt p_241841_2_) { - if (p_241841_1_.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.WITCH, (timer) -> { + if (p_241841_1_.getDifficulty() != Difficulty.PEACEFUL && EventHooks.canLivingConvert(this, EntityType.WITCH, (timer) -> { })) { Witch witchentity = EntityType.WITCH.create(p_241841_1_); if (witchentity == null) return; @@ -881,28 +882,12 @@ public void openGui(ServerPlayer player) { } this.interacting = true; player.nextContainerCounter(); - GuardPacketHandler.INSTANCE.send(new GuardOpenInventoryPacket(player.containerCounter, this.guardInventory.getContainerSize(), this.getId()), PacketDistributor.PLAYER.with(player)); + GuardPacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new GuardOpenInventoryPacket(player.containerCounter, this.guardInventory.getContainerSize(), this.getId())); player.containerMenu = new GuardContainer(player.containerCounter, player.getInventory(), this.guardInventory, this); player.initMenu(player.containerMenu); - MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, player.containerMenu)); + NeoForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, player.containerMenu)); } - @Override - public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { - if (this.isAlive() && capability == ForgeCapabilities.ITEM_HANDLER && itemHandler != null) - return itemHandler.cast(); - return super.getCapability(capability, facing); - } - - @Override - public void invalidateCaps() { - super.invalidateCaps(); - if (itemHandler != null) { - net.minecraftforge.common.util.LazyOptional oldHandler = itemHandler; - itemHandler = null; - oldHandler.invalidate(); - } - } public boolean isEating() { return GuardEatFoodGoal.isConsumable(this.getUseItem()) && this.isUsingItem(); diff --git a/src/main/java/tallestegg/guardvillagers/entities/ai/goals/FollowShieldGuards.java b/src/main/java/tallestegg/guardvillagers/entities/ai/goals/FollowShieldGuards.java index 4f9fd85..ab3d194 100644 --- a/src/main/java/tallestegg/guardvillagers/entities/ai/goals/FollowShieldGuards.java +++ b/src/main/java/tallestegg/guardvillagers/entities/ai/goals/FollowShieldGuards.java @@ -8,6 +8,7 @@ import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.ai.util.DefaultRandomPos; import net.minecraft.world.phys.Vec3; +import net.neoforged.neoforge.common.ToolActions; import tallestegg.guardvillagers.entities.Guard; public class FollowShieldGuards extends Goal { @@ -29,7 +30,7 @@ public boolean canUse() { this.taskOwner.getBoundingBox().inflate(8.0D, 8.0D, 8.0D)); if (!list.isEmpty()) { for (Guard guard : list) { - if (!guard.isInvisible() && guard.getOffhandItem().canPerformAction(net.minecraftforge.common.ToolActions.SHIELD_BLOCK) && guard.isBlocking() + if (!guard.isInvisible() && guard.getOffhandItem().canPerformAction(ToolActions.SHIELD_BLOCK) && guard.isBlocking() && this.taskOwner.level() .getNearbyEntities(Guard.class, NEARBY_GUARDS.range(3.0D), guard, this.taskOwner.getBoundingBox().inflate(5.0D)) diff --git a/src/main/java/tallestegg/guardvillagers/entities/ai/goals/RaiseShieldGoal.java b/src/main/java/tallestegg/guardvillagers/entities/ai/goals/RaiseShieldGoal.java index 8ad7766..68a6c4d 100644 --- a/src/main/java/tallestegg/guardvillagers/entities/ai/goals/RaiseShieldGoal.java +++ b/src/main/java/tallestegg/guardvillagers/entities/ai/goals/RaiseShieldGoal.java @@ -1,15 +1,16 @@ package tallestegg.guardvillagers.entities.ai.goals; -import net.minecraft.world.entity.monster.RangedAttackMob; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.monster.Creeper; +import net.minecraft.world.entity.monster.RangedAttackMob; import net.minecraft.world.entity.monster.Ravager; import net.minecraft.world.item.BowItem; import net.minecraft.world.item.CrossbowItem; -import net.minecraft.world.InteractionHand; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.ToolActions; import tallestegg.guardvillagers.configuration.GuardConfig; import tallestegg.guardvillagers.entities.Guard; @@ -22,8 +23,8 @@ public RaiseShieldGoal(Guard guard) { @Override public boolean canUse() { - return !CrossbowItem.isCharged(guard.getMainHandItem()) && (guard.getOffhandItem().getItem().canPerformAction(guard.getOffhandItem(), net.minecraftforge.common.ToolActions.SHIELD_BLOCK) && raiseShield() && guard.shieldCoolDown == 0 - && !guard.getOffhandItem().getItem().equals(ForgeRegistries.ITEMS.getValue(new ResourceLocation("bigbrain:buckler")))); + return !CrossbowItem.isCharged(guard.getMainHandItem()) && (guard.getOffhandItem().getItem().canPerformAction(guard.getOffhandItem(), ToolActions.SHIELD_BLOCK) && raiseShield() && guard.shieldCoolDown == 0 + && !guard.getOffhandItem().getItem().equals(Registries.ITEM.registry().equals(new ResourceLocation("bigbrain:buckler")))); } @Override @@ -33,7 +34,7 @@ public boolean canContinueToUse() { @Override public void start() { - if (guard.getOffhandItem().getItem().canPerformAction(guard.getOffhandItem(), net.minecraftforge.common.ToolActions.SHIELD_BLOCK)) + if (guard.getOffhandItem().getItem().canPerformAction(guard.getOffhandItem(), ToolActions.SHIELD_BLOCK)) guard.startUsingItem(InteractionHand.OFF_HAND); } diff --git a/src/main/java/tallestegg/guardvillagers/networking/GuardFollowPacket.java b/src/main/java/tallestegg/guardvillagers/networking/GuardFollowPacket.java index 84f5004..cc22edd 100644 --- a/src/main/java/tallestegg/guardvillagers/networking/GuardFollowPacket.java +++ b/src/main/java/tallestegg/guardvillagers/networking/GuardFollowPacket.java @@ -5,10 +5,12 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.Entity; -import net.minecraftforge.event.network.CustomPayloadEvent; +import net.neoforged.neoforge.network.NetworkEvent; import tallestegg.guardvillagers.entities.Guard; -public class GuardFollowPacket { +import java.util.function.Supplier; + +public class GuardFollowPacket{ private final int entityId; public GuardFollowPacket(int entityId) { @@ -27,19 +29,24 @@ public int getEntityId() { return this.entityId; } - public void handle(CustomPayloadEvent.Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - if (player != null && player.level() instanceof ServerLevel) { - Entity entity = player.level().getEntity(this.getEntityId()); - if (entity instanceof Guard) { - Guard guard = (Guard) entity; - guard.setFollowing(!guard.isFollowing()); - guard.setOwnerId(player.getUUID()); - guard.playSound(SoundEvents.VILLAGER_YES, 1.0F, 1.0F); - } - } + public void handle(NetworkEvent.Context ctx) { + ctx.enqueueWork(() -> { + ctx.enqueueWork(new Runnable() { + @Override + public void run() { + ServerPlayer player = ctx.getSender(); + if (player != null && player.level() instanceof ServerLevel) { + Entity entity = player.level().getEntity(getEntityId()); + if (entity instanceof Guard) { + Guard guard = (Guard) entity; + guard.setFollowing(!guard.isFollowing()); + guard.setOwnerId(player.getUUID()); + guard.playSound(SoundEvents.VILLAGER_YES, 1.0F, 1.0F); + } + } + } + }); }); - context.setPacketHandled(true); + ctx.setPacketHandled(true); } } \ No newline at end of file diff --git a/src/main/java/tallestegg/guardvillagers/networking/GuardOpenInventoryPacket.java b/src/main/java/tallestegg/guardvillagers/networking/GuardOpenInventoryPacket.java index 24d7af3..a933942 100644 --- a/src/main/java/tallestegg/guardvillagers/networking/GuardOpenInventoryPacket.java +++ b/src/main/java/tallestegg/guardvillagers/networking/GuardOpenInventoryPacket.java @@ -1,7 +1,7 @@ package tallestegg.guardvillagers.networking; import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.event.network.CustomPayloadEvent; +import net.neoforged.neoforge.network.NetworkEvent; import tallestegg.guardvillagers.GuardPacketHandler; public class GuardOpenInventoryPacket { @@ -37,7 +37,7 @@ public int getEntityId() { return this.entityId; } - public void handle(CustomPayloadEvent.Context context) { + public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { GuardPacketHandler.openGuardInventory(this); }); diff --git a/src/main/java/tallestegg/guardvillagers/networking/GuardSetPatrolPosPacket.java b/src/main/java/tallestegg/guardvillagers/networking/GuardSetPatrolPosPacket.java index 2ee99f4..b7f4874 100644 --- a/src/main/java/tallestegg/guardvillagers/networking/GuardSetPatrolPosPacket.java +++ b/src/main/java/tallestegg/guardvillagers/networking/GuardSetPatrolPosPacket.java @@ -5,7 +5,7 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; -import net.minecraftforge.event.network.CustomPayloadEvent; +import net.neoforged.neoforge.network.NetworkEvent; import tallestegg.guardvillagers.entities.Guard; public class GuardSetPatrolPosPacket { @@ -38,7 +38,7 @@ public void setPressed(boolean pressed) { this.pressed = pressed; } - public void handle(CustomPayloadEvent.Context context) { + public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); if (player != null && player.level() instanceof ServerLevel) { diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 5aef9b8..0043891 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -1,15 +1,9 @@ -public net.minecraft.world.entity.Mob f_21351_ # inventoryArmor -public net.minecraft.world.entity.Mob f_21350_ # inventoryHands -public net.minecraft.world.entity.ai.goal.MeleeAttackGoal f_25540_ # attacker -public net.minecraft.world.entity.ai.goal.GoalSelector f_25345_ #goals -public net.minecraft.world.entity.ai.goal.WrappedGoal f_25994_ #inner -public net.minecraft.world.entity.Entity m_20124_(Lnet/minecraft/world/entity/Pose;)V # setPose -public net.minecraft.world.entity.ai.goal.MeleeAttackGoal f_25548_ # nah -public net.minecraft.world.level.storage.loot.parameters.LootContextParamSets m_81428_(Ljava/lang/String;Ljava/util/function/Consumer;)Lnet/minecraft/world/level/storage/loot/parameters/LootContextParamSet; # register -public net.minecraft.world.entity.ai.goal.MeleeAttackGoal f_25543_ # path -protected net.minecraft.client.gui.components.ImageButton f_94224_ # xTexStart -protected net.minecraft.client.gui.components.ImageButton f_94227_ # textureWidth -protected net.minecraft.client.gui.components.ImageButton f_94228_ # textureHeight -protected net.minecraft.client.gui.components.ImageButton f_94225_ # yTexStart -protected net.minecraft.client.gui.components.ImageButton f_94226_ # yDiffText -public net.minecraft.world.entity.npc.Villager f_35378_ # lastGossipTime \ No newline at end of file +public net.minecraft.world.entity.Mob armorItems +public net.minecraft.world.entity.Mob handItems +public net.minecraft.world.entity.ai.goal.MeleeAttackGoal attacker +public net.minecraft.world.entity.ai.goal.GoalSelector goals +public net.minecraft.world.entity.ai.goal.WrappedGoal inner +public net.minecraft.world.entity.Entity setPose(Lnet/minecraft/world/entity/Pose;)V +public net.minecraft.world.entity.ai.goal.MeleeAttackGoal ticksUntilNextAttack +public net.minecraft.world.entity.ai.goal.MeleeAttackGoal path +public net.minecraft.world.entity.npc.Villager lastGossipTime \ No newline at end of file diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index 764e7d7..3b665da 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -1,29 +1,44 @@ + modLoader="javafml" #mandatory -loaderVersion="[46,)" #mandatory (28 is current forge version) +loaderVersion="${loader_version_range}" #mandatory +license="${mod_license}" issueTrackerURL="https://github.com/seymourimadeit/guardvillagers/issues" #optional -license="MIT for the code, ARR for the assets" -# A list of mods - how many allowed here is determined by the individual mod loader [[mods]] #mandatory -modId="guardvillagers" #mandatory -version="${file.jarVersion}" #mandatory -displayName="Guard Villagers" #mandatory -updateJSONURL="https://raw.githubusercontent.com/seymourimadeit/guardvillagers/master/update.json" #optional +modId="${mod_id}" #mandatory +version="${mod_version}" #mandatory +displayName="${mod_name}" #mandatory +authors="${mod_authors}" #optional displayURL="https://www.curseforge.com/minecraft/mc-mods/guard-villagers" #optional -credits="TallestEgg and HadeZ/SadNya69 for the textures." #optional -authors="TallestEgg, HadeZ/SadNya69 for the textures." #optional -description=''' -Need some help with pest control? The Guards are ready to help! -''' -[[dependencies.guardvillagers]] #optional - modId="forge" #mandatory +updateJSONURL="https://raw.githubusercontent.com/seymourimadeit/guardvillagers/master/update.json" #optional +logoFile="guard_villagers.png" #optional +# The description text for the mod (multi line!) (#mandatory) +description='''${mod_description}''' +# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. +[[dependencies.${mod_id}]] #optional + # the modid of the dependency + modId="neoforge" #mandatory + # Does this dependency have to exist - if not, ordering below must be specified mandatory=true #mandatory - versionRange="[46.0.0,)" #mandatory + # The version range of the dependency + versionRange="${neo_version_range}" #mandatory + # An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory + # BEFORE - This mod is loaded BEFORE the dependency + # AFTER - This mod is loaded AFTER the dependency ordering="NONE" + # Side this dependency is applied on - BOTH, CLIENT, or SERVER side="BOTH" # Here's another dependency -[[dependencies.guardvillagers]] +[[dependencies.${mod_id}]] modId="minecraft" mandatory=true - versionRange="[1.20.2, 1.20.3]" + # This version range declares a minimum of the current minecraft version up to but not including the next major version + versionRange="${minecraft_version_range}" ordering="NONE" - side="BOTH" \ No newline at end of file + side="BOTH" +[[mixins]] + config="guardvillagers.mixins.json" +# Features are specific properties of the game environment, that you may want to declare you require. This example declares +# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't +# stop your mod loading on the server for example. +#[features.${mod_id}] +#openGLVersion="[3.2,)" diff --git a/src/main/resources/guard_villagers.png b/src/main/resources/guard_villagers.png new file mode 100644 index 0000000..47c176c Binary files /dev/null and b/src/main/resources/guard_villagers.png differ diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta index 4070d6d..59c5240 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -1,7 +1,8 @@ { - "pack": { - "description": "Hi!", - "pack_format": 11, - "_comment": "A pack_format of 4 requires json lang files. Note: we require v4 pack meta for all mods." - } + "pack": { + "description": { + "text": "${mod_id} resources" + }, + "pack_format": ${pack_format_number} + } }