commit 4368abcb2a9495cb13dc4720d203fdca444509bf Author: LordMZTE Date: Sat Oct 28 18:33:26 2023 +0200 init diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..1bd68c9 --- /dev/null +++ b/.clang-format @@ -0,0 +1,129 @@ +--- +AccessModifierOffset: 0 +AlignAfterOpenBracket: BlockIndent +AlignArrayOfStructures: None +AlignConsecutiveAssignments: None +AlignConsecutiveMacros: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: DontAlign +AlignOperands: DontAlign +AlignTrailingComments: false +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: [] +BinPackArguments: false +BinPackParameters: false +BitFieldColonSpacing: After +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakAfterJavaFieldAnnotations: true +#BreakArrays: false +BreakBeforeBinaryOperators: All +BreakBeforeBraces: Custom +BreakBeforeConceptDeclarations: true +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +BreakInheritanceList: AfterColon +BreakStringLiterals: true +ColumnLimit: 90 +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DeriveLineEnding: false +DerivePointerAlignment: false +DisableFormat: false # wtf +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: Always +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false +ForEachMacros: ["BOOST_FOREACH"] +IfMacros: [] +IncludeBlocks: Regroup +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: Indent +IndentGotoLabels: true +IndentPPDirectives: BeforeHash +#IndentRequiresClause: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +#InsertBraces: false +InsertTrailingCommas: Wrapped +JavaScriptQuotes: Double +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +LambdaBodyIndentation: OuterScope +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: All +PackConstructorInitializers: NextLine +PointerAlignment: Left +QualifierAlignment: Left +ReferenceAlignment: Left +ReflowComments: true +#RemoveSemicolon: true +#RequiresClausePosition: OwnLine +#RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Always +SortIncludes: false +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: true +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceAroundPointerQualifiers: After +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: false +SpaceBeforeInheritanceColon: false +SpaceBeforeParens: ControlStatementsExceptControlMacros +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesInAngles: Never +SpacesInCStyleCastParentheses: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: false +SpacesInLineCommentPrefix: + Minimum: 0 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: c++20 +StatementAttributeLikeMacros: [] +StatementMacros: [] +TabWidth: 4 +TypenameMacros: [] +UseCRLF: false # wtf +UseTab: Never +WhitespaceSensitiveMacros: ["BOOST_PP_STRINGSIZE"] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..89f5bfe --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ +.factorypath + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..60268b5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,8 @@ +Copyright (C) 2023 Anvilcraft +This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. + +The above copyright notice, this permission notice and the word "ALEC" shall be included in all copies or substantial portions of the Software. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License along with this program. If not, see diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..afb4b18 --- /dev/null +++ b/build.gradle @@ -0,0 +1,97 @@ +plugins { + id "dev.architectury.loom" version "1.1-SNAPSHOT" + id "maven-publish" +} + +sourceCompatibility = targetCompatibility = JavaVersion.VERSION_17 + +archivesBaseName = project.archives_base_name +version = project.mod_version +group = project.maven_group + +loom { + forge { + mixinConfigs = [ + "anvillib.mixins.json" + ] + } +} + +repositories { + maven { + url "https://dl.cloudsmith.io/public/geckolib3/geckolib/maven/" + } +} + +dependencies { + // to change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + + forge "net.minecraftforge:forge:${project.forge_version}" + + modImplementation "software.bernie.geckolib:geckolib-forge-1.18:3.0.57" +} + +processResources { + // this will replace the property "${version}" in your mods.toml + // with the version you've defined in your gradle.properties + filesMatching("META-INF/mods.toml") { + expand "version": project.version + } +} + +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" + options.release = 17 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() +} + +jar { + // add some additional metadata to the jar manifest + manifest { + attributes([ + "Specification-Title" : project.mod_id, + "Specification-Vendor" : project.mod_author, + "Specification-Version" : "1", + "Implementation-Title" : project.name, + "Implementation-Version" : version, + "Implementation-Vendor" : project.mod_author, + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) + } +} + +sourcesJar { + archiveClassifier = "sources" +} + +// configure the maven publication +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + + artifactId = project.archivesBaseName + } + } + + repositories { + if (project.hasProperty("mvnURL")) { + maven { + credentials { + username findProperty("mvnUsername") + password findProperty("mvnPassword") + } + url = findProperty("mvnURL") + } + } + mavenLocal() + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..8a40db2 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,23 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G + +# tell architectury loom that this project is a forge project. +# this will enable us to use the "forge" dependency. +# using archloom without this is possible and will give you a +# "standard" loom installation with some extra features. +loom.platform=forge + +# Base properties + # minecraft version + minecraft_version=1.18.2 + # forge version, latest version can be found on https://files.minecraftforge.net/ + forge_version=1.18.2-40.2.1 + # yarn, latest version can be found on https://fabricmc.net/develop/ + yarn_mappings=1.18.2+build.4 + +# Mod Properties + mod_version=0.1.0 + maven_group=net.anvilcraft + archives_base_name=anvillib-18 + mod_id=anvillib + mod_author=LordMZTE diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..41dfb87 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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 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 +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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +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 + +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 ;; +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +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 + +# 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" ) + + # 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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..606cfc1 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +pluginManagement { + // when using additional gradle plugins like shadow, + // add their repositories to this list! + repositories { + maven { url "https://maven.fabricmc.net/" } + maven { url "https://maven.architectury.dev/" } + maven { url "https://files.minecraftforge.net/maven/" } + gradlePluginPortal() + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/AnvilLib.java b/src/main/java/net/anvilcraft/anvillib/AnvilLib.java new file mode 100644 index 0000000..302eb2a --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/AnvilLib.java @@ -0,0 +1,17 @@ +package net.anvilcraft.anvillib; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import net.minecraftforge.fml.common.Mod; +import software.bernie.geckolib3.GeckoLib; + +@Mod(AnvilLib.MODID) +public class AnvilLib { + public static final String MODID = "anvillib"; + public static final Logger LOGGER = LogManager.getLogger(); + + public AnvilLib() { + GeckoLib.initialize(); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/Util.java b/src/main/java/net/anvilcraft/anvillib/Util.java new file mode 100644 index 0000000..6cf0b05 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/Util.java @@ -0,0 +1,29 @@ +package net.anvilcraft.anvillib; + +import net.minecraft.item.ItemStack; +import net.minecraft.recipe.Ingredient; +import net.minecraft.tag.TagKey; +import net.minecraft.util.Identifier; +import net.minecraft.util.registry.Registry; +import net.minecraftforge.registries.ForgeRegistries; + +public class Util { + public static ItemStack stackFromRegistry(Identifier id) { + if (ForgeRegistries.ITEMS.containsKey(id)) { + return new ItemStack(ForgeRegistries.ITEMS.getValue(id)); + } else if (ForgeRegistries.BLOCKS.containsKey(id)) { + return new ItemStack(ForgeRegistries.BLOCKS.getValue(id)); + } else { + throw new IllegalArgumentException("No block or item with ID " + id + "!"); + } + } + + public static Ingredient ingredientFromString(String s) { + if (s.charAt(0) == '#') + return Ingredient.fromTag( + TagKey.of(Registry.ITEM_KEY, new Identifier(s.substring(1))) + ); + + return Ingredient.ofStacks(stackFromRegistry(new Identifier(s))); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/ClientEventHandler.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/ClientEventHandler.java new file mode 100644 index 0000000..f50b0fa --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/ClientEventHandler.java @@ -0,0 +1,19 @@ +package net.anvilcraft.anvillib.cosmetics; + +import net.anvilcraft.anvillib.AnvilLib; +import net.minecraft.client.render.entity.PlayerEntityRenderer; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.EntityRenderersEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; + +@EventBusSubscriber(modid = AnvilLib.MODID, bus = Bus.MOD, value = { Dist.CLIENT }) +public class ClientEventHandler { + @SubscribeEvent + public static void clientSetup(EntityRenderersEvent.AddLayers event) { + for (String skin : event.getSkins()) + if (event.getSkin(skin) instanceof PlayerEntityRenderer render) + render.addFeature(new CosmeticFeatureRenderer(render, skin)); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticArmorRenderer.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticArmorRenderer.java new file mode 100644 index 0000000..9e7eed3 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticArmorRenderer.java @@ -0,0 +1,413 @@ +package net.anvilcraft.anvillib.cosmetics; + +import java.util.Arrays; +import java.util.Objects; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import org.jetbrains.annotations.ApiStatus.AvailableSince; + +import com.mojang.blaze3d.systems.RenderSystem; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.network.AbstractClientPlayerEntity; +import net.minecraft.client.render.OverlayTexture; +import net.minecraft.client.render.RenderLayer; +import net.minecraft.client.render.VertexConsumer; +import net.minecraft.client.render.VertexConsumerProvider; +import net.minecraft.client.render.entity.model.BipedEntityModel; +import net.minecraft.client.render.entity.model.EntityModelLayers; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.entity.LivingEntity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.Matrix4f; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.Vec3f; +import net.minecraftforge.fml.ModList; +import software.bernie.geckolib3.compat.PatchouliCompat; +import software.bernie.geckolib3.core.IAnimatable; +import software.bernie.geckolib3.core.IAnimatableModel; +import software.bernie.geckolib3.core.controller.AnimationController; +import software.bernie.geckolib3.core.controller.AnimationController.ModelFetcher; +import software.bernie.geckolib3.core.event.predicate.AnimationEvent; +import software.bernie.geckolib3.core.processor.IBone; +import software.bernie.geckolib3.core.util.Color; +import software.bernie.geckolib3.geo.render.built.GeoBone; +import software.bernie.geckolib3.geo.render.built.GeoModel; +import software.bernie.geckolib3.model.AnimatedGeoModel; +import software.bernie.geckolib3.renderers.geo.IGeoRenderer; +import software.bernie.geckolib3.util.EModelRenderCycle; +import software.bernie.geckolib3.util.GeoUtils; +import software.bernie.geckolib3.util.IRenderCycle; +import software.bernie.geckolib3.util.RenderUtils; + +public class CosmeticArmorRenderer extends BipedEntityModel + implements IGeoRenderer, ModelFetcher { + protected CosmeticItem currentArmorItem; + protected LivingEntity entityLiving; + protected float widthScale = 1; + protected float heightScale = 1; + protected Matrix4f dispatchedMat = new Matrix4f(); + protected Matrix4f renderEarlyMat = new Matrix4f(); + + public String headBone = null; + public String bodyBone = null; + public String rightArmBone = null; + public String leftArmBone = null; + public String rightLegBone = null; + public String leftLegBone = null; + + private final AnimatedGeoModel modelProvider; + + protected VertexConsumerProvider rtb = null; + + private IRenderCycle currentModelRenderCycle = EModelRenderCycle.INITIAL; + + { AnimationController.addModelFetcher(this); } + + @Override + @Nullable + public IAnimatableModel apply(IAnimatable t) { + if (t instanceof CosmeticItem) + return this.getGeoModelProvider(); + return null; + } + + public CosmeticArmorRenderer() { + super(MinecraftClient.getInstance().getEntityModelLoader().getModelPart( + EntityModelLayers.PLAYER_INNER_ARMOR + )); + + this.modelProvider = new CosmeticModel(); + } + + @Override + public void render( + MatrixStack poseStack, + VertexConsumer buffer, + int packedLight, + int packedOverlay, + float red, + float green, + float blue, + float alpha + ) { + this.render(0, poseStack, buffer, packedLight); + } + + public void render( + float partialTick, MatrixStack poseStack, VertexConsumer buffer, int packedLight + ) { + GeoModel model = this.modelProvider.getModel( + this.modelProvider.getModelLocation(this.currentArmorItem) + ); + AnimationEvent animationEvent = new AnimationEvent<>( + this.currentArmorItem, + 0, + 0, + MinecraftClient.getInstance().getTickDelta(), + false, // can also be getLastFrameDuration() + Arrays.asList(this.entityLiving) + ); + + poseStack.push(); + poseStack.translate(0, 24 / 16F, 0); + poseStack.scale(-1, -1, 1); + + //this.dispatchedMat = poseStack.last().pose().copy(); + this.dispatchedMat = poseStack.peek().getPositionMatrix().copy(); + + this.modelProvider.setCustomAnimations( + this.currentArmorItem, getInstanceId(this.currentArmorItem), animationEvent + ); + setCurrentModelRenderCycle(EModelRenderCycle.INITIAL); + fitToBiped(); + RenderSystem.setShaderTexture(0, getTextureLocation(this.currentArmorItem)); + + Color renderColor = getRenderColor( + this.currentArmorItem, partialTick, poseStack, null, buffer, packedLight + ); + RenderLayer renderType = getRenderType( + this.currentArmorItem, + partialTick, + poseStack, + null, + buffer, + packedLight, + getTextureLocation(this.currentArmorItem) + ); + + render( + model, + this.currentArmorItem, + partialTick, + renderType, + poseStack, + null, + buffer, + packedLight, + OverlayTexture.DEFAULT_UV, + renderColor.getRed() / 255f, + renderColor.getGreen() / 255f, + renderColor.getBlue() / 255f, + renderColor.getAlpha() / 255f + ); + + if (ModList.get().isLoaded("patchouli")) + PatchouliCompat.patchouliLoaded(poseStack); + + poseStack.pop(); + } + + @Override + public void renderEarly( + CosmeticItem animatable, + MatrixStack poseStack, + float partialTick, + VertexConsumerProvider bufferSource, + VertexConsumer buffer, + int packedLight, + int packedOverlay, + float red, + float green, + float blue, + float alpha + ) { + //this.renderEarlyMat = poseStack.last().pose().copy(); + this.renderEarlyMat = poseStack.peek().getPositionMatrix().copy(); + this.currentArmorItem = animatable; + + IGeoRenderer.super.renderEarly( + animatable, + poseStack, + partialTick, + bufferSource, + buffer, + packedLight, + packedOverlay, + red, + green, + blue, + alpha + ); + } + + @Override + public void renderRecursively( + GeoBone bone, + MatrixStack poseStack, + VertexConsumer buffer, + int packedLight, + int packedOverlay, + float red, + float green, + float blue, + float alpha + ) { + if (bone.isTrackingXform()) { + //Matrix4f poseState = poseStack.last().pose(); + Matrix4f poseState = poseStack.peek().getPositionMatrix(); + Vec3d renderOffset = getRenderOffset(this.currentArmorItem, 1); + Matrix4f localMatrix + = RenderUtils.invertAndMultiplyMatrices(poseState, this.dispatchedMat); + + bone.setModelSpaceXform( + RenderUtils.invertAndMultiplyMatrices(poseState, this.renderEarlyMat) + ); + //localMatrix.translate(new Vec3f(renderOffset)); + localMatrix.addToLastColumn(new Vec3f(renderOffset)); + bone.setLocalSpaceXform(localMatrix); + } + + IGeoRenderer.super.renderRecursively( + bone, poseStack, buffer, packedLight, packedOverlay, red, green, blue, alpha + ); + } + + public Vec3d getRenderOffset(CosmeticItem entity, float partialTick) { + return Vec3d.ZERO; + } + + protected void fitToBiped() { + if (this.headBone != null) { + IBone headBone = this.modelProvider.getBone(this.headBone); + + GeoUtils.copyRotations(this.head, headBone); + headBone.setPositionX(this.head.pivotX); + headBone.setPositionY(-this.head.pivotY); + headBone.setPositionZ(this.head.pivotZ); + } + + if (this.bodyBone != null) { + IBone bodyBone = this.modelProvider.getBone(this.bodyBone); + + GeoUtils.copyRotations(this.body, bodyBone); + bodyBone.setPositionX(this.body.pivotX); + bodyBone.setPositionY(-this.body.pivotY); + bodyBone.setPositionZ(this.body.pivotZ); + } + + if (this.rightArmBone != null) { + IBone rightArmBone = this.modelProvider.getBone(this.rightArmBone); + + GeoUtils.copyRotations(this.rightArm, rightArmBone); + rightArmBone.setPositionX(this.rightArm.pivotX + 5); + rightArmBone.setPositionY(2 - this.rightArm.pivotY); + rightArmBone.setPositionZ(this.rightArm.pivotZ); + } + + if (this.leftArmBone != null) { + IBone leftArmBone = this.modelProvider.getBone(this.leftArmBone); + + GeoUtils.copyRotations(this.leftArm, leftArmBone); + leftArmBone.setPositionX(this.leftArm.pivotX - 5); + leftArmBone.setPositionY(2 - this.leftArm.pivotY); + leftArmBone.setPositionZ(this.leftArm.pivotZ); + } + + if (this.rightLegBone != null) { + IBone rightLegBone = this.modelProvider.getBone(this.rightLegBone); + + GeoUtils.copyRotations(this.rightLeg, rightLegBone); + rightLegBone.setPositionX(this.rightLeg.pivotX + 2); + rightLegBone.setPositionY(12 - this.rightLeg.pivotY); + rightLegBone.setPositionZ(this.rightLeg.pivotZ); + } + + if (this.leftLegBone != null) { + IBone leftLegBone = this.modelProvider.getBone(this.leftLegBone); + + GeoUtils.copyRotations(this.leftLeg, leftLegBone); + leftLegBone.setPositionX(this.leftLeg.pivotX - 2); + leftLegBone.setPositionY(12 - this.leftLeg.pivotY); + leftLegBone.setPositionZ(this.leftLeg.pivotZ); + } + } + + @Override + public AnimatedGeoModel getGeoModelProvider() { + return this.modelProvider; + } + + @AvailableSince(value = "3.1.24") + @Override + @Nonnull + public IRenderCycle getCurrentModelRenderCycle() { + return this.currentModelRenderCycle; + } + + @AvailableSince(value = "3.1.24") + @Override + public void setCurrentModelRenderCycle(IRenderCycle currentModelRenderCycle) { + this.currentModelRenderCycle = currentModelRenderCycle; + } + + @AvailableSince(value = "3.1.24") + @Override + public float getWidthScale(CosmeticItem animatable) { + return this.widthScale; + } + + @AvailableSince(value = "3.1.24") + @Override + public float getHeightScale(CosmeticItem entity) { + return this.heightScale; + } + + @Override + public Identifier getTextureLocation(CosmeticItem animatable) { + return this.modelProvider.getTextureLocation(animatable); + } + + /** + * Everything after this point needs to be called every frame before rendering + */ + public CosmeticArmorRenderer setCurrentItem(LivingEntity entity, CosmeticItem item) { + this.entityLiving = entity; + this.currentArmorItem = item; + + return this; + } + + public final CosmeticArmorRenderer + applyEntityStats(BipedEntityModel defaultArmor) { + this.child = defaultArmor.child; + this.sneaking = defaultArmor.sneaking; + this.riding = defaultArmor.riding; + this.rightArmPose = defaultArmor.rightArmPose; + this.leftArmPose = defaultArmor.leftArmPose; + + return this; + } + + public void filterBones() { + this.headBone = getCurrentCosmetic().getHead(); + this.bodyBone = getCurrentCosmetic().getBody(); + this.leftArmBone = getCurrentCosmetic().getLeftArm(); + this.rightArmBone = getCurrentCosmetic().getRightArm(); + this.leftLegBone = getCurrentCosmetic().getLeftLeg(); + this.rightLegBone = getCurrentCosmetic().getRightLeg(); + + getGeoModelProvider().getModel(getCurrentCosmetic().getModelLocation()); + + this.setBoneVisibility(this.headBone, getCurrentCosmetic().getHead() != null); + this.setBoneVisibility(this.bodyBone, getCurrentCosmetic().getBody() != null); + this.setBoneVisibility( + this.leftArmBone, getCurrentCosmetic().getLeftArm() != null + ); + this.setBoneVisibility( + this.rightArmBone, getCurrentCosmetic().getRightArm() != null + ); + this.setBoneVisibility( + this.leftLegBone, getCurrentCosmetic().getLeftLeg() != null + ); + this.setBoneVisibility( + this.rightLegBone, getCurrentCosmetic().getRightLeg() != null + ); + } + + /** + * Sets a specific bone (and its child-bones) to visible or not + * @param boneName The name of the bone + * @param isVisible Whether the bone should be visible + */ + protected void setBoneVisibility(String boneName, boolean isVisible) { + if (boneName == null) + return; + + this.modelProvider.getBone(boneName).setHidden(!isVisible); + } + + /** + * Use {@link CosmeticArmorRenderer#setBoneVisibility(String, boolean)} + */ + @Deprecated(forRemoval = true) + protected IBone getAndHideBone(String boneName) { + setBoneVisibility(boneName, false); + + return this.modelProvider.getBone(boneName); + } + + @Override + public int getInstanceId(CosmeticItem animatable) { + return Objects.hash( + this.currentArmorItem.getCosmetic().getID(), this.entityLiving.getUuid() + ); + } + + @Override + public void setCurrentRTB(VertexConsumerProvider bufferSource) { + this.rtb = bufferSource; + } + + @Override + public VertexConsumerProvider getCurrentRTB() { + return this.rtb; + } + + public ICosmetic getCurrentCosmetic() { + return this.currentArmorItem.getCosmetic(); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticFeatureRenderer.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticFeatureRenderer.java new file mode 100644 index 0000000..b3e5d19 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticFeatureRenderer.java @@ -0,0 +1,92 @@ +package net.anvilcraft.anvillib.cosmetics; + +import java.util.HashMap; +import java.util.Map; + +import net.minecraft.client.model.ModelPart; +import net.minecraft.client.network.AbstractClientPlayerEntity; +import net.minecraft.client.render.RenderLayer; +import net.minecraft.client.render.VertexConsumer; +import net.minecraft.client.render.VertexConsumerProvider; +import net.minecraft.client.render.entity.PlayerEntityRenderer; +import net.minecraft.client.render.entity.feature.ArmorFeatureRenderer; +import net.minecraft.client.render.entity.model.BipedEntityModel; +import net.minecraft.client.render.entity.model.PlayerEntityModel; +import net.minecraft.client.render.item.ItemRenderer; +import net.minecraft.client.util.math.MatrixStack; + +public class CosmeticFeatureRenderer extends ArmorFeatureRenderer< + AbstractClientPlayerEntity, + PlayerEntityModel, + BipedEntityModel> { + private static final Map modelCache = new HashMap<>(); + private static CosmeticArmorRenderer cosmeticRenderer = null; + PlayerEntityRenderer renderer; + String skin; + + public CosmeticFeatureRenderer(PlayerEntityRenderer renderer, String skin) { + super(renderer, null, null); + this.renderer = renderer; + this.skin = skin; + } + + @Override + public void render( + MatrixStack matrix, + VertexConsumerProvider buffer, + int light, + AbstractClientPlayerEntity player, + float limbSwing, + float limbSwingAmount, + float partialTicks, + float ageInTicks, + float netHeadYaw, + float headPitch + ) { + for (ICosmetic c : CosmeticsManager.getCosmeticsForPlayer(player.getUuid())) { + if (c.readyToRender()) + this.renderCosmetic(matrix, buffer, player, light, c, partialTicks); + } + } + + private void renderCosmetic( + MatrixStack matrix, + VertexConsumerProvider buffer, + AbstractClientPlayerEntity player, + int light, + ICosmetic cosmetic, + float partialTicks + ) { + if (cosmeticRenderer == null) + cosmeticRenderer = new CosmeticArmorRenderer(); + if (!modelCache.containsKey(cosmetic)) + modelCache.put(cosmetic, new CosmeticItem(cosmetic)); + CosmeticItem item = modelCache.get(cosmetic); + copyRotations(this.renderer.getModel(), cosmeticRenderer); + cosmeticRenderer.applyEntityStats(this.renderer.getModel()); + cosmeticRenderer.setCurrentItem(player, item); + cosmeticRenderer.filterBones(); + + VertexConsumer vertex = ItemRenderer.getArmorGlintConsumer( + buffer, + RenderLayer.getArmorCutoutNoCull(cosmetic.getTextureLocation()), + false, + false + ); + cosmeticRenderer.render(partialTicks, matrix, vertex, light); + } + + private static void copyRotations(BipedEntityModel from, BipedEntityModel to) { + copyRotations(from.head, to.head); + copyRotations(from.hat, to.hat); + copyRotations(from.body, to.body); + copyRotations(from.leftArm, to.leftArm); + copyRotations(from.rightArm, to.rightArm); + copyRotations(from.rightLeg, to.rightLeg); + copyRotations(from.leftLeg, to.leftLeg); + } + + private static void copyRotations(ModelPart from, ModelPart to) { + to.copyTransform(from); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticItem.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticItem.java new file mode 100644 index 0000000..637d62f --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticItem.java @@ -0,0 +1,44 @@ +package net.anvilcraft.anvillib.cosmetics; + +import software.bernie.geckolib3.core.IAnimatable; +import software.bernie.geckolib3.core.PlayState; +import software.bernie.geckolib3.core.builder.AnimationBuilder; +import software.bernie.geckolib3.core.controller.AnimationController; +import software.bernie.geckolib3.core.event.predicate.AnimationEvent; +import software.bernie.geckolib3.core.manager.AnimationData; +import software.bernie.geckolib3.core.manager.AnimationFactory; +import software.bernie.geckolib3.util.GeckoLibUtil; + +public class CosmeticItem implements IAnimatable { + private ICosmetic cosmetic = null; + private AnimationBuilder animationBuilder = new AnimationBuilder(); + + public CosmeticItem(ICosmetic cosmetic) { + this.cosmetic = cosmetic; + this.cosmetic.addAnimations(animationBuilder); + } + + private

PlayState predicate(AnimationEvent

event) { + event.getController().transitionLengthTicks = 0; + event.getController().setAnimation(animationBuilder); + return PlayState.CONTINUE; + } + + @Override + public void registerControllers(AnimationData data) { + data.addAnimationController( + new AnimationController<>(this, "controller", 20, this::predicate) + ); + } + + private final AnimationFactory factory = GeckoLibUtil.createFactory(this); + + @Override + public AnimationFactory getFactory() { + return this.factory; + } + + public ICosmetic getCosmetic() { + return this.cosmetic; + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticModel.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticModel.java new file mode 100644 index 0000000..6c9ce50 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticModel.java @@ -0,0 +1,21 @@ +package net.anvilcraft.anvillib.cosmetics; + +import net.minecraft.util.Identifier; +import software.bernie.geckolib3.model.AnimatedGeoModel; + +public class CosmeticModel extends AnimatedGeoModel { + @Override + public Identifier getAnimationFileLocation(CosmeticItem animatable) { + return animatable.getCosmetic().getAnimationFileLocation(); + } + + @Override + public Identifier getModelLocation(CosmeticItem animatable) { + return animatable.getCosmetic().getModelLocation(); + } + + @Override + public Identifier getTextureLocation(CosmeticItem animatable) { + return animatable.getCosmetic().getTextureLocation(); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticsManager.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticsManager.java new file mode 100644 index 0000000..fce3e75 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/CosmeticsManager.java @@ -0,0 +1,51 @@ +package net.anvilcraft.anvillib.cosmetics; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +public class CosmeticsManager { + private static List providers = new ArrayList<>(); + private static Map> cosmeticCache = new HashMap<>(); + private static Set activePlayers = new HashSet<>(); + + private static void refresh() { + boolean doRefresh = false; + for (ICosmeticProvider provider : providers) { + doRefresh = doRefresh || provider.requestsRefresh(); + } + if (!doRefresh) + return; + cosmeticCache.clear(); + for (UUID uuid : activePlayers) { + loadPlayer(uuid); + } + } + + private static void loadPlayer(UUID player) { + if (cosmeticCache.containsKey(player)) + return; + cosmeticCache.put(player, new ArrayList<>()); + List cosmetics = cosmeticCache.get(player); + for (ICosmeticProvider provider : providers) { + provider.addCosmetics(player, (cosmetic) -> cosmetics.add(cosmetic)); + } + } + + public static void registerProvider(ICosmeticProvider provider) { + providers.add(provider); + } + + protected static List getCosmeticsForPlayer(UUID uuid) { + if (!activePlayers.contains(uuid)) { + activePlayers.add(uuid); + loadPlayer(uuid); + } + refresh(); + return cosmeticCache.get(uuid); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/ICosmetic.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/ICosmetic.java new file mode 100644 index 0000000..b0db9b9 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/ICosmetic.java @@ -0,0 +1,44 @@ +package net.anvilcraft.anvillib.cosmetics; + +import net.minecraft.util.Identifier; +import software.bernie.geckolib3.core.builder.AnimationBuilder; + +public interface ICosmetic { + Identifier getAnimationFileLocation(); + + Identifier getModelLocation(); + + Identifier getTextureLocation(); + + default String getHead() { + return null; //head + } + + default String getBody() { + return null; //body + } + + default String getLeftArm() { + return null; //arm_left + } + + default String getRightArm() { + return null; //arm_right + } + + default String getLeftLeg() { + return null; //leg_left + } + + default String getRightLeg() { + return null; //leg_right + } + + void addAnimations(AnimationBuilder builder); + + default boolean readyToRender() { + return true; + } + + Identifier getID(); +} diff --git a/src/main/java/net/anvilcraft/anvillib/cosmetics/ICosmeticProvider.java b/src/main/java/net/anvilcraft/anvillib/cosmetics/ICosmeticProvider.java new file mode 100644 index 0000000..00c4a26 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/cosmetics/ICosmeticProvider.java @@ -0,0 +1,10 @@ +package net.anvilcraft.anvillib.cosmetics; + +import java.util.UUID; +import java.util.function.Consumer; + +public interface ICosmeticProvider { + boolean requestsRefresh(); + + void addCosmetics(UUID player, Consumer cosmeticAdder); +} diff --git a/src/main/java/net/anvilcraft/anvillib/mixin/common/RecipeManagerMixin.java b/src/main/java/net/anvilcraft/anvillib/mixin/common/RecipeManagerMixin.java new file mode 100644 index 0000000..c4250a9 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/mixin/common/RecipeManagerMixin.java @@ -0,0 +1,48 @@ +package net.anvilcraft.anvillib.mixin.common; + +import java.util.HashMap; +import java.util.Map; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.google.gson.JsonElement; + +import net.anvilcraft.anvillib.AnvilLib; +import net.anvilcraft.anvillib.recipe.RecipesEvent; +import net.minecraft.recipe.Recipe; +import net.minecraft.recipe.RecipeManager; +import net.minecraft.recipe.RecipeType; +import net.minecraft.resource.ResourceManager; +import net.minecraft.util.Identifier; +import net.minecraft.util.profiler.Profiler; +import net.minecraftforge.fml.ModLoader; + +@Mixin(RecipeManager.class) +public class RecipeManagerMixin { + @Shadow + private Map, Map>> recipes; + + @Shadow + private Map> recipesById; + + @Inject(method = "apply", at = @At("RETURN")) + private void afterLoad( + Map alec1, + ResourceManager alec2, + Profiler alec3, + CallbackInfo ci + ) { + AnvilLib.LOGGER.info("Firing Recipe Event"); + Map, Map>> recipes = new HashMap<>(); + this.recipes.forEach((k, v) -> recipes.put(k, new HashMap<>(v))); + + var ev = new RecipesEvent(recipes, new HashMap<>(this.recipesById)); + ModLoader.get().postEvent(ev); + this.recipes = ev.recipes; + this.recipesById = ev.recipesById; + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/AbstractIngredientCondition.java b/src/main/java/net/anvilcraft/anvillib/recipe/AbstractIngredientCondition.java new file mode 100644 index 0000000..c17d74e --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/AbstractIngredientCondition.java @@ -0,0 +1,23 @@ +package net.anvilcraft.anvillib.recipe; + +import java.util.Arrays; +import java.util.function.Predicate; + +import net.anvilcraft.anvillib.Util; +import net.minecraft.recipe.Ingredient; +import net.minecraft.util.Identifier; + +public abstract class AbstractIngredientCondition implements Predicate { + public static AbstractIngredientCondition of(String s) { + return s.charAt(0) == '#' + ? new TagIngredientCondition(new Identifier(s.substring(1))) + : new StackIngredientCondition(Util.stackFromRegistry(new Identifier(s))); + } + + @Override + public boolean test(Ingredient i) { + return Arrays.stream(i.entries).anyMatch(this::entryMatches); + } + + public abstract boolean entryMatches(Ingredient.Entry e); +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/IRecipeMapper.java b/src/main/java/net/anvilcraft/anvillib/recipe/IRecipeMapper.java new file mode 100644 index 0000000..c814161 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/IRecipeMapper.java @@ -0,0 +1,12 @@ +package net.anvilcraft.anvillib.recipe; + +import java.util.function.Function; + +import net.minecraft.recipe.Recipe; + +/** + * IRecipeMapper describes a class that knows how to conditionally replace recipes. + */ +public interface IRecipeMapper extends Function, Recipe> { + public boolean shouldMap(Recipe recipe); +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/IngredientsContainPredicate.java b/src/main/java/net/anvilcraft/anvillib/recipe/IngredientsContainPredicate.java new file mode 100644 index 0000000..97ba77c --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/IngredientsContainPredicate.java @@ -0,0 +1,19 @@ +package net.anvilcraft.anvillib.recipe; + +import java.util.function.Predicate; + +import net.minecraft.recipe.Ingredient; +import net.minecraft.recipe.Recipe; + +public class IngredientsContainPredicate implements Predicate> { + public Predicate pred; + + public IngredientsContainPredicate(Predicate pred) { + this.pred = pred; + } + + @Override + public boolean test(Recipe r) { + return r.getIngredients().stream().anyMatch(this.pred); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/InputReplaceRecipeMapper.java b/src/main/java/net/anvilcraft/anvillib/recipe/InputReplaceRecipeMapper.java new file mode 100644 index 0000000..561cf81 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/InputReplaceRecipeMapper.java @@ -0,0 +1,54 @@ +package net.anvilcraft.anvillib.recipe; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Predicate; + +import net.anvilcraft.anvillib.Util; +import net.minecraft.recipe.Ingredient; +import net.minecraft.recipe.Recipe; + +public class InputReplaceRecipeMapper implements IRecipeMapper { + public Map, Ingredient> replacements = new HashMap<>(); + + public InputReplaceRecipeMapper replace(Predicate p, Ingredient i) { + this.replacements.put(p, i); + return this; + } + + public InputReplaceRecipeMapper replace(String p, Ingredient i) { + return this.replace(AbstractIngredientCondition.of(p), i); + } + + public InputReplaceRecipeMapper replace(String p, String i) { + return this.replace(p, Util.ingredientFromString(i)); + } + + public InputReplaceRecipeMapper replace(Predicate p, String i) { + return this.replace(p, Util.ingredientFromString(i)); + } + + @Override + public boolean shouldMap(Recipe recipe) { + var ingredients = recipe.getIngredients(); + if (ingredients == null) + return false; + + for (var k : this.replacements.keySet()) + if (ingredients.stream().anyMatch(k)) + return true; + return false; + } + + @Override + public Recipe apply(Recipe recipe) { + var ingredients = recipe.getIngredients(); + for (int i = 0; i < ingredients.size(); i++) { + var ing = ingredients.get(i); + for (var entry : this.replacements.entrySet()) + if (entry.getKey().test(ing)) + ingredients.set(i, entry.getValue()); + } + return recipe; + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/RecipeContainsPredicate.java b/src/main/java/net/anvilcraft/anvillib/recipe/RecipeContainsPredicate.java new file mode 100644 index 0000000..0e2a19a --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/RecipeContainsPredicate.java @@ -0,0 +1,22 @@ +package net.anvilcraft.anvillib.recipe; + +import java.util.function.Predicate; + +import net.minecraft.item.ItemStack; +import net.minecraft.recipe.Recipe; + +public class RecipeContainsPredicate implements Predicate> { + public ItemStack item; + + public RecipeContainsPredicate(ItemStack item) { + this.item = item; + } + + @Override + public boolean test(Recipe r) { + return r.getIngredients() == null + ? false + : r.getIngredients().stream().anyMatch(new StackIngredientCondition(this.item) + ) || r.getOutput().isItemEqual(this.item); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/RecipesEvent.java b/src/main/java/net/anvilcraft/anvillib/recipe/RecipesEvent.java new file mode 100644 index 0000000..b6fc610 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/RecipesEvent.java @@ -0,0 +1,81 @@ +package net.anvilcraft.anvillib.recipe; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Predicate; + +import net.minecraft.recipe.Recipe; +import net.minecraft.recipe.RecipeType; +import net.minecraft.util.Identifier; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; + +public class RecipesEvent extends Event implements IModBusEvent { + public Map, Map>> recipes; + public Map> recipesById; + + public RecipesEvent( + Map, Map>> recipes, + Map> recipesById + ) { + this.recipes = recipes; + this.recipesById = recipesById; + } + + public void registerRecipe(Recipe recipe) { + if (!this.recipes.containsKey(recipe.getType())) + this.recipes.put(recipe.getType(), new HashMap<>()); + + this.recipes.get(recipe.getType()).put(recipe.getId(), recipe); + this.recipesById.put(recipe.getId(), recipe); + } + + public Optional> removeRecipeID(Identifier id) { + if (this.recipesById.containsKey(id)) { + return Optional.of( + this.recipes.get(this.recipesById.remove(id).getType()).remove(id) + ); + } + + return Optional.empty(); + } + + public void removeRecipesMatching(Predicate> p) { + var iter = this.recipesById.entrySet().iterator(); + while (iter.hasNext()) { + var entry = iter.next(); + if (p.test(entry.getValue())) { + iter.remove(); + this.recipes.get(entry.getValue().getType()).remove(entry.getKey()); + } + } + } + + public void mapRecipes(IRecipeMapper mapper) { + var iter = this.recipesById.entrySet().iterator(); + while (iter.hasNext()) { + var entry = iter.next(); + if (mapper.shouldMap(entry.getValue())) { + var mapped = mapper.apply(entry.getValue()); + if (mapped != entry.getValue()) { + iter.remove(); + this.recipes.get(entry.getValue().getType()).remove(entry.getKey()); + this.registerRecipe(mapped); + } + } + } + } + + public void mapRecipeID(Identifier id, Function, Recipe> func) { + var recipe = this.recipesById.get(id); + if (recipe != null) { + var mapped = func.apply(recipe); + if (recipe != mapped) { + this.removeRecipeID(id); + this.registerRecipe(mapped); + } + } + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/ShapedRecipeBuilder.java b/src/main/java/net/anvilcraft/anvillib/recipe/ShapedRecipeBuilder.java new file mode 100644 index 0000000..1e2ffe8 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/ShapedRecipeBuilder.java @@ -0,0 +1,95 @@ +package net.anvilcraft.anvillib.recipe; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.recipe.Ingredient; +import net.minecraft.recipe.ShapedRecipe; +import net.minecraft.tag.TagKey; +import net.minecraft.util.Identifier; +import net.minecraft.util.collection.DefaultedList; +import net.minecraft.util.registry.Registry; +import net.minecraftforge.registries.ForgeRegistries; + +public class ShapedRecipeBuilder { + public Identifier ident; + public String[] pattern; + public Map ingredients = new HashMap<>(); + public ItemStack output; + + public ShapedRecipeBuilder(Identifier ident, ItemStack output) { + this.ident = ident; + this.output = output; + } + + public ShapedRecipeBuilder pattern(String... pat) { + this.pattern = pat; + return this; + } + + public ShapedRecipeBuilder ingredient(char c, Ingredient i) { + this.ingredients.put(c, i); + return this; + } + + public ShapedRecipeBuilder ingredient(char c, ItemStack... is) { + return this.ingredient(c, Ingredient.ofStacks(is)); + } + + public ShapedRecipeBuilder ingredient(char c, Item i) { + return this.ingredient(c, new ItemStack(i)); + } + + public ShapedRecipeBuilder ingredient(char c, Block b) { + return this.ingredient(c, new ItemStack(b)); + } + + public ShapedRecipeBuilder ingredient(char c, String s) { + if (s.charAt(0) == '#') { + return this.tagIngredient(c, new Identifier(s.substring(1))); + } + + var ident = new Identifier(s); + var maybeItem = ForgeRegistries.ITEMS.getValue(ident); + if (maybeItem == null) { + var maybeBlock = ForgeRegistries.BLOCKS.getValue(ident); + if (maybeBlock == null) + throw new IllegalArgumentException( + "ID " + s + " not found in item or block registry!" + ); + + return this.ingredient(c, maybeBlock); + } + + return this.ingredient(c, maybeItem); + } + + public ShapedRecipeBuilder tagIngredient(char c, Identifier t) { + return this.ingredient(c, Ingredient.fromTag(TagKey.of(Registry.ITEM_KEY, t))); + } + + public ShapedRecipe build() { + int width = -1; + for (String line : this.pattern) { + if (width != -1 && width != line.length()) + throw new IllegalArgumentException( + "Lines in crafting pattern must be same width!" + ); + width = line.length(); + } + + DefaultedList ingredients = DefaultedList.of(); + Arrays.stream(this.pattern) + .flatMap(s -> s.chars().mapToObj(c -> (char) c)) + .map(this.ingredients::get) + .forEach(ingredients::add); + + return new ShapedRecipe( + this.ident, "", width, this.pattern.length, ingredients, this.output + ); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/StackIngredientCondition.java b/src/main/java/net/anvilcraft/anvillib/recipe/StackIngredientCondition.java new file mode 100644 index 0000000..856b6de --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/StackIngredientCondition.java @@ -0,0 +1,18 @@ +package net.anvilcraft.anvillib.recipe; + +import net.minecraft.item.ItemStack; +import net.minecraft.recipe.Ingredient.Entry; +import net.minecraft.recipe.Ingredient.StackEntry; + +public class StackIngredientCondition extends AbstractIngredientCondition { + public ItemStack stack; + + public StackIngredientCondition(ItemStack stack) { + this.stack = stack; + } + + @Override + public boolean entryMatches(Entry e) { + return e instanceof StackEntry se && se.stack.isItemEqual(this.stack); + } +} diff --git a/src/main/java/net/anvilcraft/anvillib/recipe/TagIngredientCondition.java b/src/main/java/net/anvilcraft/anvillib/recipe/TagIngredientCondition.java new file mode 100644 index 0000000..8b765f7 --- /dev/null +++ b/src/main/java/net/anvilcraft/anvillib/recipe/TagIngredientCondition.java @@ -0,0 +1,18 @@ +package net.anvilcraft.anvillib.recipe; + +import net.minecraft.recipe.Ingredient.Entry; +import net.minecraft.recipe.Ingredient.TagEntry; +import net.minecraft.util.Identifier; + +public class TagIngredientCondition extends AbstractIngredientCondition { + public Identifier id; + + public TagIngredientCondition(Identifier id) { + this.id = id; + } + + @Override + public boolean entryMatches(Entry e) { + return e instanceof TagEntry te && te.tag.id().equals(this.id); + } +} diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg new file mode 100644 index 0000000..946dc01 --- /dev/null +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -0,0 +1,3 @@ +public net.minecraft.world.item.crafting.Ingredient f_43902_ # Ingredient.entries +public net.minecraft.world.item.crafting.Ingredient$TagValue f_43959_ # Ingredient$TagEntry.tag +public net.minecraft.world.item.crafting.Ingredient$ItemValue f_43951_ # Ingredient$StackEntry.stack diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..de1a349 --- /dev/null +++ b/src/main/resources/META-INF/mods.toml @@ -0,0 +1,41 @@ +modLoader = "javafml" +loaderVersion = "[40,)" +license = "AGPL-3.0+ALEC" + +issueTrackerURL = "https://git.tilera.org/Anvilcraft/anvillib/issues" + +[[mods]] +modId = "anvillib" +version = "${version}" +displayName = "anvillib" +displayURL = "https://anvilcraft.net/" +#credits = "" +authors = "LordMZTE, (tilera)" + +description = ''' +Core for Notex 4. + +Includes recipes and tweaks. +''' + +[[dependencies.anvillib]] +modId = "forge" +mandatory = true + +versionRange = "[40,)" +ordering = "NONE" +side = "BOTH" + +[[dependencies.anvillib]] +modId = "minecraft" +mandatory = true +versionRange = "[1.18.2]" +ordering = "NONE" +side = "BOTH" + +[[dependencies.anvillib]] +modId = "geckolib3" +mandatory = true +versionRange = "[3.0.57,)" +ordering = "NONE" +side = "BOTH" diff --git a/src/main/resources/anvillib.mixins.json b/src/main/resources/anvillib.mixins.json new file mode 100644 index 0000000..f223f7c --- /dev/null +++ b/src/main/resources/anvillib.mixins.json @@ -0,0 +1,13 @@ +{ + "required": true, + "package": "net.anvilcraft.anvillib.mixin", + "compatibilityLevel": "JAVA_17", + "minVersion": "0.8", + "mixins": [ + "common.RecipeManagerMixin" + ], + "client": [], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..3dff4a1 --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1,7 @@ +{ + "pack": { + "description": "Resources for anvillib", + "pack_format": 8, + "_comment": "pack_format 8 is the current format for Minecraft 1.18.2. Be aware may have changed by the time you use this template!" + } +}