From a621a04ba075e2179203526ba8467451802185c6 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 16 Oct 2023 23:49:55 +1030 Subject: [PATCH 01/87] Port to 1.20.1 Mostly complete. --- build.gradle | 24 +- build.properties | 6 +- gradle/wrapper/gradle-wrapper.jar | Bin 59821 -> 62076 bytes gradle/wrapper/gradle-wrapper.properties | 3 +- gradlew | 25 +- gradlew.bat | 15 +- settings.gradle | 26 +- .../15d5dd4ace2ad25407a17728f6fbc07b246efd63 | 2 +- .../95d738e2c774c5a4b0452cf55df2775d732b2634 | 2 +- .../f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 | 2 +- .../java/codechicken/lib/CodeChickenLib.java | 34 +-- .../block/component/data/TagComponent.java | 2 +- .../codechicken/lib/data/MCDataInput.java | 2 +- .../codechicken/lib/data/MCDataOutput.java | 2 +- .../lib/datagen/ConditionalIngredient.java | 4 +- .../lib/datagen/ItemModelProvider.java | 74 +++++- .../lib/datagen/LanguageProvider.java | 22 +- .../lib/datagen/LootTableProvider.java | 46 ++-- .../AbstractItemStackRecipeBuilder.java | 2 +- .../datagen/recipe/AbstractRecipeBuilder.java | 3 +- .../lib/datagen/recipe/RecipeProvider.java | 52 ++-- ...java => SpecialCraftingRecipeBuilder.java} | 14 +- .../lib/gui/SimpleCreativeTab.java | 28 --- .../ProxyClient.java => ClientInit.java} | 44 ++-- .../lib/internal/DataGenerators.java | 32 ++- .../lib/internal/HighlightHandler.java | 6 +- .../lib/internal/ItemFileRenderer.java | 13 +- .../lib/internal/command/CCLCommands.java | 10 +- .../internal/command/EntityTypeArgument.java | 32 --- .../internal/command/admin/CountCommand.java | 18 +- .../command/admin/KillAllCommand.java | 29 +-- .../internal/command/admin/MiscCommands.java | 15 +- .../command/client/HighlightCommand.java | 12 +- .../command/client/ItemInfoCommand.java | 10 +- .../client/RenderItemToFileCommand.java | 4 +- .../lib/internal/command/dev/DevCommands.java | 3 +- .../lib/internal/mixin/ItemRendererMixin.java | 10 +- .../internal/mixin/LevelRendererMixin.java | 24 +- .../codechicken/lib/internal/proxy/Proxy.java | 21 -- .../lib/inventory/InventoryUtils.java | 2 +- .../container/ICCLContainerType.java | 13 +- .../lib/item/SimpleArmorMaterial.java | 13 +- .../lib/model/CompositeItemModel.java | 126 ++++++++++ .../codechicken/lib/model/ItemQuadBakery.java | 2 +- .../lib/model/ModelRegistryHelper.java | 47 +--- .../lib/model/PerspectiveModel.java | 10 +- .../lib/model/PerspectiveModelState.java | 12 +- .../AbstractBakedPropertiesModel.java | 7 +- .../model/bakedmodels/ModelProperties.java | 1 + .../PerspectiveAwareBakedModel.java | 1 + .../PerspectiveAwareLayeredModel.java | 1 + .../model/bakedmodels/WrappedItemModel.java | 7 +- .../lib/model/bakery/CCBakeryModel.java | 99 -------- .../lib/model/bakery/IBakeryProvider.java | 24 -- .../lib/model/bakery/ModelBakery.java | 229 ------------------ .../lib/model/bakery/generation/IBakery.java | 9 - .../model/bakery/generation/IBlockBakery.java | 45 ---- .../model/bakery/generation/IItemBakery.java | 42 ---- .../model/bakery/generation/package-info.java | 9 - .../bakery/key/IBlockStateKeyGenerator.java | 24 -- .../bakery/key/IItemStackKeyGenerator.java | 25 -- .../codechicken/lib/raytracer/RayTracer.java | 12 +- .../lib/render/CCModelLibrary.java | 2 +- .../block/CCBlockRendererDispatcher.java | 14 +- .../lib/render/buffer/DelegateRenderType.java | 5 +- .../lib/render/buffer/VBORenderType.java | 7 +- .../lib/render/item/IItemRenderer.java | 6 +- .../lib/render/shader/CCUniform.java | 8 +- .../lib/render/shader/ICCUniform.java | 84 +++---- .../lib/texture/SpriteRegistryHelper.java | 228 ++++++++--------- .../java/codechicken/lib/util/FontUtils.java | 18 -- .../java/codechicken/lib/util/ItemUtils.java | 2 +- .../codechicken/lib/util/ServerUtils.java | 6 +- .../codechicken/lib/util/TransformUtils.java | 90 ++++--- .../java/codechicken/lib/vec/Matrix4.java | 77 +++--- src/main/java/codechicken/lib/vec/Quat.java | 28 ++- .../java/codechicken/lib/vec/Vector3.java | 6 +- .../resources/META-INF/accesstransformer.cfg | 2 +- src/main/resources/META-INF/mods.toml | 2 +- .../lib/test/TestResourceProvider.java | 2 +- 80 files changed, 788 insertions(+), 1232 deletions(-) rename src/main/java/codechicken/lib/datagen/recipe/{SpecialRecipeBuilder.java => SpecialCraftingRecipeBuilder.java} (64%) delete mode 100644 src/main/java/codechicken/lib/gui/SimpleCreativeTab.java rename src/main/java/codechicken/lib/internal/{proxy/ProxyClient.java => ClientInit.java} (62%) delete mode 100644 src/main/java/codechicken/lib/internal/command/EntityTypeArgument.java delete mode 100644 src/main/java/codechicken/lib/internal/proxy/Proxy.java create mode 100644 src/main/java/codechicken/lib/model/CompositeItemModel.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/CCBakeryModel.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/IBakeryProvider.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/ModelBakery.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/generation/IBakery.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/generation/IBlockBakery.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/generation/IItemBakery.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/generation/package-info.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/key/IBlockStateKeyGenerator.java delete mode 100644 src/main/java/codechicken/lib/model/bakery/key/IItemStackKeyGenerator.java delete mode 100644 src/main/java/codechicken/lib/util/FontUtils.java diff --git a/build.gradle b/build.gradle index 9eb6ecd7..0a359bd8 100644 --- a/build.gradle +++ b/build.gradle @@ -1,26 +1,12 @@ -buildscript { - repositories { - mavenLocal() - jcenter() - maven { url = "https://maven.minecraftforge.net/" } - maven { url = "https://repo.spongepowered.org/maven" } - } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:5.1.+' - classpath 'org.spongepowered:mixingradle:0.7-SNAPSHOT' - } -} - plugins { id 'java' id 'maven-publish' id 'com.github.johnrengelman.shadow' version '7.1.2' id "net.covers1624.signing" version '1.1.4' + id 'net.neoforged.gradle' version '[6.0.18,6.2)' + id 'org.spongepowered.mixin' version '0.7.+' } -apply plugin: 'net.minecraftforge.gradle' -apply plugin: "org.spongepowered.mixin" - java.toolchain.languageVersion = JavaLanguageVersion.of(17) group = 'codechicken' @@ -106,7 +92,7 @@ repositories { } dependencies { - minecraft "net.minecraftforge:forge:${config.mc_version}-${config.forge_version}" + minecraft "net.neoforged:forge:${config.mc_version}-${config.forge_version}" shadow 'net.covers1624:Quack:0.4.7.72' @@ -151,7 +137,7 @@ def commonManifest = { jar.enabled = false shadowJar { finalizedBy 'reobfShadowJar' - classifier = 'universal' + archiveClassifier = 'universal' manifest commonManifest configurations = [project.configurations.shadow] @@ -161,7 +147,7 @@ shadowJar { task srcJar(type: Jar) { build.dependsOn it from sourceSets.main.allSource - classifier = 'sources' + archiveClassifier = 'sources' from file("LICENSE") } diff --git a/build.properties b/build.properties index e1e50f68..539ff8ac 100644 --- a/build.properties +++ b/build.properties @@ -1,3 +1,3 @@ -mc_version=1.19.2 -forge_version=43.2.0 -mod_version=4.3.2 +mc_version=1.20.1 +forge_version=47.1.65 +mod_version=4.4.0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 41d9927a4d4fb3f96a785543079b8df6723c946b..c1962a79e29d3e0ab67b14947c167a862655af9b 100644 GIT binary patch delta 40199 zcmaI7V{~Rgw>28uwrv|7+qP{xPn?dOj%_exmnx8HNdckXw_xa0n*U1RT6 zWB-{|bJkpI)h>a59)UwD%Yj2+Bo$yL;h}?KBr&=C8w$w(GhildVE)%L1p<^10|NvE z1_lHKLb@w#T`0x{1l?Q&b+9S)L+*UZOMUk9YN~Nr zcLekuo$Y@Aees_|7WTOb0O5*xf-|f*aNRBu9f>)*H|^*aACS{fmv)9U1eE0K1v4x?Sn-Y{ZhyVgg{)Uop+>#9_4Rp$!fZd_f^4tWJ_^~ZI8g9zHvhot=+Xie%kIcW+=j2^gM3@Ac-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(dTL4+#1Fj-A!cQz%Q||NC&j&W3#PhGxB6Cl(J(kj;6;vDNkLN(<84n zTlb-S&Sa^cG$Q{!xUzP;#EPUggW+nYyX@E$&QhbxfkL=)R`7>fUA}`Ky0VsTtVo$4 zT=35i2Hd?I=3RwurwF}dw}I=q5rKbUe35Mrlq$X=r6NPuBR8a)6EX4SYuhIrgC7<6 zJeGj8+d$%qwv?9)$1nY(N}{dKJ)tC=fZ2F zpTpI#?iNpl%9{Q}S@y`CfEuuXoxX$xn>YKHH+c;CEekgj-9m2kgx#{u^mV8Y!u&`x z)9hO#^Cn%*{a^sk=Xg28*HNz){+ZXJm z$!+mE=^hGeAGm}XwK!sTJ2}2lsGl)cIICuuuGNUvWs0|A$`8qn?~wTl{5G8qYpFyKAG30$*g0B%`Q02h`|a{nsoF(XC(#YRp- z!U>WD!K{IUS27ks1|-zNKrv=8GW)M7p34YG5CxGuwn72K+Ec)OvJQLRIu++DZK2G9k|uiyaH z7fOg8=b^R>0OO(QBLEyQ2idAzM0Vg8Zcrxw3j%TvNhCmHn137j*#2h6MurRj6x!eJ zj0x04vx+130guU8aSLFQAa(?LtUtgp z=p{=K$_hN_qxsEO$7|t!NhM>09Kp&s0dTUUR7cHUaRgA4B1AHb7kVf_OR^$&#fgN( z(grPzwlOreFcCJgFcUtQ-}^}f#KZ~cnv?(~&rBg8co*;l4*WUA4-)J^LV^b{$;%2X z&@&zSO&JCUmZvBo;+{m7I}Ccr`it?XO;In1fHCl|qk{nntVaQ(ejotBB67^>hc_Lu zGH-I45z^$p4+B_dE*x>|eqm7}7z*JA`-zAi&UgO`SOgQ{AKB@Cb1SjB1AKNoKl5)k z(ScktRzHj=l*!5Ro6xb$?*j?&n2arq0EHBP6Zn;}OG1J=Ch#~KNSKvBGK>GFHyxmp zv0?E/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. diff --git a/gradlew.bat b/gradlew.bat index 107acd32..93e3f59f 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/settings.gradle b/settings.gradle index 398e21f6..3a4d862d 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,19 +1,11 @@ -/* - * This settings file was auto generated by the Gradle buildInit task - * by 'sunstrike' at '21/11/13 14:14' with Gradle 1.9 - * - * The settings file is used to specify which projects to include in your build. - * In a single project build this file can be empty or even removed. - * - * Detailed information about configuring a multi-project build in Gradle can be found - * in the user guide at http://gradle.org/docs/1.9/userguide/multi_project_builds.html - */ - -/* -// To declare projects as part of a multi-project build use the 'include' method -include 'shared' -include 'api' -include 'services:webservice' -*/ +pluginManagement { + repositories { + gradlePluginPortal() + maven { + name = 'NeoForged' + url = 'https://maven.neoforged.net/releases' + } + } +} rootProject.name = 'CodeChickenLib' diff --git a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 index 01575e6a..9a6224e4 100644 --- a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 +++ b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 @@ -1,3 +1,3 @@ -// 1.19 2022-06-22T22:36:02.635898629 codechickenlib Languages: en_us +// 1.20.1 2023-09-08T20:35:35.335872512 codechickenlib Languages: en_us ce1ce42a962941336b9de69689e94a97219ad7d9 assets/codechickenlib/lang/en_us.json ce1ce42a962941336b9de69689e94a97219ad7d9 data/codechickenlib/lang/en_us.json diff --git a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 index 38272923..663271f0 100644 --- a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 +++ b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 @@ -1,4 +1,4 @@ -// 1.19 2022-06-22T22:36:02.63605193 CodeChickenLib Block tags. +// 1.20.1 2023-09-08T20:30:19.590475077 CodeChickenLib Block tags. 48ffc90719924738f43a8ea0c526941cbbb83318 data/forge/tags/blocks/wool.json dc26d59698d238e0c60c400dbffea2ba82af4365 data/forge/tags/blocks/wool/black.json 4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/forge/tags/blocks/wool/blue.json diff --git a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 index 3940ce49..33d215f6 100644 --- a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 +++ b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 @@ -1,4 +1,4 @@ -// 1.19 2022-06-22T22:36:02.634627369 CodeChickenLib Item tags. +// 1.20.1 2023-09-08T20:30:19.593585402 CodeChickenLib Item tags. 48ffc90719924738f43a8ea0c526941cbbb83318 data/forge/tags/items/wool.json dc26d59698d238e0c60c400dbffea2ba82af4365 data/forge/tags/items/wool/black.json 4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/forge/tags/items/wool/blue.json diff --git a/src/main/java/codechicken/lib/CodeChickenLib.java b/src/main/java/codechicken/lib/CodeChickenLib.java index 84797e52..37ae617f 100644 --- a/src/main/java/codechicken/lib/CodeChickenLib.java +++ b/src/main/java/codechicken/lib/CodeChickenLib.java @@ -2,19 +2,13 @@ import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigFile; +import codechicken.lib.datagen.ConditionalIngredient; +import codechicken.lib.internal.ClientInit; import codechicken.lib.internal.command.CCLCommands; import codechicken.lib.internal.network.CCLNetwork; -import codechicken.lib.internal.proxy.Proxy; -import codechicken.lib.internal.proxy.ProxyClient; -import codechicken.lib.datagen.ConditionalIngredient; import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import java.nio.file.Paths; @@ -28,31 +22,15 @@ public class CodeChickenLib { public static ConfigCategory config; - public static Proxy proxy; - public CodeChickenLib() { config = new ConfigFile(MOD_ID) .path(Paths.get("config/ccl.cfg")) .load(); - proxy = DistExecutor.safeRunForDist(() -> ProxyClient::new, () -> Proxy::new); - FMLJavaModLoadingContext.get().getModEventBus().register(this); - CCLCommands.init(); - ConditionalIngredient.Serializer.init(); - } - @SubscribeEvent - public void onCommonSetup(FMLCommonSetupEvent event) { - proxy.commonSetup(event); - CCLNetwork.init(); - } - - @SubscribeEvent - public void onClientSetup(FMLClientSetupEvent event) { - proxy.clientSetup(event); - } + DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> ClientInit::init); - @SubscribeEvent - public void onServerSetup(FMLDedicatedServerSetupEvent event) { - proxy.serverSetup(event); + CCLCommands.init(); + CCLNetwork.init(); + ConditionalIngredient.Serializer.init(); } } diff --git a/src/main/java/codechicken/lib/block/component/data/TagComponent.java b/src/main/java/codechicken/lib/block/component/data/TagComponent.java index 53509d3d..dc98c281 100644 --- a/src/main/java/codechicken/lib/block/component/data/TagComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/TagComponent.java @@ -1,9 +1,9 @@ package codechicken.lib.block.component.data; import net.minecraft.data.DataProvider; -import net.minecraft.data.tags.BlockTagsProvider; import net.minecraft.tags.TagKey; import net.minecraft.world.level.block.Block; +import net.minecraftforge.common.data.BlockTagsProvider; import org.jetbrains.annotations.ApiStatus; /** diff --git a/src/main/java/codechicken/lib/data/MCDataInput.java b/src/main/java/codechicken/lib/data/MCDataInput.java index 35352c64..299dac94 100644 --- a/src/main/java/codechicken/lib/data/MCDataInput.java +++ b/src/main/java/codechicken/lib/data/MCDataInput.java @@ -2,7 +2,6 @@ import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; -import com.mojang.math.Vector3f; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.EncoderException; @@ -25,6 +24,7 @@ import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.RegistryManager; +import org.joml.Vector3f; import javax.annotation.Nullable; import java.io.DataInput; diff --git a/src/main/java/codechicken/lib/data/MCDataOutput.java b/src/main/java/codechicken/lib/data/MCDataOutput.java index d9f14cc7..d380f706 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutput.java +++ b/src/main/java/codechicken/lib/data/MCDataOutput.java @@ -2,7 +2,6 @@ import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; -import com.mojang.math.Vector3f; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.EncoderException; import net.minecraft.core.BlockPos; @@ -19,6 +18,7 @@ import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.IForgeRegistry; +import org.joml.Vector3f; import java.io.DataOutput; import java.io.DataOutputStream; diff --git a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java b/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java index bc39fc94..b83d7588 100644 --- a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java +++ b/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java @@ -121,11 +121,11 @@ private static void onAddReloadListenerEvent(AddReloadListenerEvent event) { public Ingredient parse(JsonObject json) { if (!CraftingHelper.processConditions(json, "conditions", conditionContext)) { if (json.has("fail")) { - return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "fail")); + return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "fail"), true); } return Ingredient.EMPTY; } - return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "pass")); + return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "pass"), false); } // We don't operate like this, we always return a different ingredient. diff --git a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java index 60355fa9..a91a4d8a 100644 --- a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java +++ b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java @@ -1,7 +1,8 @@ package codechicken.lib.datagen; +import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import net.minecraft.data.DataGenerator; +import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; @@ -16,14 +17,13 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; +import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; +import static codechicken.lib.CodeChickenLib.MOD_ID; + /** * Created by covers1624 on 15/10/20. */ @@ -34,8 +34,8 @@ public abstract class ItemModelProvider extends ModelProvider protected static final ModelFile.UncheckedModelFile GENERATED = new ModelFile.UncheckedModelFile("item/generated"); protected static final ModelFile.UncheckedModelFile HANDHELD = new ModelFile.UncheckedModelFile("item/handheld"); - public ItemModelProvider(DataGenerator generator, String modid, ExistingFileHelper existingFileHelper) { - super(generator, modid, ITEM_FOLDER, WrappedItemModelBuilder::new, existingFileHelper); + public ItemModelProvider(PackOutput output, String modid, ExistingFileHelper existingFileHelper) { + super(output, modid, ITEM_FOLDER, WrappedItemModelBuilder::new, existingFileHelper); } //region Location helpers @@ -140,6 +140,12 @@ protected void simpleItemBlock(Block block) { } //endregion + private SimpleItemModelBuilder makeNested(ItemLike item) { + WrappedItemModelBuilder builder = (WrappedItemModelBuilder) nested(); + builder.simpleBuilder = new SimpleItemModelBuilder(this, builder, item.asItem()); + return builder.simpleBuilder; + } + private ExistingFileHelper getExistingFileHelper() { return existingFileHelper; } @@ -321,4 +327,58 @@ protected JsonObject toJson(JsonObject json) { return json; } } + + public static class CompositeLoaderBuilder extends CustomLoaderBuilder { + + private final Map children = new LinkedHashMap<>(); + private final List order = new ArrayList<>(); + + protected CompositeLoaderBuilder(ResourceLocation loader, SimpleItemModelBuilder parent) { + super(loader, parent); + } + + public static CompositeLoaderBuilder forge(SimpleItemModelBuilder parent) { + return new CompositeLoaderBuilder(new ResourceLocation("forge", "composite"), parent); + } + + public static CompositeLoaderBuilder ccl(SimpleItemModelBuilder parent) { + return new CompositeLoaderBuilder(new ResourceLocation(MOD_ID, "item_composite"), parent); + } + + public CompositeLoaderBuilder nested(String name, Consumer cons) { + if (children.containsKey(name)) throw new IllegalArgumentException("Child with name " + name + " is already registered."); + + SimpleItemModelBuilder nested = parent.provider.makeNested(parent.item); + cons.accept(nested); + children.put(name, nested); + order.add(name); + return this; + } + + public CompositeLoaderBuilder order(String... names) { + for (String name : names) { + if (!children.containsKey(name)) { + throw new IllegalArgumentException("Child with name " + name + " does not exist."); + } + } + order.clear(); + Collections.addAll(order, names); + return this; + } + + @Override + protected JsonObject toJson(JsonObject json) { + super.toJson(json); + + JsonObject children = new JsonObject(); + this.children.forEach((name, child) -> children.add(name, child.builder.toJson())); + json.add("children", children); + + JsonArray order = new JsonArray(); + this.order.forEach(order::add); + json.add("item_render_order", order); + + return json; + } + } } diff --git a/src/main/java/codechicken/lib/datagen/LanguageProvider.java b/src/main/java/codechicken/lib/datagen/LanguageProvider.java index 82663f96..b7862be5 100644 --- a/src/main/java/codechicken/lib/datagen/LanguageProvider.java +++ b/src/main/java/codechicken/lib/datagen/LanguageProvider.java @@ -3,8 +3,8 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; +import net.minecraft.data.PackOutput; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Item; @@ -13,10 +13,12 @@ import net.minecraft.world.level.block.Block; import net.minecraftforge.data.event.GatherDataEvent; -import java.io.IOException; import java.nio.file.Path; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; /** @@ -27,13 +29,13 @@ public abstract class LanguageProvider implements DataProvider { private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create(); private final Map client = new TreeMap<>(); private final Map server = new TreeMap<>(); - private final DataGenerator gen; + private final PackOutput output; private final String modid; private final String locale; private final Side distFilter; - protected LanguageProvider(DataGenerator gen, String modid, String locale, Side distFilter) { - this.gen = gen; + protected LanguageProvider(PackOutput output, String modid, String locale, Side distFilter) { + this.output = output; this.modid = modid; this.locale = locale; this.distFilter = distFilter; @@ -42,14 +44,16 @@ protected LanguageProvider(DataGenerator gen, String modid, String locale, Side protected abstract void addTranslations(); @Override - public void run(CachedOutput p_200398_1_) throws IOException { + public CompletableFuture run(CachedOutput p_200398_1_) { addTranslations(); + List> futures = new LinkedList<>(); if (distFilter.includeClient() && !client.isEmpty()) { - save(p_200398_1_, client, gen.getOutputFolder().resolve("assets/" + modid + "/lang/" + locale + ".json")); + futures.add(DataProvider.saveStable(p_200398_1_, GSON.toJsonTree(client), output.getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(modid + "/lang/" + locale + ".json"))); } if (distFilter.includeServer() && !server.isEmpty()) { - save(p_200398_1_, server, gen.getOutputFolder().resolve("data/" + modid + "/lang/" + locale + ".json")); + futures.add(DataProvider.saveStable(p_200398_1_, GSON.toJsonTree(server), output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve(modid + "/lang/" + locale + ".json"))); } + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } @Override @@ -61,7 +65,7 @@ public String getLocale() { return locale; } - private void save(CachedOutput cache, Object object, Path target) throws IOException { + private void save(CachedOutput cache, Object object, Path target) { DataProvider.saveStable(cache, GSON.toJsonTree(object), target); } diff --git a/src/main/java/codechicken/lib/datagen/LootTableProvider.java b/src/main/java/codechicken/lib/datagen/LootTableProvider.java index 7f58840c..c1330534 100644 --- a/src/main/java/codechicken/lib/datagen/LootTableProvider.java +++ b/src/main/java/codechicken/lib/datagen/LootTableProvider.java @@ -7,17 +7,13 @@ import net.minecraft.advancements.critereon.ItemPredicate; import net.minecraft.advancements.critereon.MinMaxBounds; import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; -import net.minecraft.data.HashCache; +import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.storage.loot.LootPool; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.LootTables; -import net.minecraft.world.level.storage.loot.ValidationContext; +import net.minecraft.world.level.storage.loot.*; import net.minecraft.world.level.storage.loot.entries.LootItem; import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; import net.minecraft.world.level.storage.loot.functions.ApplyBonusCount; @@ -31,10 +27,12 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; /** * Created by covers1624 on 7/10/20. @@ -44,26 +42,28 @@ public abstract class LootTableProvider implements DataProvider { private static final Logger logger = LogManager.getLogger(); private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - private final DataGenerator dataGenerator; + private final PackOutput.PathProvider output; private final Map tables = new HashMap<>(); - protected LootTableProvider(DataGenerator dataGenerator) { - this.dataGenerator = dataGenerator; + protected LootTableProvider(PackOutput.PathProvider output) { + this.output = output; } @Override - public void run(CachedOutput cache) { + public CompletableFuture run(CachedOutput cache) { tables.clear(); - Path out = dataGenerator.getOutputFolder(); registerTables(); - ValidationContext validator = new ValidationContext(LootContextParamSets.ALL_PARAMS, e -> null, tables::get); - - tables.forEach((name, table) -> { - LootTables.validate(validator, name, table); + ValidationContext validator = new ValidationContext(LootContextParamSets.ALL_PARAMS, new LootDataResolver() { + @Override + public T getElement(LootDataId pId) { + return null; + } }); + tables.forEach((name, table) -> table.validate(validator)); + Multimap problems = validator.getProblems(); if (!problems.isEmpty()) { logger.warn("Problems detected for LootTableGenerator: " + getName()); @@ -72,14 +72,12 @@ public void run(CachedOutput cache) { }); throw new IllegalStateException("Failed to validate loot tables, see logs."); } + List> futures = new LinkedList<>(); tables.forEach((name, table) -> { - Path output = getPath(out, name); - try { - DataProvider.saveStable(cache, LootTables.serialize(table), output); - } catch (IOException e) { - logger.error("Couldn't save loot table {}", output, e); - } + Path output = this.output.json(name); + futures.add(DataProvider.saveStable(cache, LootDataType.TABLE.parser().toJsonTree(table), output)); }); + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } protected abstract void registerTables(); @@ -101,8 +99,8 @@ public static abstract class BlockLootProvider extends LootTableProvider { ); protected static final LootItemCondition.Builder NO_SILK_TOUCH = SILK_TOUCH.invert(); - protected BlockLootProvider(DataGenerator dataGenerator) { - super(dataGenerator); + protected BlockLootProvider(PackOutput.PathProvider output) { + super(output); } protected LootPool.Builder singleItem(ItemLike item) { diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java index d92c0ecb..24c8b1e2 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java @@ -17,7 +17,7 @@ protected AbstractItemStackRecipeBuilder(RecipeSerializer serializer, Resourc @Override protected ResourceLocation getAdvancementId() { - return new ResourceLocation(id.getNamespace(), "recipes/" + this.result.getItem().getItemCategory().getRecipeFolderName() + "/" + id.getPath()); + return new ResourceLocation(id.getNamespace(), "recipes/__advancement/" + id.getPath()); } @Override diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java index 27399956..c65b2a52 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java @@ -15,7 +15,6 @@ import net.minecraft.world.level.ItemLike; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.crafting.conditions.ICondition; -import net.minecraftforge.common.crafting.conditions.IConditionBuilder; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; @@ -132,7 +131,7 @@ protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { } protected InventoryChangeTrigger.TriggerInstance hasItem(ItemPredicate... predicates) { - return new InventoryChangeTrigger.TriggerInstance(EntityPredicate.Composite.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); + return new InventoryChangeTrigger.TriggerInstance(ContextAwarePredicate.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); } public abstract class AbstractFinishedRecipe implements FinishedRecipe { diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java index 143f3e19..cd97519b 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java @@ -5,55 +5,56 @@ import com.google.gson.JsonObject; import net.minecraft.advancements.critereon.*; import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; +import net.minecraft.data.PackOutput; import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; /** * Created by covers1624 on 27/12/20. */ public abstract class RecipeProvider implements DataProvider { - private static final Logger logger = LogManager.getLogger(); - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - private final Map recipes = new HashMap<>(); - private final DataGenerator generator; + private final PackOutput output; - public RecipeProvider(DataGenerator generatorIn) { - this.generator = generatorIn; + public RecipeProvider(PackOutput output) { + this.output = output; } @Override - public final void run(CachedOutput cache) throws IOException { - Path path = generator.getOutputFolder(); + public final CompletableFuture run(CachedOutput cache) { + Path path = output.getOutputFolder(); registerRecipes(); + List> futures = new LinkedList<>(); for (Map.Entry entry : recipes.entrySet()) { ResourceLocation id = entry.getKey(); FinishedRecipe finishedRecipe = entry.getValue().build(); - saveRecipe(cache, finishedRecipe.serializeRecipe(), path.resolve("data/" + id.getNamespace() + "/recipes/" + id.getPath() + ".json")); + futures.add(DataProvider.saveStable(cache, finishedRecipe.serializeRecipe(), path.resolve("data/" + id.getNamespace() + "/recipes/" + id.getPath() + ".json"))); JsonObject advancement = finishedRecipe.serializeAdvancement(); if (advancement != null) { - saveRecipeAdvancement(cache, advancement, path.resolve("data/" + id.getNamespace() + "/advancements/" + id.getPath() + ".json")); + futures.add(DataProvider.saveStable(cache, advancement, path.resolve("data/" + id.getNamespace() + "/advancements/" + id.getPath() + ".json"))); } } + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } protected abstract void registerRecipes(); @@ -112,29 +113,12 @@ protected T builder(T builder) { protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result) { return builder(FurnaceRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, result, id)); } - protected SpecialRecipeBuilder special(SimpleRecipeSerializer serializer, String id) { return builder(SpecialRecipeBuilder.builder(serializer, id)); } - protected SpecialRecipeBuilder special(SimpleRecipeSerializer serializer, ResourceLocation id) { return builder(SpecialRecipeBuilder.builder(serializer, id)); } + protected SpecialCraftingRecipeBuilder special(SimpleCraftingRecipeSerializer serializer, String id) { return builder(SpecialCraftingRecipeBuilder.builder(serializer, id)); } + protected SpecialCraftingRecipeBuilder special(SimpleCraftingRecipeSerializer serializer, ResourceLocation id) { return builder(SpecialCraftingRecipeBuilder.builder(serializer, id)); } //@formatter:on - private void saveRecipe(CachedOutput cache, JsonObject recipeJson, Path path) { - try { - DataProvider.saveStable(cache, recipeJson, path); - } catch (IOException e) { - logger.error("Couldn't save recipe {}", path, e); - } - - } - - private void saveRecipeAdvancement(CachedOutput cache, JsonObject advancementJson, Path path) { - try { - DataProvider.saveStable(cache, advancementJson, path); - } catch (IOException e) { - logger.error("Couldn't save recipe advancement {}", path, e); - } - } - protected EnterBlockTrigger.TriggerInstance enteredBlock(Block blockIn) { - return new EnterBlockTrigger.TriggerInstance(EntityPredicate.Composite.ANY, blockIn, StatePropertiesPredicate.ANY); + return new EnterBlockTrigger.TriggerInstance(ContextAwarePredicate.ANY, blockIn, StatePropertiesPredicate.ANY); } protected InventoryChangeTrigger.TriggerInstance hasItem(ItemLike itemIn) { @@ -146,6 +130,6 @@ protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { } protected InventoryChangeTrigger.TriggerInstance hasItem(ItemPredicate... predicates) { - return new InventoryChangeTrigger.TriggerInstance(EntityPredicate.Composite.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); + return new InventoryChangeTrigger.TriggerInstance(ContextAwarePredicate.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/SpecialRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java similarity index 64% rename from src/main/java/codechicken/lib/datagen/recipe/SpecialRecipeBuilder.java rename to src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java index 575836c8..17a29d61 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/SpecialRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java @@ -4,27 +4,27 @@ import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer; /** * Created by covers1624 on 25/3/21. */ -public class SpecialRecipeBuilder implements RecipeBuilder { +public class SpecialCraftingRecipeBuilder implements RecipeBuilder { - protected final SimpleRecipeSerializer serializer; + protected final SimpleCraftingRecipeSerializer serializer; protected final ResourceLocation id; - public SpecialRecipeBuilder(SimpleRecipeSerializer serializer, ResourceLocation id) { + public SpecialCraftingRecipeBuilder(SimpleCraftingRecipeSerializer serializer, ResourceLocation id) { this.serializer = serializer; this.id = id; } - public static SpecialRecipeBuilder builder(SimpleRecipeSerializer serializer, String id) { + public static SpecialCraftingRecipeBuilder builder(SimpleCraftingRecipeSerializer serializer, String id) { return builder(serializer, new ResourceLocation(id)); } - public static SpecialRecipeBuilder builder(SimpleRecipeSerializer serializer, ResourceLocation id) { - return new SpecialRecipeBuilder(serializer, id); + public static SpecialCraftingRecipeBuilder builder(SimpleCraftingRecipeSerializer serializer, ResourceLocation id) { + return new SpecialCraftingRecipeBuilder(serializer, id); } @Override diff --git a/src/main/java/codechicken/lib/gui/SimpleCreativeTab.java b/src/main/java/codechicken/lib/gui/SimpleCreativeTab.java deleted file mode 100644 index 71f2ec13..00000000 --- a/src/main/java/codechicken/lib/gui/SimpleCreativeTab.java +++ /dev/null @@ -1,28 +0,0 @@ -package codechicken.lib.gui; - -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.ItemStack; - -import javax.annotation.Nonnull; -import java.util.function.Supplier; - -/** - * Provides a Simple way to create a {@link CreativeModeTab} - *

- * Created by covers1624 on 7/11/2016. - */ -public class SimpleCreativeTab extends CreativeModeTab { - - private final Supplier stackSupplier; - - public SimpleCreativeTab(String label, Supplier stackSupplier) { - super(label); - this.stackSupplier = stackSupplier; - } - - @Nonnull - @Override - public ItemStack makeIcon() { - return stackSupplier.get(); - } -} diff --git a/src/main/java/codechicken/lib/internal/proxy/ProxyClient.java b/src/main/java/codechicken/lib/internal/ClientInit.java similarity index 62% rename from src/main/java/codechicken/lib/internal/proxy/ProxyClient.java rename to src/main/java/codechicken/lib/internal/ClientInit.java index ea0ab255..ed96cd2c 100644 --- a/src/main/java/codechicken/lib/internal/proxy/ProxyClient.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -1,39 +1,47 @@ -package codechicken.lib.internal.proxy; +package codechicken.lib.internal; import codechicken.lib.CodeChickenLib; import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigSyncManager; -import codechicken.lib.model.bakery.ModelBakery; +import codechicken.lib.model.CompositeItemModel; import codechicken.lib.render.CCRenderEventHandler; import codechicken.lib.render.block.BlockRenderingRegistry; -import codechicken.lib.render.item.map.MapRenderRegistry; +import net.covers1624.quack.util.CrashLock; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; +import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; /** - * Created by covers1624 on 30/10/19. + * Created by covers1624 on 8/9/23. */ -public class ProxyClient extends Proxy { +public class ClientInit { + + private static final CrashLock LOCK = new CrashLock("Already Initialized."); public static boolean catchBlockRenderExceptions; public static boolean messagePlayerOnRenderExceptionCaught; - @Override - public void clientSetup(FMLClientSetupEvent event) { + public static void init() { + LOCK.lock(); + IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); + loadClientConfig(); - //OpenGLUtils.loadCaps(); - // CustomParticleHandler.init(); - BlockRenderingRegistry.init(); - ModelBakery.init(); CCRenderEventHandler.init(); - MinecraftForge.EVENT_BUS.register(new MapRenderRegistry()); - // ClientCommandHandler.instance.registerCommand(new CCLClientCommand()); - MinecraftForge.EVENT_BUS.addListener(this::onClientDisconnected); + MinecraftForge.EVENT_BUS.addListener(ClientInit::onClientDisconnected); + + bus.addListener(ClientInit::onClientSetup); + bus.addListener(ClientInit::onRegisterGeometryLoaders); } - private void loadClientConfig() { + private static void onClientSetup(FMLClientSetupEvent event) { + BlockRenderingRegistry.init(); + } + + private static void loadClientConfig() { ConfigCategory clientTag = CodeChickenLib.config.getCategory("client"); clientTag.delete("block_renderer_dispatcher_misc"); clientTag.delete("catchItemRenderExceptions"); @@ -57,7 +65,11 @@ private void loadClientConfig() { clientTag.save(); } - private void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut event) { + private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut event) { ConfigSyncManager.onClientDisconnected(); } + + private static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) { + event.register("item_composite", new CompositeItemModel()); + } } diff --git a/src/main/java/codechicken/lib/internal/DataGenerators.java b/src/main/java/codechicken/lib/internal/DataGenerators.java index 91638b65..62673c3f 100644 --- a/src/main/java/codechicken/lib/internal/DataGenerators.java +++ b/src/main/java/codechicken/lib/internal/DataGenerators.java @@ -2,16 +2,21 @@ import codechicken.lib.datagen.LanguageProvider; import codechicken.lib.util.CCLTags; +import net.minecraft.core.HolderLookup; import net.minecraft.data.DataGenerator; -import net.minecraft.data.tags.BlockTagsProvider; +import net.minecraft.data.PackOutput; import net.minecraft.data.tags.ItemTagsProvider; import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraftforge.common.data.BlockTagsProvider; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.data.event.GatherDataEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; +import java.util.concurrent.CompletableFuture; + import static codechicken.lib.CodeChickenLib.MOD_ID; /** @@ -23,21 +28,24 @@ public class DataGenerators { @SubscribeEvent public static void gatherDataGenerators(GatherDataEvent event) { DataGenerator gen = event.getGenerator(); + PackOutput output = gen.getPackOutput(); + CompletableFuture lookupProvider = event.getLookupProvider(); + ExistingFileHelper files = event.getExistingFileHelper(); - BlockTags blockTagsProvider = new BlockTags(gen, files); + BlockTags blockTagsProvider = new BlockTags(output, lookupProvider, files); gen.addProvider(event.includeServer(), blockTagsProvider); - gen.addProvider(event.includeServer(), new ItemTags(gen, blockTagsProvider, files)); - gen.addProvider(event.includeClient() || event.includeServer(), new LangUS(gen, LanguageProvider.getDist(event))); + gen.addProvider(event.includeServer(), new ItemTags(output, lookupProvider, blockTagsProvider.contentsGetter(), files)); + gen.addProvider(event.includeClient() || event.includeServer(), new LangUS(output, LanguageProvider.getDist(event))); } private static class BlockTags extends BlockTagsProvider { - public BlockTags(DataGenerator generatorIn, ExistingFileHelper files) { - super(generatorIn, MOD_ID, files); + public BlockTags(PackOutput output, CompletableFuture lookupProvider, ExistingFileHelper files) { + super(output, lookupProvider, MOD_ID, files); } @Override - protected void addTags() { + protected void addTags(HolderLookup.Provider pProvider) { tag(CCLTags.Blocks.WOOL) .addTag(CCLTags.Blocks.WOOL_WHITE) .addTag(CCLTags.Blocks.WOOL_ORANGE) @@ -81,12 +89,12 @@ public String getName() { private static class ItemTags extends ItemTagsProvider { - public ItemTags(DataGenerator generatorIn, BlockTags blockTagProvider, ExistingFileHelper files) { - super(generatorIn, blockTagProvider, MOD_ID, files); + public ItemTags(PackOutput output, CompletableFuture lookupProvider, CompletableFuture> blockTagProvider, ExistingFileHelper files) { + super(output, lookupProvider, blockTagProvider, MOD_ID, files); } @Override - protected void addTags() { + protected void addTags(HolderLookup.Provider pProvider) { tag(CCLTags.Items.WOOL) .addTag(CCLTags.Items.WOOL_WHITE) .addTag(CCLTags.Items.WOOL_ORANGE) @@ -130,8 +138,8 @@ public String getName() { public static class LangUS extends LanguageProvider { - public LangUS(DataGenerator gen, Side side) { - super(gen, MOD_ID, "en_us", side); + public LangUS(PackOutput output, Side side) { + super(output, MOD_ID, "en_us", side); } @Override diff --git a/src/main/java/codechicken/lib/internal/HighlightHandler.java b/src/main/java/codechicken/lib/internal/HighlightHandler.java index b223bc6d..aada1ba9 100644 --- a/src/main/java/codechicken/lib/internal/HighlightHandler.java +++ b/src/main/java/codechicken/lib/internal/HighlightHandler.java @@ -16,7 +16,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RenderLevelLastEvent; +import net.minecraftforge.client.event.RenderLevelStageEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import org.jetbrains.annotations.Nullable; @@ -59,7 +59,9 @@ public void setupRenderState() { ); @SubscribeEvent - public static void renderLevelLast(RenderLevelLastEvent event) { + public static void renderLevelLast(RenderLevelStageEvent event) { + if (event.getStage() != RenderLevelStageEvent.Stage.AFTER_PARTICLES) return; + if (highlight != null) { MultiBufferSource.BufferSource source = Minecraft.getInstance().renderBuffers().bufferSource(); Camera camera = Minecraft.getInstance().gameRenderer.getMainCamera(); diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 8afe90e5..cd861795 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -5,14 +5,16 @@ import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Matrix4f; +import com.mojang.blaze3d.vertex.VertexSorting; import net.covers1624.quack.image.AnimatedGifEncoder; import net.covers1624.quack.io.IOUtils; import net.covers1624.quack.util.SneakyUtils; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.item.ItemStack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.joml.Matrix4f; import org.lwjgl.opengl.GL11; import javax.imageio.ImageIO; @@ -77,13 +79,15 @@ private static void takeItemScreenshot(ItemStack stack, int res, Consumer dispatcher = event.getDispatcher(); - CountCommand.register(dispatcher); - KillAllCommand.register(dispatcher); - MiscCommands.register(dispatcher); - DevCommands.register(dispatcher); + CommandBuildContext context = event.getBuildContext(); + CountCommand.register(dispatcher, context); + KillAllCommand.register(dispatcher, context); + MiscCommands.register(dispatcher, context); + DevCommands.register(dispatcher, context); } private static void registerClientCommands(RegisterClientCommandsEvent event) { diff --git a/src/main/java/codechicken/lib/internal/command/EntityTypeArgument.java b/src/main/java/codechicken/lib/internal/command/EntityTypeArgument.java deleted file mode 100644 index 636816c6..00000000 --- a/src/main/java/codechicken/lib/internal/command/EntityTypeArgument.java +++ /dev/null @@ -1,32 +0,0 @@ -package codechicken.lib.internal.command; - -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.arguments.ResourceKeyArgument; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.network.chat.Component; -import net.minecraft.world.entity.EntityType; - -import static codechicken.lib.CodeChickenLib.MOD_ID; -import static net.minecraft.commands.arguments.ResourceKeyArgument.getRegistryKeyType; - -/** - * Created by covers1624 on 17/9/20. - */ -public class EntityTypeArgument { - - private static final DynamicCommandExceptionType MISSING = new DynamicCommandExceptionType(p -> - Component.translatable(MOD_ID + ":argument.entity_type.invalid", p) - ); - - public static ResourceKeyArgument> entityType() { - return ResourceKeyArgument.key(Registry.ENTITY_TYPE_REGISTRY); - } - - public static Holder> getEntityType(CommandContext stack, String name) throws CommandSyntaxException { - return getRegistryKeyType(stack, name, Registry.ENTITY_TYPE_REGISTRY, MISSING); - } -} diff --git a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java index 693a8076..d1ba89b3 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java @@ -4,7 +4,10 @@ import com.mojang.brigadier.context.CommandContext; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.ResourceArgument; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; @@ -17,8 +20,6 @@ import java.util.function.Predicate; import java.util.stream.StreamSupport; -import static codechicken.lib.internal.command.EntityTypeArgument.entityType; -import static codechicken.lib.internal.command.EntityTypeArgument.getEntityType; import static codechicken.lib.math.MathHelper.floor; import static net.minecraft.ChatFormatting.*; import static net.minecraft.commands.Commands.argument; @@ -29,13 +30,13 @@ */ public class CountCommand { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("count") .requires(e -> e.hasPermission(2)) - .then(argument("entity", entityType()) + .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { - EntityType entityType = getEntityType(ctx, "entity").value(); + EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); return countAllEntities(ctx, e -> e.equals(entityType)); }) ) @@ -65,13 +66,14 @@ private static int countAllEntities(CommandContext ctx, Pred for (EntityType type : order) { int count = counts.getInt(type); String name = ForgeRegistries.ENTITY_TYPES.getKey(type).toString(); - ctx.getSource().sendSuccess(Component.literal(GREEN + name + RESET + " x " + AQUA + count), false); + ctx.getSource().sendSuccess(() -> Component.literal(GREEN + name + RESET + " x " + AQUA + count), false); total += count; } if (order.size() == 0) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.count.fail"), false); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.count.fail"), false); } else if (order.size() > 1) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.count.total", AQUA.toString() + total + RESET), false); + int finalTotal = total; + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.count.total", AQUA.toString() + finalTotal + RESET), false); } return total; diff --git a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java index 389cf6ac..fd2df032 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java @@ -4,9 +4,11 @@ import com.mojang.brigadier.context.CommandContext; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.covers1624.quack.collection.StreamableIterable; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; -import net.minecraft.core.Holder; +import net.minecraft.commands.arguments.ResourceArgument; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; @@ -23,8 +25,6 @@ import java.util.function.Consumer; import java.util.function.Predicate; -import static codechicken.lib.internal.command.EntityTypeArgument.entityType; -import static codechicken.lib.internal.command.EntityTypeArgument.getEntityType; import static codechicken.lib.math.MathHelper.floor; import static net.minecraft.ChatFormatting.*; import static net.minecraft.commands.Commands.argument; @@ -35,21 +35,21 @@ */ public class KillAllCommand { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("killall") .requires(e -> e.hasPermission(2)) - .then(argument("entity", entityType()) + .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { - EntityType entityType = getEntityType(ctx, "entity").value(); + EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); return killallForce(ctx, entityType, e -> Objects.equals(e.getType(), entityType)); }) ) .executes(ctx -> killallForce(ctx, null, e -> e instanceof Enemy)) .then(literal("gracefully") - .then(argument("entity", entityType()) + .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { - EntityType entityType = getEntityType(ctx, "entity").value(); + EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); return killAllGracefully(ctx, entityType, e -> Objects.equals(e.getType(), entityType)); }) ) @@ -69,7 +69,7 @@ private static int killallForce(CommandContext ctx, @Nullabl private static int killEntities(CommandContext ctx, @Nullable EntityType type, Predicate predicate, Consumer killFunc) { if (type == EntityType.PLAYER) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.fail.player").withStyle(RED), false); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.fail.player").withStyle(RED), false); return 0; } CommandSourceStack source = ctx.getSource(); @@ -77,7 +77,7 @@ private static int killEntities(CommandContext ctx, @Nullabl ServerChunkCache provider = world.getChunkSource(); Object2IntMap> counts = new Object2IntOpenHashMap<>(); counts.defaultReturnValue(0); - StreamableIterable entities = StreamableIterable.of(world.getEntities().getAll()) + FastStream entities = FastStream.of(world.getEntities().getAll()) .filter(Objects::nonNull) .filter(predicate) .filter(e -> provider.hasChunk(floor(e.getX()) >> 4, floor(e.getZ()) >> 4)); @@ -95,13 +95,14 @@ private static int killEntities(CommandContext ctx, @Nullabl for (EntityType t : order) { int count = counts.getInt(t); String name = ForgeRegistries.ENTITY_TYPES.getKey(t).toString(); - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.success.line", RED + name + RESET + " x " + AQUA + count), false); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.success.line", RED + name + RESET + " x " + AQUA + count), false); total += count; } if (order.size() == 0) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.fail"), false); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.fail"), false); } else if (order.size() > 1) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.success", AQUA.toString() + total + RESET), false); + int finalTotal = total; + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.success", AQUA.toString() + finalTotal + RESET), false); } return total; } diff --git a/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java b/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java index 3ea6edb3..41d6b1b8 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java +++ b/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java @@ -2,6 +2,7 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; @@ -12,7 +13,7 @@ */ public class MiscCommands { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("meminfo") .requires(e -> e.hasPermission(4)) @@ -21,11 +22,11 @@ public static void register(CommandDispatcher dispatcher) { .then(literal("gc") .requires(e -> e.hasPermission(4)) .executes(ctx -> { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.gc.before"), true); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.gc.before"), true); printMemInfo(ctx, true); - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.gc.performing"), true); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.gc.performing"), true); System.gc(); - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.gc.after"), true); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.gc.after"), true); printMemInfo(ctx, true); return 0; }) @@ -48,8 +49,10 @@ private static int printMemInfo(CommandContext ctx, boolean mem = " " + mem; allocated = " " + allocated; } - ctx.getSource().sendSuccess(Component.literal(mem), true); - ctx.getSource().sendSuccess(Component.literal(allocated), true); + String finalMem = mem; + String finalAllocated = allocated; + ctx.getSource().sendSuccess(() -> Component.literal(finalMem), true); + ctx.getSource().sendSuccess(() -> Component.literal(finalAllocated), true); return 0; } diff --git a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java index 18f7ffbe..94b1880d 100644 --- a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java @@ -66,10 +66,10 @@ private static int setHighlightArg(CommandContext ctx) throw private static int setHighlight(CommandContext ctx, BlockPos pos) { CommandSourceStack source = ctx.getSource(); if (HighlightHandler.highlight == null) { - source.sendSuccess(Component.literal("Set highlight at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); + source.sendSuccess(() -> Component.literal("Set highlight at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); } else { BlockPos prev = HighlightHandler.highlight; - source.sendSuccess(Component.literal("Moved highlight from " + prev.getX() + ", " + prev.getY() + ", " + prev.getZ() + " to " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); + source.sendSuccess(() -> Component.literal("Moved highlight from " + prev.getX() + ", " + prev.getY() + ", " + prev.getZ() + " to " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); } HighlightHandler.highlight = pos; return 0; @@ -83,7 +83,7 @@ private static int clearHighlight(CommandContext ctx) { } HighlightHandler.highlight = null; HighlightHandler.useDepth = true; - source.sendSuccess(Component.literal("Highlight position cleared."), false); + source.sendSuccess(() -> Component.literal("Highlight position cleared."), false); return 0; } @@ -97,9 +97,9 @@ private static int toggleDepth(CommandContext ctx) { HighlightHandler.useDepth = !HighlightHandler.useDepth; if (HighlightHandler.useDepth) { - source.sendSuccess(Component.literal("Enabled highlight depth."), false); + source.sendSuccess(() -> Component.literal("Enabled highlight depth."), false); } else { - source.sendSuccess(Component.literal("Disabled highlight depth."), false); + source.sendSuccess(() -> Component.literal("Disabled highlight depth."), false); } return 0; } @@ -127,7 +127,7 @@ private static int dumpInfo(CommandContext ctx) { builder.append(" Tile Class: ").append(tryOrNull(() -> tile.getClass())).append("\n"); builder.append(" Tile Id: ").append(tryOrNull(() -> ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(tile.getType()))).append("\n"); builder.append(" Tile NBT: ").append(tryOrNull(() -> tile.saveWithoutMetadata())).append("\n"); - source.sendSuccess(Component.literal(builder.toString()), false); + source.sendSuccess(() -> Component.literal(builder.toString()), false); return 0; } diff --git a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java index d1702c30..e05bffbf 100644 --- a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java @@ -4,6 +4,7 @@ import com.mojang.brigadier.context.CommandContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraftforge.registries.ForgeRegistries; @@ -26,15 +27,12 @@ public static void register(CommandDispatcher dispatcher) { private static int execute(CommandContext command) { CommandSourceStack ctx = command.getSource(); Player player = command.getSource().getPlayer(); - ItemStack stack = player.getMainHandItem(); - if (stack.isEmpty()) { - stack = player.getOffhandItem(); - } + ItemStack stack = player.hasItemInSlot(EquipmentSlot.MAINHAND) ? player.getMainHandItem() : player.getOffhandItem(); if (stack.isEmpty()) return 0; String tag = stack.hasTag() ? stack.getTag().toString() : "Item has no NBT."; - ctx.sendSuccess(Component.literal("Registry Name: " + ForgeRegistries.ITEMS.getKey(stack.getItem())), false); - ctx.sendSuccess(Component.literal("NBT : " + tag), false); + ctx.sendSuccess(() -> Component.literal("Registry Name: " + ForgeRegistries.ITEMS.getKey(stack.getItem())), false); + ctx.sendSuccess(() -> Component.literal("NBT : " + tag), false); return 0; } } diff --git a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java index 60536a6f..b08921fd 100644 --- a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java @@ -57,7 +57,7 @@ private static int renderToFile(CommandContext ctx, int reso Path path = getPath(ctx, "png"); ItemStack held = getHeldItem(); - ctx.getSource().sendSuccess(Component.literal("Queued item render to file: " + path), false); + ctx.getSource().sendSuccess(() -> Component.literal("Queued item render to file: " + path), false); ItemFileRenderer.addRenderTask(held, path, resolution); return 0; } @@ -70,7 +70,7 @@ private static int renderToGif(CommandContext ctx, int resol Path path = getPath(ctx, "gif"); ItemStack held = getHeldItem(); - src.sendSuccess(Component.literal("Queued item render to gif: " + path), false); + src.sendSuccess(() -> Component.literal("Queued item render to gif: " + path), false); ItemFileRenderer.addGifRenderTask(held, path, resolution, fps, duration); return 0; } diff --git a/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java b/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java index 911a5bc3..66b37ca2 100644 --- a/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java +++ b/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java @@ -2,6 +2,7 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; @@ -14,7 +15,7 @@ */ public class DevCommands { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("setup_dev_world") .requires(e -> e.hasPermission(4)) diff --git a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java index 223a1977..521c70df 100644 --- a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java +++ b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java @@ -3,9 +3,9 @@ import codechicken.lib.render.item.IItemRenderer; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraftforge.client.ForgeHooksClient; import org.spongepowered.asm.mixin.Mixin; @@ -22,18 +22,18 @@ public class ItemRendererMixin { @Inject ( - method = "render(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/client/renderer/block/model/ItemTransforms$TransformType;ZLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;IILnet/minecraft/client/resources/model/BakedModel;)V", + method = "render", at = @At ("HEAD"), cancellable = true ) - public void onRenderItem(ItemStack stack, ItemTransforms.TransformType transformType, boolean leftHand, PoseStack mStack, MultiBufferSource buffers, int packedLight, int packedOverlay, BakedModel modelIn, CallbackInfo ci) { + public void onRenderItem(ItemStack stack, ItemDisplayContext context, boolean leftHand, PoseStack mStack, MultiBufferSource buffers, int packedLight, int packedOverlay, BakedModel modelIn, CallbackInfo ci) { if (modelIn instanceof IItemRenderer) { ci.cancel(); mStack.pushPose(); //If anyone doesnt return an IItemRenderer from here, your doing it wrong. - IItemRenderer renderer = (IItemRenderer) ForgeHooksClient.handleCameraTransforms(mStack, modelIn, transformType, leftHand); + IItemRenderer renderer = (IItemRenderer) ForgeHooksClient.handleCameraTransforms(mStack, modelIn, context, leftHand); mStack.translate(-0.5D, -0.5D, -0.5D); - renderer.renderItem(stack, transformType, mStack, buffers, packedLight, packedOverlay); + renderer.renderItem(stack, context, mStack, buffers, packedLight, packedOverlay); mStack.popPose(); } } diff --git a/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java index 87578401..26af5cae 100644 --- a/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java +++ b/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java @@ -2,11 +2,11 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Matrix4f; import net.minecraft.client.Camera; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.LightTexture; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -20,15 +20,15 @@ @Mixin (LevelRenderer.class) public abstract class LevelRendererMixin { - @Inject ( - method = "renderLevel", - at = @At ( - value = "INVOKE", - ordinal = 1, - target = "Lnet/minecraft/client/renderer/PostChain;process(F)V" - ) - ) - private void disableTransparencyShaderDepth(PoseStack p1, float p2, long p3, boolean p4, Camera p5, GameRenderer p6, LightTexture p7, Matrix4f p8, CallbackInfo ci) { - GlStateManager._depthMask(false); - } +// @Inject ( +// method = "renderLevel", +// at = @At ( +// value = "INVOKE", +// ordinal = 1, +// target = "Lnet/minecraft/client/renderer/PostChain;process(F)V" +// ) +// ) +// private void disableTransparencyShaderDepth(PoseStack p1, float p2, long p3, boolean p4, Camera p5, GameRenderer p6, LightTexture p7, Matrix4f p8, CallbackInfo ci) { +// GlStateManager._depthMask(false); +// } } diff --git a/src/main/java/codechicken/lib/internal/proxy/Proxy.java b/src/main/java/codechicken/lib/internal/proxy/Proxy.java deleted file mode 100644 index 85fa05f7..00000000 --- a/src/main/java/codechicken/lib/internal/proxy/Proxy.java +++ /dev/null @@ -1,21 +0,0 @@ -package codechicken.lib.internal.proxy; - -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent; - -/** - * Created by covers1624 on 30/10/19. - */ -public class Proxy { - - public void commonSetup(FMLCommonSetupEvent event) { - } - - public void clientSetup(FMLClientSetupEvent event) { - } - - public void serverSetup(FMLDedicatedServerSetupEvent event) { - } - -} diff --git a/src/main/java/codechicken/lib/inventory/InventoryUtils.java b/src/main/java/codechicken/lib/inventory/InventoryUtils.java index 9151f21e..b519f2ae 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryUtils.java +++ b/src/main/java/codechicken/lib/inventory/InventoryUtils.java @@ -217,7 +217,7 @@ public static boolean areStacksIdentical(@Nonnull ItemStack stack1, @Nonnull Ite } public static boolean canStack(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { - return stack1.isEmpty() || stack2.isEmpty() || (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.tagMatches(stack2, stack1)) && stack1.isStackable(); + return stack1.isEmpty() || stack2.isEmpty() || (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameTags(stack2, stack1)) && stack1.isStackable(); } /** diff --git a/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java b/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java index fb9fdc0a..74a5c9ff 100644 --- a/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java +++ b/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java @@ -2,6 +2,9 @@ import codechicken.lib.data.MCDataInput; import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.flag.FeatureFlag; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; @@ -11,15 +14,19 @@ public interface ICCLContainerType { static MenuType create(ICCLContainerFactory factory) { - return new CCLContainerType<>(factory); + return new CCLContainerType<>(factory, FeatureFlags.VANILLA_SET); + } + + static MenuType create(ICCLContainerFactory factory, FeatureFlag... featureFlags) { + return new CCLContainerType<>(factory, FeatureFlags.REGISTRY.subset(featureFlags)); } T create(int windowId, Inventory inventory, MCDataInput packet); class CCLContainerType extends MenuType implements ICCLContainerType { - public CCLContainerType(MenuType.MenuSupplier factory) { - super(factory); + public CCLContainerType(MenuType.MenuSupplier factory, FeatureFlagSet featureFlags) { + super(factory, featureFlags); } @Override diff --git a/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java b/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java index 8305e01e..8aa20e8a 100644 --- a/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java +++ b/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java @@ -3,6 +3,7 @@ import net.minecraft.sounds.SoundEvent; import net.minecraft.util.LazyLoadedValue; import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterial; import net.minecraft.world.item.ArmorMaterials; import net.minecraft.world.item.crafting.Ingredient; @@ -39,13 +40,13 @@ public static Builder builder() { } @Override - public int getDurabilityForSlot(EquipmentSlot slot) { - return durability[slot.getIndex()]; + public int getDurabilityForType(ArmorItem.Type type) { + return durability[type.ordinal()]; } @Override - public int getDefenseForSlot(EquipmentSlot slot) { - return damageReduction[slot.getIndex()]; + public int getDefenseForType(ArmorItem.Type type) { + return damageReduction[type.ordinal()]; } @Override @@ -98,8 +99,8 @@ public Builder durability(EquipmentSlot slot, int value) { } public Builder durabilityFactor(int factor) { - for (int i = 0; i < 4; i++) { - durability[i] = ArmorMaterials.HEALTH_PER_SLOT[i] * factor; + for (ArmorItem.Type type : ArmorItem.Type.values()) { + durability[type.ordinal()] = ArmorMaterials.HEALTH_FUNCTION_FOR_TYPE.get(type) * factor; } return this; } diff --git a/src/main/java/codechicken/lib/model/CompositeItemModel.java b/src/main/java/codechicken/lib/model/CompositeItemModel.java new file mode 100644 index 00000000..054641c3 --- /dev/null +++ b/src/main/java/codechicken/lib/model/CompositeItemModel.java @@ -0,0 +1,126 @@ +package codechicken.lib.model; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.gson.*; +import com.mojang.math.Transformation; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.block.model.BlockModel; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.*; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.client.model.CompositeModel; +import net.minecraftforge.client.model.geometry.IGeometryBakingContext; +import net.minecraftforge.client.model.geometry.IGeometryLoader; +import net.minecraftforge.client.model.geometry.IUnbakedGeometry; +import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +/** + * Similar to Forge's {@link CompositeModel}, with support for children to have overrides. + *

+ * Created by covers1624 on 8/9/23. + */ +public class CompositeItemModel implements IGeometryLoader { + + @Override + public Geometry read(JsonObject jsonObject, JsonDeserializationContext ctx) throws JsonParseException { + JsonObject childrenObj = jsonObject.getAsJsonObject("children"); + if (childrenObj == null) throw new JsonParseException("Composite model requires children."); + + Map children = FastStream.of(childrenObj.entrySet()) + .toImmutableMap(Map.Entry::getKey, e -> ctx.deserialize(e.getValue(), BlockModel.class)); + + List itemPasses; + JsonArray itemPassesArr = jsonObject.getAsJsonArray("item_render_order"); + if (itemPassesArr != null) { + itemPasses = FastStream.of(itemPassesArr) + .map(JsonElement::getAsString) + .peek(e -> { + if (!children.containsKey(e)) { + throw new JsonParseException("Invalid child in item_render_order." + e + " does not exist."); + } + }) + .toImmutableList(); + } else { + itemPasses = ImmutableList.copyOf(children.keySet()); + } + + return new Geometry(children, itemPasses); + } + + public record Geometry(Map children, List itemPasses) implements IUnbakedGeometry { + + @Override + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + TextureAtlasSprite particle = spriteGetter.apply(context.getMaterial("particle")); + ModelState effectiveState = composeState(context.getRootTransform(), modelState); + + ImmutableMap children = FastStream.of(this.children.entrySet()) + .filter(e -> context.isComponentVisible(e.getKey(), true)) + .toImmutableMap(Map.Entry::getKey, e -> e.getValue().bake(baker, e.getValue(), spriteGetter, effectiveState, modelLocation, true)); + + ImmutableList itemPasses = FastStream.of(this.itemPasses) + .map(children::get) + .toImmutableList(); + + class Overrides extends ItemOverrides { + + @Nullable + @Override + public BakedModel resolve(BakedModel pModel, ItemStack pStack, @Nullable ClientLevel pLevel, @Nullable LivingEntity pEntity, int pSeed) { + ImmutableList iPasses = FastStream.of(itemPasses) + .map(e -> e.getOverrides().resolve(e, pStack, pLevel, pEntity, pSeed)) + .toImmutableList(); + + return new CompositeModel.Baked( + context.isGui3d(), + context.useBlockLight(), + context.useAmbientOcclusion(), + particle, + context.getTransforms(), + this, + children, + iPasses + ); + } + } + + return new CompositeModel.Baked( + context.isGui3d(), + context.useBlockLight(), + context.useAmbientOcclusion(), + particle, + context.getTransforms(), + new Overrides(), + children, + itemPasses + ); + } + + @Override + public void resolveParents(Function modelGetter, IGeometryBakingContext context) { + children.values().forEach(value -> value.resolveParents(modelGetter)); + } + + @Override + public Set getConfigurableComponentNames() { + return children.keySet(); + } + + private static ModelState composeState(Transformation rootTransform, ModelState state) { + if (rootTransform.isIdentity()) return state; + + return UnbakedGeometryHelper.composeRootTransformIntoModelState(state, rootTransform); + } + } +} diff --git a/src/main/java/codechicken/lib/model/ItemQuadBakery.java b/src/main/java/codechicken/lib/model/ItemQuadBakery.java index f08628b4..aaae8e29 100644 --- a/src/main/java/codechicken/lib/model/ItemQuadBakery.java +++ b/src/main/java/codechicken/lib/model/ItemQuadBakery.java @@ -31,7 +31,7 @@ public static List bakeItem(ModelState state, TextureAtlasSprite... s List quads = new LinkedList<>(); for (int i = 0; i < sprites.length; i++) { TextureAtlasSprite sprite = sprites[i]; - List unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite); + List unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite.contents()); quads.addAll(UnbakedGeometryHelper.bakeElements(unbaked, e -> sprite, state, new ResourceLocation("ccl:dynamic"))); } return quads; diff --git a/src/main/java/codechicken/lib/model/ModelRegistryHelper.java b/src/main/java/codechicken/lib/model/ModelRegistryHelper.java index 2f84aeeb..c703e29a 100644 --- a/src/main/java/codechicken/lib/model/ModelRegistryHelper.java +++ b/src/main/java/codechicken/lib/model/ModelRegistryHelper.java @@ -15,23 +15,13 @@ public class ModelRegistryHelper { private final List> registerModels = new LinkedList<>(); - private final List modelBakePreCallbacks = new LinkedList<>(); - private final List modelBakeCallbacks = new LinkedList<>(); - - public ModelRegistryHelper(IEventBus eventBus) { - eventBus.register(this); - } public ModelRegistryHelper() { - FMLJavaModLoadingContext.get().getModEventBus().register(this); + this(FMLJavaModLoadingContext.get().getModEventBus()); } - public void registerPreBakeCallback(IModelBakeCallbackPre callback) { - modelBakePreCallbacks.add(callback); - } - - public void registerCallback(IModelBakeCallback callback) { - modelBakeCallbacks.add(callback); + public ModelRegistryHelper(IEventBus eventBus) { + eventBus.register(this); } public void register(ModelResourceLocation location, BakedModel model) { @@ -39,38 +29,9 @@ public void register(ModelResourceLocation location, BakedModel model) { } @SubscribeEvent - public void onModelBake(ModelEvent.BakingCompleted event) { - for (IModelBakeCallbackPre callback : modelBakePreCallbacks) { - callback.onModelBakePre(event); - } - + public void onModelBake(ModelEvent.ModifyBakingResult event) { for (Pair pair : registerModels) { event.getModels().put(pair.getKey(), pair.getValue()); } - - for (IModelBakeCallback callback : modelBakeCallbacks) { - callback.onModelBake(event); - } - } - - public interface IModelBakeCallbackPre { - - /** - * Called before CCL does anything to the ModelRegistry. - * Useful for wrapped models, Use this in the constructor of the wrapped model. - * - * @param event The Model event. - */ - void onModelBakePre(ModelEvent.BakingCompleted event); - } - - public interface IModelBakeCallback { - - /** - * A Simple callback for model baking. - * - * @param event The Model event. - */ - void onModelBake(ModelEvent.BakingCompleted event); } } diff --git a/src/main/java/codechicken/lib/model/PerspectiveModel.java b/src/main/java/codechicken/lib/model/PerspectiveModel.java index 44e7a6c7..8cf07cf9 100644 --- a/src/main/java/codechicken/lib/model/PerspectiveModel.java +++ b/src/main/java/codechicken/lib/model/PerspectiveModel.java @@ -3,10 +3,10 @@ import codechicken.lib.util.TransformUtils; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Transformation; -import com.mojang.math.Vector3f; -import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.world.item.ItemDisplayContext; import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; /** * A simple {@link BakedModel} implementation, with automatic handling of @@ -27,10 +27,10 @@ public interface PerspectiveModel extends BakedModel { PerspectiveModelState getModelState(); @Override - default BakedModel applyTransform(ItemTransforms.TransformType transformType, PoseStack pStack, boolean leftFlip) { + default BakedModel applyTransform(ItemDisplayContext context, PoseStack pStack, boolean leftFlip) { PerspectiveModelState modelState = getModelState(); if (modelState != null) { - Transformation transform = getModelState().getTransform(transformType); + Transformation transform = getModelState().getTransform(context); Vector3f trans = transform.getTranslation(); pStack.translate(trans.x(), trans.y(), trans.z()); @@ -47,6 +47,6 @@ default BakedModel applyTransform(ItemTransforms.TransformType transformType, Po } return this; } - return BakedModel.super.applyTransform(transformType, pStack, leftFlip); + return BakedModel.super.applyTransform(context, pStack, leftFlip); } } diff --git a/src/main/java/codechicken/lib/model/PerspectiveModelState.java b/src/main/java/codechicken/lib/model/PerspectiveModelState.java index 130edd80..22f584cf 100644 --- a/src/main/java/codechicken/lib/model/PerspectiveModelState.java +++ b/src/main/java/codechicken/lib/model/PerspectiveModelState.java @@ -3,8 +3,8 @@ import codechicken.lib.util.TransformUtils; import com.google.common.collect.ImmutableMap; import com.mojang.math.Transformation; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; import net.minecraft.client.resources.model.ModelState; +import net.minecraft.world.item.ItemDisplayContext; import java.util.Map; @@ -19,20 +19,20 @@ public class PerspectiveModelState implements ModelState { public static final PerspectiveModelState IDENTITY = new PerspectiveModelState(ImmutableMap.of()); - private final Map transforms; + private final Map transforms; private final boolean isUvLocked; - public PerspectiveModelState(Map transforms) { + public PerspectiveModelState(Map transforms) { this(transforms, false); } - public PerspectiveModelState(Map transforms, boolean isUvLocked) { + public PerspectiveModelState(Map transforms, boolean isUvLocked) { this.transforms = ImmutableMap.copyOf(transforms); this.isUvLocked = isUvLocked; } - public Transformation getTransform(TransformType type) { - return transforms.getOrDefault(type, Transformation.identity()); + public Transformation getTransform(ItemDisplayContext context) { + return transforms.getOrDefault(context, Transformation.identity()); } @Override diff --git a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java b/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java index f0a4ee3c..3e58dd29 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java @@ -10,12 +10,12 @@ import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; @@ -32,6 +32,7 @@ /** * Created by covers1624 on 1/02/2017. */ +@Deprecated // These may go away unless there is sufficient need for generic implementations like these. public abstract class AbstractBakedPropertiesModel implements PerspectiveModel, IModelParticleProvider, BakedModel { protected final ModelProperties properties; @@ -118,7 +119,7 @@ public PerspectiveModelState getModelState() { } @Override - public BakedModel applyTransform(TransformType transformType, PoseStack pStack, boolean leftFlip) { - return PerspectiveModel.super.applyTransform(transformType, pStack, leftFlip); + public BakedModel applyTransform(ItemDisplayContext context, PoseStack pStack, boolean leftFlip) { + return PerspectiveModel.super.applyTransform(context, pStack, leftFlip); } } diff --git a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java b/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java index c35eb8df..c93011b3 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java @@ -13,6 +13,7 @@ /** * Created by covers1624 on 19/11/2016. */ +@Deprecated // These may go away unless there is sufficient need for generic implementations like these. public class ModelProperties implements Copyable { public static final ModelProperties DEFAULT_ITEM = ModelProperties.builder() diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java index ac87a8b2..85f1c4df 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java @@ -16,6 +16,7 @@ /** * Created by covers1624 on 25/11/2016. */ +@Deprecated // These may go away unless there is sufficient need for generic implementations like these. public class PerspectiveAwareBakedModel extends AbstractBakedPropertiesModel { private final ImmutableMap> faceQuads; diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java index 79ecec81..e3a37c87 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java @@ -19,6 +19,7 @@ /** * Created by covers1624 on 19/11/2016. */ +@Deprecated // These may go away unless there is sufficient need for generic implementations like these. public class PerspectiveAwareLayeredModel extends AbstractBakedPropertiesModel { private final ImmutableMap> unculledQuads; diff --git a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java b/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java index 9c0172f4..ae0172d3 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java @@ -11,7 +11,6 @@ import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -20,6 +19,7 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; @@ -28,7 +28,6 @@ import javax.annotation.Nullable; import java.util.Collections; import java.util.List; -import java.util.Random; import java.util.function.Function; /** @@ -48,7 +47,7 @@ public abstract class WrappedItemModel implements BakedModel { @Override public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel world, @Nullable LivingEntity entity, int seed) { WrappedItemModel.this.entity = entity; - WrappedItemModel.this.world = world == null ? entity == null ? null : (ClientLevel) entity.level : null; + WrappedItemModel.this.world = world == null ? entity == null ? null : (ClientLevel) entity.level() : null; return originalModel; } }; @@ -82,7 +81,7 @@ public ItemOverrides getOverrides() { * Render the wrapped model. *

* This does not take into account all the special edge cases hardcoded into - * {@link ItemRenderer#render(ItemStack, ItemTransforms.TransformType, boolean, PoseStack, MultiBufferSource, int, int, BakedModel)}. + * {@link ItemRenderer#render(ItemStack, ItemDisplayContext, boolean, PoseStack, MultiBufferSource, int, int, BakedModel)}. * * @param stack The stack. * @param pStack The pose stack. diff --git a/src/main/java/codechicken/lib/model/bakery/CCBakeryModel.java b/src/main/java/codechicken/lib/model/bakery/CCBakeryModel.java deleted file mode 100644 index 8f60b461..00000000 --- a/src/main/java/codechicken/lib/model/bakery/CCBakeryModel.java +++ /dev/null @@ -1,99 +0,0 @@ -package codechicken.lib.model.bakery; - -import codechicken.lib.render.particle.IModelParticleProvider; -import codechicken.lib.texture.TextureUtils; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.client.model.data.ModelData; - -import javax.annotation.Nonnull; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * Created by covers1624 on 26/10/2016. - */ -public class CCBakeryModel implements BakedModel, IModelParticleProvider { - - public CCBakeryModel() { - } - - @Override - public List getQuads(BlockState state, Direction side, RandomSource rand) { - return getQuads(state, side, rand, ModelData.EMPTY, null); - } - - @Nonnull - @Override - public List getQuads(BlockState state, Direction side, RandomSource rand, ModelData modelData, RenderType layer) { - return ModelBakery.getCachedModel(state, modelData).getQuads(state, side, rand, modelData, layer); - } - - @Override - public boolean useAmbientOcclusion() { - return true; - } - - @Override - public boolean isGui3d() { - return false; - } - - @Override - public boolean usesBlockLight() { - return false; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return TextureUtils.getMissingSprite(); - } - - @Override - public Set getHitEffects(BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data) { - BakedModel model = ModelBakery.getCachedModel(state, data); - if (model instanceof IModelParticleProvider) { - return ((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, data); - } - return Collections.emptySet(); - } - - @Override - public Set getDestroyEffects(BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data) { - BakedModel model = ModelBakery.getCachedModel(state, data); - if (model instanceof IModelParticleProvider) { - return ((IModelParticleProvider) model).getDestroyEffects(state, world, pos, data); - } - return Collections.emptySet(); - } - - @Override - public ItemOverrides getOverrides() { - return new ItemOverrides() { - @Override - public BakedModel resolve(BakedModel originalModel, ItemStack stack, ClientLevel world, LivingEntity entity, int seed) { - BakedModel model = ModelBakery.getCachedItemModel(stack); - return Objects.requireNonNullElse(model, originalModel); - } - }; - } -} diff --git a/src/main/java/codechicken/lib/model/bakery/IBakeryProvider.java b/src/main/java/codechicken/lib/model/bakery/IBakeryProvider.java deleted file mode 100644 index 33602f57..00000000 --- a/src/main/java/codechicken/lib/model/bakery/IBakeryProvider.java +++ /dev/null @@ -1,24 +0,0 @@ -package codechicken.lib.model.bakery; - -import codechicken.lib.model.bakery.generation.IBakery; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -/** - * Created by covers1624 on 28/10/2016. - * For Blocks, implement this on your block class. - * For Items, implement this on your item class. - */ -public interface IBakeryProvider { - - /** - * Used to provide a bakery for the Item OR Block. - * This should basically always return either ILayeredBlockBakery or ISimpleBlockBakery for blocks or, - * IItemBakery for items. - * - * @return The Bakery! - */ - @OnlyIn (Dist.CLIENT) - IBakery getBakery(); - -} diff --git a/src/main/java/codechicken/lib/model/bakery/ModelBakery.java b/src/main/java/codechicken/lib/model/bakery/ModelBakery.java deleted file mode 100644 index bf5e43cb..00000000 --- a/src/main/java/codechicken/lib/model/bakery/ModelBakery.java +++ /dev/null @@ -1,229 +0,0 @@ -package codechicken.lib.model.bakery; - -import codechicken.lib.model.bakedmodels.ModelProperties; -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import codechicken.lib.model.bakedmodels.PerspectiveAwareBakedModel; -import codechicken.lib.model.bakedmodels.PerspectiveAwareLayeredModel; -import codechicken.lib.model.bakery.generation.IBlockBakery; -import codechicken.lib.model.bakery.generation.IItemBakery; -import codechicken.lib.model.bakery.key.IBlockStateKeyGenerator; -import codechicken.lib.model.bakery.key.IItemStackKeyGenerator; -import codechicken.lib.util.LogUtils; -import codechicken.lib.util.ResourceUtils; -import codechicken.lib.util.TransformUtils; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.registries.ForgeRegistries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.function.BiFunction; -import java.util.function.Function; - -/** - * Created by covers1624 on 25/10/2016. - */ -@OnlyIn (Dist.CLIENT) -public class ModelBakery { - - private static final Logger logger = LogManager.getLogger(); - - private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("ccl.debugBakeryLogging")); - private static final boolean FORCE_BLOCK_REBAKE = Boolean.parseBoolean(System.getProperty("ccl.debugForceBlockModelRebake")); - private static final boolean FORCE_ITEM_REBAKE = Boolean.parseBoolean(System.getProperty("ccl.debugForceItemModelRebake")); - - private static final Cache keyModelCache = CacheBuilder.newBuilder().expireAfterAccess(30, TimeUnit.MINUTES).build(); - - private static final ModelProperties DEFAULT = ModelProperties.builder() - .withAO(true) - .withGui3D(true) - .build(); - private static final PerspectiveProperties DEFAULT_PERSPECTIVE = DEFAULT.toBuilder() - .withTransforms(TransformUtils.DEFAULT_BLOCK) - .build(); - - private static final Map itemKeyGeneratorMap = Collections.synchronizedMap(new HashMap<>()); - private static final Map blockKeyGeneratorMap = Collections.synchronizedMap(new HashMap<>()); - private static BakedModel missingModel; - - public static final IBlockStateKeyGenerator defaultBlockKeyGenerator = (state, data) -> state.toString(); - - public static final IItemStackKeyGenerator defaultItemKeyGenerator = stack -> ForgeRegistries.ITEMS.getKey(stack.getItem()).toString() + "|" + stack.getDamageValue(); - - public static void init() { - ResourceUtils.registerReloadListener(e -> nukeModelCache()); - FMLJavaModLoadingContext.get().getModEventBus().addListener(ModelBakery::onModelBake); - } - - private static void onModelBake(ModelEvent.BakingCompleted event) { - missingModel = event.getModelManager().getMissingModel(); - } - - public static IBlockStateKeyGenerator getKeyGenerator(Block block) { - if (blockKeyGeneratorMap.containsKey(block)) { - return blockKeyGeneratorMap.get(block); - } - return defaultBlockKeyGenerator; - } - - public static IItemStackKeyGenerator getKeyGenerator(Item item) { - if (itemKeyGeneratorMap.containsKey(item)) { - return itemKeyGeneratorMap.get(item); - } - return defaultItemKeyGenerator; - } - - public static void registerBlockKeyGenerator(Block block, IBlockStateKeyGenerator generator) { - if (blockKeyGeneratorMap.containsKey(block)) { - throw new IllegalArgumentException("Unable to register IBlockStateKeyGenerator as one is already registered for block:" + ForgeRegistries.BLOCKS.getKey(block)); - } - blockKeyGeneratorMap.put(block, generator); - } - - public static void registerItemKeyGenerator(Item item, IItemStackKeyGenerator generator) { - if (itemKeyGeneratorMap.containsKey(item)) { - throw new IllegalArgumentException("Unable to register IItemStackKeyGenerator as one is already registered for item: " + ForgeRegistries.ITEMS.getKey(item)); - } - itemKeyGeneratorMap.put(item, generator); - } - - public static BakedModel getCachedItemModel(ItemStack stack) { - BakedModel model; - IItemStackKeyGenerator generator = getKeyGenerator(stack.getItem()); - String key = generator.generateKey(stack); - model = keyModelCache.getIfPresent(key); - if (model == null || FORCE_ITEM_REBAKE) { - try { - model = timeModelGeneration(ModelBakery::generateItemModel, stack, "ITEM: " + key); - } catch (Throwable t) { - LogUtils.errorOnce(logger, t, "ItemBaking", "Fatal exception thrown whilst baking item model for: " + stack); - return missingModel; - } - if (model != missingModel) { - keyModelCache.put(key, model); - } - } - return model; - - } - - public static BakedModel generateItemModel(ItemStack stack) { - Item item = stack.getItem(); - if (item instanceof IBakeryProvider bakeryProvider) { - - IItemBakery bakery = (IItemBakery) bakeryProvider.getBakery(); - - List unculledQuads = List.copyOf(bakery.bakeItemQuads(null, stack)); - - Map> faceQuads = new HashMap<>(); - for (Direction face : Direction.BY_3D_DATA) { - faceQuads.put(face, List.copyOf(bakery.bakeItemQuads(face, stack))); - } - - PerspectiveProperties properties = bakery.getModelProperties(stack); - return new PerspectiveAwareBakedModel(faceQuads, unculledQuads, properties); - } - return missingModel; - } - - public static BakedModel getCachedModel(BlockState state, ModelData data) { - if (state == null) { - return missingModel; - } - BakedModel model; - IBlockStateKeyGenerator keyGenerator = getKeyGenerator(state.getBlock()); - String key = keyGenerator.generateKey(state, data); - model = keyModelCache.getIfPresent(key); - if (model == null || FORCE_BLOCK_REBAKE) { - try { - model = timeModelGeneration(ModelBakery::generateModel, state, data, "BLOCK: " + key); - } catch (Throwable t) { - LogUtils.errorOnce(logger, t, "BlockBaking", "Fatal exception thrown whilst baking block model for: " + state); - return missingModel; - } - if (model != missingModel) { - keyModelCache.put(key, model); - } - } - return model; - } - - public static BakedModel generateModel(BlockState state, ModelData data) { - if (state.getBlock() instanceof IBakeryProvider bakeryProvider) { - IBlockBakery bakery = (IBlockBakery) bakeryProvider.getBakery(); - ChunkRenderTypeSet layers = bakery.getBlockRenderLayers(); - - Map> unculledQuads = new HashMap<>(); - Map>> culledQuads = new HashMap<>(); - for (RenderType layer : layers) { - unculledQuads.put(layer, List.copyOf(bakery.bakeFace(null, layer, state, data))); - - Map> faceQuadMap = new HashMap<>(); - for (Direction face : Direction.BY_3D_DATA) { - faceQuadMap.put(face, List.copyOf(bakery.bakeFace(face, layer, state, data))); - } - culledQuads.put(layer, faceQuadMap); - - } - return new PerspectiveAwareLayeredModel(culledQuads, unculledQuads, DEFAULT_PERSPECTIVE, RenderType.solid()); - } - return missingModel; - } - - private static R timeModelGeneration(Function func, T thing, String logPostfix) { - if (DEBUG) { - logger.info("Baking Model.. Key: {}", logPostfix); - } - long start = System.nanoTime(); - R ret = func.apply(thing); - long end = System.nanoTime(); - logGenTime(start, end); - return ret; - } - - private static R timeModelGeneration(BiFunction func, T thing, U thing2, String logPostfix) { - if (DEBUG) { - logger.info("Baking Model.. Key: {}", logPostfix); - } - long start = System.nanoTime(); - R ret = func.apply(thing, thing2); - long end = System.nanoTime(); - logGenTime(start, end); - return ret; - } - - private static void logGenTime(long start, long end) { - if (DEBUG) { - long delta = end - start; - long millis = TimeUnit.NANOSECONDS.toMillis(delta); - String s; - if (millis >= 5) { - s = millis + "ms"; - } else { - s = delta + "ns"; - } - - logger.info("Baking finished in {}.", s); - } - } - - public static void nukeModelCache() { - keyModelCache.invalidateAll(); - } -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/IBakery.java b/src/main/java/codechicken/lib/model/bakery/generation/IBakery.java deleted file mode 100644 index c60ccd8d..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/IBakery.java +++ /dev/null @@ -1,9 +0,0 @@ -package codechicken.lib.model.bakery.generation; - -/** - * Created by covers1624 on 4/03/2017. - * Just a simple interface to mark things as a bakery. You should never need to implement this yourself. - */ -public interface IBakery { - -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/IBlockBakery.java b/src/main/java/codechicken/lib/model/bakery/generation/IBlockBakery.java deleted file mode 100644 index 8107bc12..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/IBlockBakery.java +++ /dev/null @@ -1,45 +0,0 @@ -package codechicken.lib.model.bakery.generation; - -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * Created by covers1624 on 28/10/2016. - */ -public interface IBlockBakery extends IItemBakery { - - ChunkRenderTypeSet SOLID = ChunkRenderTypeSet.of(RenderType.solid()); - ChunkRenderTypeSet CUTOUT_MIPPED = ChunkRenderTypeSet.of(RenderType.cutoutMipped()); - ChunkRenderTypeSet CUTOUT = ChunkRenderTypeSet.of(RenderType.cutout()); - ChunkRenderTypeSet TRANSLUCENT = ChunkRenderTypeSet.of(RenderType.translucent()); - - /** - * Gets the layers to generate quads for. - *

- * Please cache these, they are expensive to construct. - * - * @return The {@link ChunkRenderTypeSet}. - */ - ChunkRenderTypeSet getBlockRenderLayers(); - - /** - * Called to generate the quads for a given face, layer, state and model data. - * - * @param face The face quads are requested for, {@code null} for un-culled. - * @param layer The layer quads are requested for. - * @param state The {@link BlockState} of your block - * @param data Any {@link ModelData} your block may have returned. - * @return The quads for the layer or empty. - */ - @OnlyIn (Dist.CLIENT) - List bakeFace(@Nullable Direction face, RenderType layer, BlockState state, ModelData data); -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/IItemBakery.java b/src/main/java/codechicken/lib/model/bakery/generation/IItemBakery.java deleted file mode 100644 index 434d586d..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/IItemBakery.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.model.bakery.generation; - -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Direction; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * A bakery capable of generating quads for an {@link ItemStack}. - *

- * This is used for regular items and {@link BlockItem}s. - *

- * Created by covers1624 on 12/02/2017. - */ -public interface IItemBakery extends IBakery { - - /** - * Used to generate quads for your {@link ItemStack}. - * - * @param face The face quads are requested for. - * @param stack The stack! - * @return The quads. - */ - @OnlyIn (Dist.CLIENT) - List bakeItemQuads(@Nullable Direction face, ItemStack stack); - - /** - * Return the {@link PerspectiveProperties} for the generated model. - * - * @return The {@link PerspectiveProperties} to use. - */ - @OnlyIn (Dist.CLIENT) - default PerspectiveProperties getModelProperties(ItemStack stack) { - return stack.getItem() instanceof BlockItem ? PerspectiveProperties.DEFAULT_BLOCK : PerspectiveProperties.DEFAULT_ITEM; - } -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/package-info.java b/src/main/java/codechicken/lib/model/bakery/generation/package-info.java deleted file mode 100644 index 111fca7b..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -package codechicken.lib.model.bakery.generation; - -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/codechicken/lib/model/bakery/key/IBlockStateKeyGenerator.java b/src/main/java/codechicken/lib/model/bakery/key/IBlockStateKeyGenerator.java deleted file mode 100644 index 7299d235..00000000 --- a/src/main/java/codechicken/lib/model/bakery/key/IBlockStateKeyGenerator.java +++ /dev/null @@ -1,24 +0,0 @@ -package codechicken.lib.model.bakery.key; - -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; - -/** - * Created by covers1624 on 26/11/2016. - */ -public interface IBlockStateKeyGenerator { - - /** - * Used to tell the bakery what BlockStates are the same. - * The bakery implementation is global, so make sure you prefix your blocks registry name and meta. - * E.g. "thermalexpansion:machine|6" - * Just remember, this key defines a model in the cache, if a model with the provided key is not found, your bakery will be called to generate one. - *

- * The stack is always as follows CCBakeryModel > Bakery > Gen Key > Hey does this key exist in cache ? ret model : Call block specific bakery to gen model > cache > ret. - * - * @param state - * @return - */ - String generateKey(BlockState state, ModelData modelData); - -} diff --git a/src/main/java/codechicken/lib/model/bakery/key/IItemStackKeyGenerator.java b/src/main/java/codechicken/lib/model/bakery/key/IItemStackKeyGenerator.java deleted file mode 100644 index 6ec1379c..00000000 --- a/src/main/java/codechicken/lib/model/bakery/key/IItemStackKeyGenerator.java +++ /dev/null @@ -1,25 +0,0 @@ -package codechicken.lib.model.bakery.key; - -import net.minecraft.world.item.ItemStack; - -/** - * Created by covers1624 on 2/11/2016. - * This is used so the bakery has some idea of the difference between generated models. - * This is used specifically as the cache key, and is called frequently, Make sure it's well optimized. - */ -public interface IItemStackKeyGenerator { - - /** - * Used to tell the bakery what ItemStacks are the same. - * The bakery implementation is global, so make sure you prefix your blocks registry name and meta. - * E.g. "thermalexpansion:machine|6" - * Just remember, this key defines a model in the cache, if a model with the provided key is not found, your bakery will be called to generate one. - *

- * The stack is always as follows ModelBakery > Bakery > Gen Key > Hey does this key exist in cache ? ret model : Call item specific bakery to gen model > cache > ret. - * - * @param stack The stack to generate a key for. - * @return The uniquely identifiable key for the given stack. - */ - String generateKey(ItemStack stack); - -} diff --git a/src/main/java/codechicken/lib/raytracer/RayTracer.java b/src/main/java/codechicken/lib/raytracer/RayTracer.java index 193a6e3d..d6c06688 100644 --- a/src/main/java/codechicken/lib/raytracer/RayTracer.java +++ b/src/main/java/codechicken/lib/raytracer/RayTracer.java @@ -20,12 +20,6 @@ public class RayTracer { - - @Deprecated (forRemoval = true, since = "1.18.2") // Unnecessarily specific level type. - public static BlockHitResult retraceBlock(LevelReader level, Player player, BlockPos pos) { - return retraceBlock((BlockGetter) level, player, pos); - } - public static BlockHitResult retraceBlock(BlockGetter level, Player player, BlockPos pos) { Vec3 startVec = getStartVec(player); Vec3 endVec = getEndVec(player); @@ -42,7 +36,7 @@ public static BlockHitResult retraceBlock(BlockGetter level, Player player, Bloc } private static double getBlockReachDistance_server(ServerPlayer player) { - return player.getAttribute(ForgeMod.REACH_DISTANCE.get()).getValue(); + return player.getAttribute(ForgeMod.BLOCK_REACH.get()).getValue(); } @OnlyIn (Dist.CLIENT) @@ -69,7 +63,7 @@ public static BlockHitResult retrace(Player player, double reach, ClipContext.Bl public static BlockHitResult retrace(Player player, double reach, ClipContext.Block blockMode, ClipContext.Fluid fluidMode) { Vec3 startVec = getStartVec(player); Vec3 endVec = getEndVec(player, reach); - return player.level.clip(new ClipContext(startVec, endVec, blockMode, fluidMode, player)); + return player.level().clip(new ClipContext(startVec, endVec, blockMode, fluidMode, player)); } public static Vec3 getCorrectedHeadVec(Player player) { @@ -83,7 +77,7 @@ public static Vec3 getStartVec(Player player) { @Deprecated // Use attribute directly? avoid all this nonsense. public static double getBlockReachDistance(Player player) { - return player.level.isClientSide ? getBlockReachDistance_client() : player instanceof ServerPlayer ? getBlockReachDistance_server((ServerPlayer) player) : 5D; + return player.level().isClientSide ? getBlockReachDistance_client() : player instanceof ServerPlayer ? getBlockReachDistance_server((ServerPlayer) player) : 5D; } public static Vec3 getEndVec(Player player) { diff --git a/src/main/java/codechicken/lib/render/CCModelLibrary.java b/src/main/java/codechicken/lib/render/CCModelLibrary.java index 91f095c0..10327877 100644 --- a/src/main/java/codechicken/lib/render/CCModelLibrary.java +++ b/src/main/java/codechicken/lib/render/CCModelLibrary.java @@ -95,7 +95,7 @@ public static RenderType getIcos7RenderType(ResourceLocation texture) { public static RenderType.CompositeState makeIcosState(ResourceLocation texture) { return RenderType.CompositeState.builder() - .setShaderState(RenderStateShard.BLOCK_SHADER) + .setShaderState(RenderStateShard.RENDERTYPE_SOLID_SHADER) // TODO 1.20, this is probably wrong. .setTextureState(new RenderStateShard.TextureStateShard(texture, false, false)) .setTransparencyState(RenderStateShard.NO_TRANSPARENCY) .setLightmapState(RenderStateShard.LIGHTMAP) diff --git a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java index f5ede1a4..594ff821 100644 --- a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java +++ b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java @@ -1,7 +1,7 @@ package codechicken.lib.render.block; +import codechicken.lib.internal.ClientInit; import codechicken.lib.internal.ExceptionMessageEventHandler; -import codechicken.lib.internal.proxy.ProxyClient; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraft.CrashReport; @@ -50,7 +50,7 @@ public CCBlockRendererDispatcher(BlockRenderDispatcher parent, BlockColors block //In world. @Override - public void renderBatched(BlockState state, BlockPos pos, BlockAndTintGetter level, PoseStack stack, VertexConsumer builder, boolean checkSides, RandomSource rand, ModelData modelData, RenderType renderType, boolean queryModelSpecificData) { + public void renderBatched(BlockState state, BlockPos pos, BlockAndTintGetter level, PoseStack stack, VertexConsumer builder, boolean checkSides, RandomSource rand, ModelData modelData, RenderType renderType) { try { ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(state.getBlock(), e -> e.canHandleBlock(level, pos, state, renderType)); if (renderer != null) { @@ -58,7 +58,7 @@ public void renderBatched(BlockState state, BlockPos pos, BlockAndTintGetter lev return; } } catch (Throwable t) { - if (ProxyClient.catchBlockRenderExceptions) { + if (ClientInit.catchBlockRenderExceptions) { handleCaughtException(t, state, pos, level); return; } @@ -68,9 +68,9 @@ public void renderBatched(BlockState state, BlockPos pos, BlockAndTintGetter lev throw new ReportedException(crashreport); } try { - parentDispatcher.renderBatched(state, pos, level, stack, builder, checkSides, rand, modelData, renderType, queryModelSpecificData); + parentDispatcher.renderBatched(state, pos, level, stack, builder, checkSides, rand, modelData, renderType); } catch (Throwable t) { - if (ProxyClient.catchBlockRenderExceptions) { + if (ClientInit.catchBlockRenderExceptions) { handleCaughtException(t, state, pos, level); return; } @@ -126,7 +126,7 @@ private static void handleCaughtException(Throwable t, BlockState inState, Block builder.append(" Tile Id: ").append(tryOrNull(() -> ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(tile.getType()))).append("\n"); builder.append(" Tile NBT: ").append(tryOrNull(() -> tile.saveWithFullMetadata())).append("\n"); builder.append("This functionality can be disabled in the CCL config file.\n"); - if (ProxyClient.messagePlayerOnRenderExceptionCaught) { + if (ClientInit.messagePlayerOnRenderExceptionCaught) { builder.append("You can also turn off player messages in the CCL config file.\n"); } String logMessage = builder.toString(); @@ -135,7 +135,7 @@ private static void handleCaughtException(Throwable t, BlockState inState, Block logger.error(logMessage, t); } Player player = Minecraft.getInstance().player; - if (ProxyClient.messagePlayerOnRenderExceptionCaught && player != null) { + if (ClientInit.messagePlayerOnRenderExceptionCaught && player != null) { long time = System.nanoTime(); if (TimeUnit.NANOSECONDS.toSeconds(time - lastTime) > 5) { lastTime = time; diff --git a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java index 52956eeb..83c273c2 100644 --- a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java @@ -2,6 +2,7 @@ import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexSorting; import net.minecraft.client.renderer.RenderType; /** @@ -21,8 +22,8 @@ public DelegateRenderType(RenderType parent, VertexFormat format) { } @Override - public void end(BufferBuilder p_228631_1_, int p_228631_2_, int p_228631_3_, int p_228631_4_) { - parent.end(p_228631_1_, p_228631_2_, p_228631_3_, p_228631_4_); + public void end(BufferBuilder buffer, VertexSorting sorting) { + parent.end(buffer, sorting); } @Override diff --git a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java index 80d817b7..5427d82d 100644 --- a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.VertexBuffer; import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexSorting; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; @@ -21,7 +22,7 @@ public class VBORenderType extends DelegateRenderType implements AutoCloseable { private final BiConsumer factory; - private final VertexBuffer vertexBuffer = new VertexBuffer(); + private final VertexBuffer vertexBuffer = new VertexBuffer(VertexBuffer.Usage.DYNAMIC); private final BufferBuilder builder; private boolean dirty = true; @@ -80,7 +81,7 @@ private void rebuild() { } @Override - public void end(BufferBuilder buffer, int cameraX, int cameraY, int cameraZ) { + public void end(BufferBuilder buffer, VertexSorting sorting) { // End buffer and discard state, we don't operate like this. buffer.endOrDiscardIfEmpty(); @@ -137,7 +138,7 @@ public void setupRenderState() { } @Override - public void end(BufferBuilder buffer, int cameraX, int cameraY, int cameraZ) { + public void end(BufferBuilder buffer, VertexSorting sorting) { // End buffer and discard state, we don't operate like this. buffer.endOrDiscardIfEmpty(); diff --git a/src/main/java/codechicken/lib/render/item/IItemRenderer.java b/src/main/java/codechicken/lib/render/item/IItemRenderer.java index e9b7d23a..1c875ddd 100644 --- a/src/main/java/codechicken/lib/render/item/IItemRenderer.java +++ b/src/main/java/codechicken/lib/render/item/IItemRenderer.java @@ -7,11 +7,11 @@ import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; @@ -24,13 +24,13 @@ public interface IItemRenderer extends PerspectiveModel { * Called to render your item with complete control. Bypasses all vanilla rendering of your model. * * @param stack The {@link ItemStack} being rendered. - * @param transformType The {@link TransformType} of where we are rendering. + * @param ctx The {@link ItemDisplayContext} of where we are rendering. * @param mStack The {@link PoseStack} to get / add transformations to. * @param source The {@link MultiBufferSource} to retrieve buffers from. * @param packedLight The {@link LightTexture} packed coords. * @param packedOverlay The {@link OverlayTexture} packed coords. */ - void renderItem(ItemStack stack, TransformType transformType, PoseStack mStack, MultiBufferSource source, int packedLight, int packedOverlay); + void renderItem(ItemStack stack, ItemDisplayContext ctx, PoseStack mStack, MultiBufferSource source, int packedLight, int packedOverlay); //Useless methods for IItemRenderer. //@formatter:off diff --git a/src/main/java/codechicken/lib/render/shader/CCUniform.java b/src/main/java/codechicken/lib/render/shader/CCUniform.java index 42a2c6cc..7ae99a96 100644 --- a/src/main/java/codechicken/lib/render/shader/CCUniform.java +++ b/src/main/java/codechicken/lib/render/shader/CCUniform.java @@ -3,12 +3,12 @@ import codechicken.lib.render.shader.UniformType.Carrier; import com.mojang.blaze3d.shaders.Shader; import com.mojang.blaze3d.shaders.Uniform; -import com.mojang.math.Matrix3f; -import com.mojang.math.Matrix4f; -import com.mojang.math.Vector3f; -import com.mojang.math.Vector4f; import org.apache.commons.lang3.NotImplementedException; import org.jetbrains.annotations.Nullable; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.joml.Vector4f; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL21; import org.lwjgl.opengl.GL30; diff --git a/src/main/java/codechicken/lib/render/shader/ICCUniform.java b/src/main/java/codechicken/lib/render/shader/ICCUniform.java index 5fb38430..42d5df52 100644 --- a/src/main/java/codechicken/lib/render/shader/ICCUniform.java +++ b/src/main/java/codechicken/lib/render/shader/ICCUniform.java @@ -1,8 +1,8 @@ package codechicken.lib.render.shader; import codechicken.lib.vec.Matrix4; -import com.mojang.math.Matrix3f; -import com.mojang.math.Matrix4f; +import org.joml.Matrix3f; +import org.joml.Matrix4f; /** * Created by covers1624 on 8/4/22. @@ -178,70 +178,70 @@ public interface ICCUniform { private static float[] toArrayF(Matrix3f matrix) { return new float[] { matrix.m00, - matrix.m10, - matrix.m20, matrix.m01, - matrix.m11, - matrix.m21, matrix.m02, + matrix.m10, + matrix.m11, matrix.m12, + matrix.m20, + matrix.m21, matrix.m22, }; } private static float[] toArrayF(Matrix4f matrix) { return new float[] { - matrix.m00, - matrix.m10, - matrix.m20, - matrix.m30, - matrix.m01, - matrix.m11, - matrix.m21, - matrix.m31, - matrix.m02, - matrix.m12, - matrix.m22, - matrix.m32, - matrix.m03, - matrix.m13, - matrix.m23, - matrix.m33, + matrix.m00(), + matrix.m01(), + matrix.m02(), + matrix.m03(), + matrix.m10(), + matrix.m11(), + matrix.m12(), + matrix.m13(), + matrix.m20(), + matrix.m21(), + matrix.m22(), + matrix.m23(), + matrix.m30(), + matrix.m31(), + matrix.m32(), + matrix.m33(), }; } private static double[] toArrayD(Matrix3f matrix) { return new double[] { matrix.m00, - matrix.m10, - matrix.m20, matrix.m01, - matrix.m11, - matrix.m21, matrix.m02, + matrix.m10, + matrix.m11, matrix.m12, + matrix.m20, + matrix.m21, matrix.m22, }; } private static double[] toArrayD(Matrix4f matrix) { return new double[] { - matrix.m00, - matrix.m10, - matrix.m20, - matrix.m30, - matrix.m01, - matrix.m11, - matrix.m21, - matrix.m31, - matrix.m02, - matrix.m12, - matrix.m22, - matrix.m32, - matrix.m03, - matrix.m13, - matrix.m23, - matrix.m33, + matrix.m00(), + matrix.m01(), + matrix.m02(), + matrix.m03(), + matrix.m10(), + matrix.m11(), + matrix.m12(), + matrix.m13(), + matrix.m20(), + matrix.m21(), + matrix.m22(), + matrix.m23(), + matrix.m30(), + matrix.m31(), + matrix.m32(), + matrix.m33(), }; } } diff --git a/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java b/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java index a5db4f48..bba1a7ee 100644 --- a/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java +++ b/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java @@ -1,114 +1,114 @@ -package codechicken.lib.texture; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.inventory.InventoryMenu; -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; - -import java.util.*; -import java.util.function.Consumer; - -/** - * Utilities for persistent TextureAtlasSprite registration. - *

- * Created by covers1624 on 27/10/19. - */ -public class SpriteRegistryHelper { - - public static final ResourceLocation TEXTURES = InventoryMenu.BLOCK_ATLAS; - // public static final ResourceLocation PARTICLE_TEXTURES = "textures/particle"; - // public static final ResourceLocation MOB_EFFECT_TEXTURES = "textures/mob_effect"; - // public static final ResourceLocation PAINTING_TEXTURES = "textures/painting"; - - private final Multimap iconRegisters = HashMultimap.create(); - private final Map atlasRegistrars = new HashMap<>(); - - public SpriteRegistryHelper() { - this(FMLJavaModLoadingContext.get().getModEventBus()); - } - - public SpriteRegistryHelper(IEventBus eventBus) { - eventBus.addListener(this::onTextureStitchPre); - eventBus.addListener(this::onTextureStitchPost); - } - - /** - * Adds an IIconRegister for the given basePath. - * The base path should be that returned by {@link AtlasTexture#location()} - * Some known vanilla defaults are provided above. - * - * @param basePath The base path for the Atlas. - * @param iconRegister The IIconRegister. - */ - public void addIIconRegister(ResourceLocation basePath, IIconRegister iconRegister) { - iconRegisters.put(basePath, iconRegister); - } - - /** - * Adds an IIconRegister for the {@link #TEXTURES} Atlas. - * - * @param iconRegister The IIconRegister. - */ - public void addIIconRegister(IIconRegister iconRegister) { - addIIconRegister(TEXTURES, iconRegister); - } - - //######### INTERNAL - private AtlasRegistrarImpl getRegistrar(TextureAtlas atlas) { - AtlasRegistrarImpl registrar = atlasRegistrars.get(atlas.location()); - if (registrar == null) { - registrar = new AtlasRegistrarImpl(); - atlasRegistrars.put(atlas.location(), registrar); - } - return registrar; - } - - private void onTextureStitchPre(TextureStitchEvent.Pre event) { - TextureAtlas atlas = event.getAtlas(); - AtlasRegistrarImpl registrar = getRegistrar(atlas); - iconRegisters.get(atlas.location()).forEach(e -> e.registerIcons(registrar)); - registrar.processPre(event::addSprite); - } - - private void onTextureStitchPost(TextureStitchEvent.Post event) { - TextureAtlas atlas = event.getAtlas(); - AtlasRegistrarImpl registrar = getRegistrar(atlas); - registrar.processPost(atlas); - } - - private static final class AtlasRegistrarImpl implements AtlasRegistrar { - - private final Multimap> sprites = HashMultimap.create(); - private final List> postCallbacks = new ArrayList<>(); - - @Override - public void registerSprite(ResourceLocation loc, Consumer onReady) { - sprites.put(loc, onReady); - } - - @Override - public void postRegister(Consumer func) { - postCallbacks.add(func); - } - - private void processPre(Consumer register) { - sprites.keySet().forEach(register); - } - - private void processPost(TextureAtlas atlas) { - for (Map.Entry>> entry : sprites.asMap().entrySet()) { - TextureAtlasSprite sprite = atlas.getSprite(entry.getKey()); - entry.getValue().forEach(e -> e.accept(sprite)); - } - for (Consumer callback : postCallbacks) { - callback.accept(atlas); - } - } - } -} +//package codechicken.lib.texture; +// +//import com.google.common.collect.HashMultimap; +//import com.google.common.collect.Multimap; +//import net.minecraft.client.renderer.texture.TextureAtlas; +//import net.minecraft.client.renderer.texture.TextureAtlasSprite; +//import net.minecraft.resources.ResourceLocation; +//import net.minecraft.world.inventory.InventoryMenu; +//import net.minecraftforge.client.event.TextureStitchEvent; +//import net.minecraftforge.eventbus.api.IEventBus; +//import net.minecraftforge.eventbus.api.SubscribeEvent; +//import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +// +//import java.util.*; +//import java.util.function.Consumer; +// +///** +// * Utilities for persistent TextureAtlasSprite registration. +// *

+// * Created by covers1624 on 27/10/19. +// */ +//public class SpriteRegistryHelper { +// +// public static final ResourceLocation TEXTURES = InventoryMenu.BLOCK_ATLAS; +// // public static final ResourceLocation PARTICLE_TEXTURES = "textures/particle"; +// // public static final ResourceLocation MOB_EFFECT_TEXTURES = "textures/mob_effect"; +// // public static final ResourceLocation PAINTING_TEXTURES = "textures/painting"; +// +// private final Multimap iconRegisters = HashMultimap.create(); +// private final Map atlasRegistrars = new HashMap<>(); +// +// public SpriteRegistryHelper() { +// this(FMLJavaModLoadingContext.get().getModEventBus()); +// } +// +// public SpriteRegistryHelper(IEventBus eventBus) { +// eventBus.addListener(this::onTextureStitchPre); +// eventBus.addListener(this::onTextureStitchPost); +// } +// +// /** +// * Adds an IIconRegister for the given basePath. +// * The base path should be that returned by {@link AtlasTexture#location()} +// * Some known vanilla defaults are provided above. +// * +// * @param basePath The base path for the Atlas. +// * @param iconRegister The IIconRegister. +// */ +// public void addIIconRegister(ResourceLocation basePath, IIconRegister iconRegister) { +// iconRegisters.put(basePath, iconRegister); +// } +// +// /** +// * Adds an IIconRegister for the {@link #TEXTURES} Atlas. +// * +// * @param iconRegister The IIconRegister. +// */ +// public void addIIconRegister(IIconRegister iconRegister) { +// addIIconRegister(TEXTURES, iconRegister); +// } +// +// //######### INTERNAL +// private AtlasRegistrarImpl getRegistrar(TextureAtlas atlas) { +// AtlasRegistrarImpl registrar = atlasRegistrars.get(atlas.location()); +// if (registrar == null) { +// registrar = new AtlasRegistrarImpl(); +// atlasRegistrars.put(atlas.location(), registrar); +// } +// return registrar; +// } +// +// private void onTextureStitchPre(TextureStitchEvent.Pre event) { +// TextureAtlas atlas = event.getAtlas(); +// AtlasRegistrarImpl registrar = getRegistrar(atlas); +// iconRegisters.get(atlas.location()).forEach(e -> e.registerIcons(registrar)); +// registrar.processPre(event::addSprite); +// } +// +// private void onTextureStitchPost(TextureStitchEvent.Post event) { +// TextureAtlas atlas = event.getAtlas(); +// AtlasRegistrarImpl registrar = getRegistrar(atlas); +// registrar.processPost(atlas); +// } +// +// private static final class AtlasRegistrarImpl implements AtlasRegistrar { +// +// private final Multimap> sprites = HashMultimap.create(); +// private final List> postCallbacks = new ArrayList<>(); +// +// @Override +// public void registerSprite(ResourceLocation loc, Consumer onReady) { +// sprites.put(loc, onReady); +// } +// +// @Override +// public void postRegister(Consumer func) { +// postCallbacks.add(func); +// } +// +// private void processPre(Consumer register) { +// sprites.keySet().forEach(register); +// } +// +// private void processPost(TextureAtlas atlas) { +// for (Map.Entry>> entry : sprites.asMap().entrySet()) { +// TextureAtlasSprite sprite = atlas.getSprite(entry.getKey()); +// entry.getValue().forEach(e -> e.accept(sprite)); +// } +// for (Consumer callback : postCallbacks) { +// callback.accept(atlas); +// } +// } +// } +//} diff --git a/src/main/java/codechicken/lib/util/FontUtils.java b/src/main/java/codechicken/lib/util/FontUtils.java deleted file mode 100644 index 884b162e..00000000 --- a/src/main/java/codechicken/lib/util/FontUtils.java +++ /dev/null @@ -1,18 +0,0 @@ -package codechicken.lib.util; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; - -public class FontUtils { - - public static Font fontRenderer = Minecraft.getInstance().font; - - public static void drawCenteredString(PoseStack mStack, String s, int xCenter, int y, int colour) { - fontRenderer.drawShadow(mStack, s, xCenter - fontRenderer.width(s) / 2, y, colour); - } - - public static void drawRightString(PoseStack mStack, String s, int xRight, int y, int colour) { - fontRenderer.drawShadow(mStack, s, xRight - fontRenderer.width(s), y, colour); - } -} diff --git a/src/main/java/codechicken/lib/util/ItemUtils.java b/src/main/java/codechicken/lib/util/ItemUtils.java index 0627df76..ec8443fa 100644 --- a/src/main/java/codechicken/lib/util/ItemUtils.java +++ b/src/main/java/codechicken/lib/util/ItemUtils.java @@ -168,6 +168,6 @@ public static int compareItemStack(@Nonnull ItemStack stack1, @Nonnull ItemStack * @return whether the two items are the same in terms of damage and itemID. */ public static boolean areStacksSameType(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { - return !stack1.isEmpty() && !stack2.isEmpty() && (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.tagMatches(stack2, stack1)); + return !stack1.isEmpty() && !stack2.isEmpty() && (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameTags(stack2, stack1)); } } diff --git a/src/main/java/codechicken/lib/util/ServerUtils.java b/src/main/java/codechicken/lib/util/ServerUtils.java index 6d69cdb9..94c75e05 100644 --- a/src/main/java/codechicken/lib/util/ServerUtils.java +++ b/src/main/java/codechicken/lib/util/ServerUtils.java @@ -47,10 +47,6 @@ public static List getPlayers() { return getServer().getPlayerList().getPlayers(); } - public static boolean isPlayerLoadingChunk(ServerPlayer player, ChunkPos chunk) { - return player.getLevel().getChunkSource().chunkMap.getPlayers(chunk, false).stream().anyMatch(e -> e.getId() == player.getId()); - } - public static Path getSaveDirectory() { return getSaveDirectory(Level.OVERWORLD); } @@ -92,7 +88,7 @@ public static void openContainer(ServerPlayer player, MenuProvider containerProv } public static void openContainer(ServerPlayer player, MenuProvider containerProvider, Consumer packetConsumer) { - if (player.level.isClientSide()) { + if (player.level().isClientSide()) { return; } player.doCloseContainer(); diff --git a/src/main/java/codechicken/lib/util/TransformUtils.java b/src/main/java/codechicken/lib/util/TransformUtils.java index c5ff13e9..2fe126d3 100644 --- a/src/main/java/codechicken/lib/util/TransformUtils.java +++ b/src/main/java/codechicken/lib/util/TransformUtils.java @@ -1,14 +1,19 @@ package codechicken.lib.util; +import codechicken.lib.math.MathHelper; import codechicken.lib.model.PerspectiveModelState; import codechicken.lib.vec.Vector3; import com.google.common.collect.ImmutableMap; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.*; +import com.mojang.math.Transformation; import net.minecraft.client.renderer.block.model.ItemTransform; import net.minecraft.client.renderer.block.model.ItemTransforms; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; import net.minecraft.client.resources.model.ModelState; +import net.minecraft.world.item.ItemDisplayContext; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; import java.util.HashMap; import java.util.Map; @@ -32,57 +37,57 @@ public class TransformUtils { public static final PerspectiveModelState DEFAULT_HANDHELD_ROD; static { - Map map; + Map map; Transformation thirdPerson; Transformation firstPerson; //@formatter:off map = new HashMap<>(); thirdPerson = create(0F,2.5F, 0F,75F, 45F, 0F,0.375F ); - map.put(TransformType.GUI, create(0F, 0F, 0F,30F,225F, 0F,0.625F)); - map.put(TransformType.GROUND, create(0F, 3F, 0F, 0F, 0F, 0F, 0.25F)); - map.put(TransformType.FIXED, create(0F, 0F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, thirdPerson); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(0F, 0F, 0F, 0F, 45F, 0F, 0.4F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(0F, 0F, 0F, 0F, 225F, 0F, 0.4F)); + map.put(ItemDisplayContext.GUI, create(0F, 0F, 0F,30F,225F, 0F,0.625F)); + map.put(ItemDisplayContext.GROUND, create(0F, 3F, 0F, 0F, 0F, 0F, 0.25F)); + map.put(ItemDisplayContext.FIXED, create(0F, 0F, 0F, 0F, 0F, 0F, 0.5F)); + map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, thirdPerson); + map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); + map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(0F, 0F, 0F, 0F, 45F, 0F, 0.4F)); + map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(0F, 0F, 0F, 0F, 225F, 0F, 0.4F)); DEFAULT_BLOCK = new PerspectiveModelState(ImmutableMap.copyOf(map)); map = new HashMap<>(); thirdPerson = create( 0F, 3F, 1F, 0F, 0F, 0F, 0.55F); firstPerson = create(1.13F,3.2F,1.13F, 0F,-90F,25F, 0.68F); - map.put(TransformType.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.HEAD, create( 0F, 13F, 7F, 0F,180F, 0F, 1F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, thirdPerson); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, firstPerson); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, flipLeft(firstPerson)); + map.put(ItemDisplayContext.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); + map.put(ItemDisplayContext.HEAD, create( 0F, 13F, 7F, 0F,180F, 0F, 1F)); + map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, thirdPerson); + map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); + map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, firstPerson); + map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, flipLeft(firstPerson)); DEFAULT_ITEM = new PerspectiveModelState(ImmutableMap.copyOf(map)); map = new HashMap<>(); - map.put(TransformType.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.FIXED, create( 0F, 0F, 0F, 0F,180F, 0F, 1F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, create( 0F, 4F, 0.5F, 0F,-90F, 55,0.85F)); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, create( 0F, 4F, 0.5F, 0F, 90F,-55,0.85F)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F,-90F, 25,0.68F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25,0.68F)); + map.put(ItemDisplayContext.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); + map.put(ItemDisplayContext.FIXED, create( 0F, 0F, 0F, 0F,180F, 0F, 1F)); + map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, create( 0F, 4F, 0.5F, 0F,-90F, 55,0.85F)); + map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, create( 0F, 4F, 0.5F, 0F, 90F,-55,0.85F)); + map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F,-90F, 25,0.68F)); + map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25,0.68F)); DEFAULT_TOOL = new PerspectiveModelState(ImmutableMap.copyOf(map)); map = new HashMap<>(); - map.put(TransformType.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.FIXED, create( 0F, 0F, 0F, 0F, 180F, 0F, 1F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, create( -1F, -2F, 2.5F,-80F, 260F,-40F, 0.9F)); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, create( -1F, -2F, 2.5F,-80F,-280F, 40F, 0.9F)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F, -90F, 25F,0.68F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25F,0.68F)); + map.put(ItemDisplayContext.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); + map.put(ItemDisplayContext.FIXED, create( 0F, 0F, 0F, 0F, 180F, 0F, 1F)); + map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, create( -1F, -2F, 2.5F,-80F, 260F,-40F, 0.9F)); + map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, create( -1F, -2F, 2.5F,-80F,-280F, 40F, 0.9F)); + map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F, -90F, 25F,0.68F)); + map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25F,0.68F)); DEFAULT_BOW = new PerspectiveModelState(ImmutableMap.copyOf(map)); map = new HashMap<>(); - map.put(TransformType.GROUND, create(0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, create(0F, 4F,2.5F, 0F, 90F, 55F,0.85F)); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, create(0F, 4F,2.5F, 0F,-90F,-55F,0.85F)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(0F,1.6F,0.8F, 0F, 90F, 25F,0.68F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(0F,1.6F,0.8F, 0F,-90F,-25F,0.68F)); + map.put(ItemDisplayContext.GROUND, create(0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); + map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, create(0F, 4F,2.5F, 0F, 90F, 55F,0.85F)); + map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, create(0F, 4F,2.5F, 0F,-90F,-55F,0.85F)); + map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(0F,1.6F,0.8F, 0F, 90F, 25F,0.68F)); + map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(0F,1.6F,0.8F, 0F,-90F,-25F,0.68F)); DEFAULT_HANDHELD_ROD = new PerspectiveModelState(ImmutableMap.copyOf(map)); //@formatter:on } @@ -124,7 +129,12 @@ public static Transformation create(Vector3 transform, Vector3 rotation, Vector3 * @return The new TRSRTransformation. */ public static Transformation create(Vector3f transform, Vector3f rotation, Vector3f scale) { - return new Transformation(transform, new Quaternion(rotation.x(), rotation.y(), rotation.z(), true), scale, null); + return new Transformation( + transform, + new Quaternionf().rotationXYZ((float) (rotation.x() * MathHelper.torad), (float) (rotation.y() * MathHelper.torad), (float) (rotation.z() * MathHelper.torad)), + scale, + null + ); } public static Transformation create(ItemTransform transform) { @@ -152,9 +162,9 @@ public static Transformation flipLeft(Transformation transform) { public static ModelState stateFromItemTransforms(ItemTransforms itemTransforms) { if (itemTransforms == ItemTransforms.NO_TRANSFORMS) return IDENTITY; - ImmutableMap.Builder map = ImmutableMap.builder(); + ImmutableMap.Builder map = ImmutableMap.builder(); - for (TransformType value : TransformType.values()) { + for (ItemDisplayContext value : ItemDisplayContext.values()) { map.put(value, create(itemTransforms.getTransform(value))); } @@ -171,12 +181,12 @@ public static void applyLeftyFlip(PoseStack pStack) { Matrix4f tMat = pStack.last().pose(); Matrix3f nMat = pStack.last().normal(); - tMat.multiplyBackward(flipX.getMatrix()); - tMat.multiply(flipX.getMatrix()); - nMat.multiplyBackward(flipX.getNormalMatrix()); + tMat.mulLocal(flipX.getMatrix()); + tMat.mul(flipX.getMatrix()); + nMat.mulLocal(flipX.getNormalMatrix()); nMat.mul(flipX.getNormalMatrix()); - pStack.last().pose().multiply(tMat); + pStack.last().pose().mul(tMat); pStack.last().normal().mul(nMat); } } diff --git a/src/main/java/codechicken/lib/vec/Matrix4.java b/src/main/java/codechicken/lib/vec/Matrix4.java index bdf0550a..914312ef 100644 --- a/src/main/java/codechicken/lib/vec/Matrix4.java +++ b/src/main/java/codechicken/lib/vec/Matrix4.java @@ -1,9 +1,9 @@ package codechicken.lib.vec; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Matrix4f; -import com.mojang.math.Vector4f; import net.minecraft.core.Vec3i; +import org.joml.Matrix4f; +import org.joml.Vector4f; import java.math.BigDecimal; import java.math.MathContext; @@ -417,22 +417,22 @@ public Matrix4 set(PoseStack stack) { } public Matrix4 set(Matrix4f mat) { - m00 = mat.m00; - m01 = mat.m01; - m02 = mat.m02; - m03 = mat.m03; - m10 = mat.m10; - m11 = mat.m11; - m12 = mat.m12; - m13 = mat.m13; - m20 = mat.m20; - m21 = mat.m21; - m22 = mat.m22; - m23 = mat.m23; - m30 = mat.m30; - m31 = mat.m31; - m32 = mat.m32; - m33 = mat.m33; + m00 = mat.m00(); + m01 = mat.m10(); + m02 = mat.m20(); + m03 = mat.m30(); + m10 = mat.m01(); + m11 = mat.m11(); + m12 = mat.m21(); + m13 = mat.m31(); + m20 = mat.m02(); + m21 = mat.m12(); + m22 = mat.m22(); + m23 = mat.m32(); + m30 = mat.m03(); + m31 = mat.m13(); + m32 = mat.m23(); + m33 = mat.m33(); return this; } @@ -515,22 +515,23 @@ public void save(DoubleBuffer buff) { public Matrix4f toMatrix4f() { Matrix4f mat = new Matrix4f(); - mat.m00 = (float) m00; - mat.m01 = (float) m01; - mat.m02 = (float) m02; - mat.m03 = (float) m03; - mat.m10 = (float) m10; - mat.m11 = (float) m11; - mat.m12 = (float) m12; - mat.m13 = (float) m13; - mat.m20 = (float) m20; - mat.m21 = (float) m21; - mat.m22 = (float) m22; - mat.m23 = (float) m23; - mat.m30 = (float) m30; - mat.m31 = (float) m31; - mat.m32 = (float) m32; - mat.m33 = (float) m33; + mat.m00((float) m00); + mat.m01((float) m01); + mat.m02((float) m02); + mat.m03((float) m03); + mat.m10((float) m10); + mat.m11((float) m11); + mat.m12((float) m12); + mat.m13((float) m13); + mat.m20((float) m20); + mat.m21((float) m21); + mat.m22((float) m22); + mat.m23((float) m23); + mat.m30((float) m30); + mat.m31((float) m31); + mat.m32((float) m32); + mat.m33((float) m33); + mat.transpose(); return mat; } @@ -542,11 +543,11 @@ public static Vector3 gluProject(Vector3 obj, Matrix4 modelMatrix, Matrix4 projM if (o.w() == 0) { return Vector3.ZERO.copy(); } - o.setW((1.0F / o.w()) * 0.5F); + o.w = (1.0F / o.w()) * 0.5F; - o.setX(o.x() * o.w() + 0.5F); - o.setY(o.y() * o.w() + 0.5F); - o.setZ(o.z() * o.w() + 0.5F); + o.x = o.x() * o.w() + 0.5F; + o.y = o.y() * o.w() + 0.5F; + o.z = o.z() * o.w() + 0.5F; Vector3 winPos = new Vector3(); winPos.z = o.z(); diff --git a/src/main/java/codechicken/lib/vec/Quat.java b/src/main/java/codechicken/lib/vec/Quat.java index 2fda52e4..e0d43c86 100644 --- a/src/main/java/codechicken/lib/vec/Quat.java +++ b/src/main/java/codechicken/lib/vec/Quat.java @@ -1,7 +1,8 @@ package codechicken.lib.vec; import codechicken.lib.util.Copyable; -import com.mojang.math.Quaternion; +import org.joml.Quaterniond; +import org.joml.Quaternionf; import java.math.BigDecimal; import java.math.MathContext; @@ -28,11 +29,18 @@ public Quat(Quat quat) { s = quat.s; } - public Quat(Quaternion quat) { - x = quat.i(); - y = quat.j(); - z = quat.k(); - s = quat.r(); + public Quat(Quaternionf quat) { + x = quat.x; + y = quat.y; + z = quat.z; + s = quat.w; + } + + public Quat(Quaterniond quat) { + x = quat.x; + y = quat.y; + z = quat.z; + s = quat.w; } public Quat(double d, double d1, double d2, double d3) { @@ -104,8 +112,12 @@ public Quat rightMultiply(Quat quat) { return this; } - public Quaternion toQuaternion() { - return new Quaternion((float) x, (float) y, (float) z, (float) s); + public Quaternionf toQuaternionF() { + return new Quaternionf((float) x, (float) y, (float) z, (float) s); + } + + public Quaterniond toQuaternionD() { + return new Quaterniond(x, y, z, s); } public double mag() { diff --git a/src/main/java/codechicken/lib/vec/Vector3.java b/src/main/java/codechicken/lib/vec/Vector3.java index 755d7d97..ed433b14 100644 --- a/src/main/java/codechicken/lib/vec/Vector3.java +++ b/src/main/java/codechicken/lib/vec/Vector3.java @@ -2,8 +2,6 @@ import codechicken.lib.math.MathHelper; import codechicken.lib.util.Copyable; -import com.mojang.math.Vector3f; -import com.mojang.math.Vector4f; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; @@ -11,6 +9,8 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; +import org.joml.Vector4f; import java.math.BigDecimal; import java.math.MathContext; @@ -116,7 +116,7 @@ public Vec3 vec3() { } public BlockPos pos() { - return new BlockPos(x, y, z); + return new BlockPos(MathHelper.floor(x), MathHelper.floor(y), MathHelper.floor(z)); } public CompoundTag writeToNBT(CompoundTag tag) { diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 0eec72a9..3c3d8926 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -29,7 +29,7 @@ public net.minecraft.commands.arguments.ResourceKeyArgument m_233255_(Lcom/mojan public-f net.minecraft.world.level.block.Block f_49792_ # stateDefinition public-f net.minecraft.world.level.block.Block m_49966_()Lnet/minecraft/world/level/block/state/BlockState; # defaultBlockState -public net.minecraft.data.tags.TagsProvider m_206424_(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/TagsProvider$TagAppender; # tag +#public net.minecraft.data.tags.TagsProvider m_206424_(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/TagsProvider$TagAppender; # tag protected net.minecraft.client.renderer.ShaderInstance f_173331_ # uniforms protected net.minecraft.client.renderer.ShaderInstance m_173354_(Lcom/google/gson/JsonElement;)V # parseUniformNode diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index d5bc705c..3b8e4e40 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -24,7 +24,7 @@ It contains libraries for 3D math and transformations, model rendering, packets, [[dependencies.codechickenlib]] modId="minecraft" mandatory=true - versionRange="[1.19.2]" + versionRange="[1.20.1]" ordering="NONE" side="BOTH" diff --git a/src/test/java/codechicken/lib/test/TestResourceProvider.java b/src/test/java/codechicken/lib/test/TestResourceProvider.java index 3b6ceccf..7800e60f 100644 --- a/src/test/java/codechicken/lib/test/TestResourceProvider.java +++ b/src/test/java/codechicken/lib/test/TestResourceProvider.java @@ -22,6 +22,6 @@ private TestResourceProvider() { @Override public Optional getResource(ResourceLocation resource) { - return Optional.of(new Resource("test", () -> Objects.requireNonNull(OBJParserTests.class.getResourceAsStream("/" + resource.getPath()), "Resource " + resource + " doesnt exist."))); + return Optional.of(new Resource(null, () -> Objects.requireNonNull(OBJParserTests.class.getResourceAsStream("/" + resource.getPath()), "Resource " + resource + " doesnt exist."))); } } From b1d2ab2ca596c7069993704ccbd1485f2035ab5a Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 21:21:34 +1030 Subject: [PATCH 02/87] Fix AT's --- src/main/resources/META-INF/accesstransformer.cfg | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 3c3d8926..03a57caa 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -23,13 +23,13 @@ public-f net.minecraft.client.renderer.block.BlockRenderDispatcher f_110900_ # m public net.minecraft.client.renderer.block.BlockRenderDispatcher f_173397_ # blockEntityRenderer public-f net.minecraft.client.renderer.block.BlockRenderDispatcher f_110901_ # liquidBlockRenderer public-f net.minecraft.client.Minecraft f_91052_ # blockRenderer -public net.minecraft.world.item.ArmorMaterials f_40460_ # HEALTH_PER_SLOT +public net.minecraft.world.item.ArmorMaterials f_266010_ # HEALTH_FUNCTION_FOR_TYPE public net.minecraft.commands.arguments.ResourceKeyArgument m_233255_(Lcom/mojang/brigadier/context/CommandContext;Ljava/lang/String;Lnet/minecraft/resources/ResourceKey;Lcom/mojang/brigadier/exceptions/DynamicCommandExceptionType;)Lnet/minecraft/core/Holder; # getRegistryKeyType public-f net.minecraft.world.level.block.Block f_49792_ # stateDefinition public-f net.minecraft.world.level.block.Block m_49966_()Lnet/minecraft/world/level/block/state/BlockState; # defaultBlockState -#public net.minecraft.data.tags.TagsProvider m_206424_(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/TagsProvider$TagAppender; # tag +public net.minecraft.data.tags.IntrinsicHolderTagsProvider m_206424_(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/IntrinsicHolderTagsProvider$IntrinsicTagAppender; # tag protected net.minecraft.client.renderer.ShaderInstance f_173331_ # uniforms protected net.minecraft.client.renderer.ShaderInstance m_173354_(Lcom/google/gson/JsonElement;)V # parseUniformNode @@ -40,9 +40,9 @@ public-f com.mojang.blaze3d.shaders.Uniform m_5985_(F)V # set public-f com.mojang.blaze3d.shaders.Uniform m_7971_(FF)V # set public-f com.mojang.blaze3d.shaders.Uniform m_166700_(IF)V # set public-f com.mojang.blaze3d.shaders.Uniform m_5889_(FFF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142276_(Lcom/mojang/math/Vector3f;)V # set +public-f com.mojang.blaze3d.shaders.Uniform m_142276_(Lorg/joml/Vector3f;)V # set public-f com.mojang.blaze3d.shaders.Uniform m_5805_(FFFF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142558_(Lcom/mojang/math/Vector4f;)V # set +public-f com.mojang.blaze3d.shaders.Uniform m_142558_(Lorg/joml/Vector4f;)V # set public-f com.mojang.blaze3d.shaders.Uniform m_5808_(FFFF)V # setSafe public-f com.mojang.blaze3d.shaders.Uniform m_7401_(IIII)V # setSafe public-f com.mojang.blaze3d.shaders.Uniform m_142617_(I)V # set @@ -59,7 +59,7 @@ public-f com.mojang.blaze3d.shaders.Uniform m_142604_(FFFFFFFFFFFF)V # setMat3x4 public-f com.mojang.blaze3d.shaders.Uniform m_142004_(FFFFFFFF)V # setMat4x2 public-f com.mojang.blaze3d.shaders.Uniform m_142605_(FFFFFFFFFFFF)V # setMat4x3 public-f com.mojang.blaze3d.shaders.Uniform m_141978_(FFFFFFFFFFFFFFFF)V # setMat4x4 -public-f com.mojang.blaze3d.shaders.Uniform m_5679_(Lcom/mojang/math/Matrix4f;)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_200759_(Lcom/mojang/math/Matrix3f;)V # set +public-f com.mojang.blaze3d.shaders.Uniform m_5679_(Lorg/joml/Matrix4f;)V # set +public-f com.mojang.blaze3d.shaders.Uniform m_200759_(Lorg/joml/Matrix3f;)V # set public com.mojang.blaze3d.shaders.Program (Lcom/mojang/blaze3d/shaders/Program$Type;ILjava/lang/String;)V # public com.mojang.blaze3d.shaders.Program$Type m_85571_()I # getGlType From d4697eb98cceab33a36a4579c2c62a84d5ef5d65 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 21:22:45 +1030 Subject: [PATCH 03/87] Generate Javadoc jars, pgp key signing. --- build.gradle | 99 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 57 insertions(+), 42 deletions(-) diff --git a/build.gradle b/build.gradle index 0a359bd8..77b639f8 100644 --- a/build.gradle +++ b/build.gradle @@ -1,13 +1,20 @@ plugins { id 'java' id 'maven-publish' + id 'signing' id 'com.github.johnrengelman.shadow' version '7.1.2' - id "net.covers1624.signing" version '1.1.4' + id "net.covers1624.signing" version '1.1.4' apply false id 'net.neoforged.gradle' version '[6.0.18,6.2)' id 'org.spongepowered.mixin' version '0.7.+' } -java.toolchain.languageVersion = JavaLanguageVersion.of(17) +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } + withSourcesJar() + withJavadocJar() +} group = 'codechicken' archivesBaseName = 'CodeChickenLib' @@ -20,25 +27,6 @@ file('build.properties').withReader { project.ext.config = new ConfigSlurper().parse prop } -def signProps = [:] -if (System.getenv("KEY_STORE")) { - println "Using Env variables for jar signing." - signProps['keyStore'] = System.getenv("KEY_STORE") - file(System.getenv("KEY_STORE_PROPS")).withReader { - def props = new Properties() - props.load(it) - signProps.putAll(props) - } -} else if (project.hasProperty('keyStore')) { - println "Using Project properties for jar signing." - signProps['keyStore'] = project.getProperty('keyStore') - signProps['storePass'] = project.getProperty('keyStorePass') - signProps['alias'] = project.getProperty('keyStoreAlias') - signProps['keyPass'] = project.getProperty('keyStoreKeyPass') -} else { - println 'No signing secrets found, build will not be signed.' -} - config.mod_version = "${config.mod_version}." + (System.getenv("BUILD_NUMBER") ?: "1") version = "${config.mc_version}-${config.mod_version}" println "Starting build of ${archivesBaseName}, Version: ${config.mod_version}" @@ -109,20 +97,6 @@ reobf { jar { enabled = false } // Disable jar. } -signing { - if (!signProps.isEmpty()) { - jars { - sign shadowJar - after 'reobfShadowJar' - - keyStore = signProps.keyStore - alias = signProps.alias - storePass = signProps.storePass - keyPass = signProps.keyPass - } - } -} - def commonManifest = { attributes 'Specification-Title': archivesBaseName attributes 'Specification-Vendor': 'covers1624' @@ -144,11 +118,34 @@ shadowJar { from file("LICENSE") } -task srcJar(type: Jar) { - build.dependsOn it - from sourceSets.main.allSource - archiveClassifier = 'sources' - from file("LICENSE") +def jarArchive = shadowJar +if (System.getenv("KEY_STORE") || project.hasProperty('keyStore')) { + jarArchive = tasks.register("signShadowJar", net.covers1624.jarsign.jar.SignJarTask) { + dependsOn("shadowJar") + dependsOn("reobfShadowJar") + + input = shadowJar.archiveFile.get().asFile + output = shadowJar.archiveFile.get().asFile + if (System.getenv("KEY_STORE")) { + keyStore = System.getenv("KEY_STORE") + file(System.getenv("KEY_STORE_PROPS")).withReader { + def props = new Properties() + props.load(it) + alias = props['alias'] + storePass = props['storePass'] + keyPass = props['keyPass'] + } + } else { + keyStore = project.getProperty('keyStore') + alias = project.getProperty('keyStoreAlias') + storePass = project.getProperty('keyStorePass') + keyPass = project.getProperty('keyStoreKeyPass') + } + } +} + +javadoc { + options.addBooleanOption("Xdoclint:none", true) } publishing { @@ -168,8 +165,9 @@ publishing { groupId project.group artifactId project.archivesBaseName version project.version - artifact shadowJar - artifact srcJar + artifact jarArchive + artifact sourcesJar + artifact javadocJar pom { name = archivesBaseName @@ -208,6 +206,23 @@ publishing { } } +signing { + if (System.getenv('GPG_PRIVATE_KEY')) { + useInMemoryPgpKeys( + new File(System.getenv('GPG_PRIVATE_KEY')).text, + System.getenv('GPG_PRIVATE_KEY_PASS') + ) + } else if (project.hasProperty('gpgPrivateKey')) { + useInMemoryPgpKeys( + new File(project.getProperty('gpgPrivateKey')).text, + project.getProperty('gpgPrivateKeyPass') + ) + } else { + return + } + sign publishing.publications.CodeChickenLib +} + /** * Polls the 'compile' configuration for a dependency with the given module name * and resolves, and returns its version. E.g: '1.2.+' will resolve to '1.2.3.4' From 9f6ad35bae06f92e36dae1af30502cb48d484ea1 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 21:27:48 +1030 Subject: [PATCH 04/87] Buildscript and unessesary files cleanup. --- .gitignore | 4 - .../codechicken/lib/render/QBImporter.java | 808 ------------------ .../codechicken/lib/tool/LibDownloader.java | 111 --- .../lib/tool/MCStripTransformer.java | 49 -- archive/codechicken/lib/tool/Main.java | 14 - .../lib/tool/StripClassLoader.java | 53 -- archive/codechicken/lib/tool/ToolMain.java | 48 -- .../lib/tool/module/JOptModule.java | 42 - .../lib/tool/module/ModuleQBConverter.java | 82 -- build.gradle | 62 +- build.properties | 3 - gradle.properties | 4 + 12 files changed, 17 insertions(+), 1263 deletions(-) delete mode 100644 archive/codechicken/lib/render/QBImporter.java delete mode 100644 archive/codechicken/lib/tool/LibDownloader.java delete mode 100644 archive/codechicken/lib/tool/MCStripTransformer.java delete mode 100644 archive/codechicken/lib/tool/Main.java delete mode 100644 archive/codechicken/lib/tool/StripClassLoader.java delete mode 100644 archive/codechicken/lib/tool/ToolMain.java delete mode 100644 archive/codechicken/lib/tool/module/JOptModule.java delete mode 100644 archive/codechicken/lib/tool/module/ModuleQBConverter.java delete mode 100644 build.properties diff --git a/.gitignore b/.gitignore index 820dad1e..be21d4f2 100644 --- a/.gitignore +++ b/.gitignore @@ -8,14 +8,12 @@ !gradlew !gradlew.bat !build.gradle -!build.properties !gradle.properties !settings.gradle # Other Files. !LICENSE !README.md -!.travis.yml # Include git important files !.gitmodules @@ -24,5 +22,3 @@ # Include Important Folders !src/ -!libs/ -!archive diff --git a/archive/codechicken/lib/render/QBImporter.java b/archive/codechicken/lib/render/QBImporter.java deleted file mode 100644 index 03724b64..00000000 --- a/archive/codechicken/lib/render/QBImporter.java +++ /dev/null @@ -1,808 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.texture.TextureDataHolder; -import codechicken.lib.texture.TextureUtils; -import codechicken.lib.vec.*; -import codechicken.lib.vec.uv.UV; -import codechicken.lib.vec.uv.UVScale; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.ResourceLocation; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.*; -import java.util.*; - -//TODO, Is this needed anymore? -public class QBImporter { - - private static class ImagePackNode { - - Rectangle4i rect; - ImagePackNode child1; - ImagePackNode child2; - QBImage packed; - - public ImagePackNode(int x, int y, int w, int h) { - rect = new Rectangle4i(x, y, w, h); - } - - public boolean pack(QBImage img) { - if (child1 != null) { - return child1.pack(img) || child2.pack(img); - } - - if (packed != null) { - return false; - } - - int fit = getFit(img.width(), img.height()); - if (fit == 0) { - return false; - } - - if ((fit & 2) != 0) {//exact fit - packed = img; - img.packSlot = rect; - img.packT = new ImageTransform((fit & 1) << 2); - return true; - } - - int w = (fit & 1) == 0 ? img.width() : img.height(); - int h = (fit & 1) == 0 ? img.height() : img.width(); - - if (rect.w - w > rect.h - h) {//create split with biggest leftover space - child1 = new ImagePackNode(rect.x, rect.y, w, rect.h); - child2 = new ImagePackNode(rect.x + w, rect.y, rect.w - w, rect.h); - } else { - child1 = new ImagePackNode(rect.x, rect.y, rect.w, h); - child2 = new ImagePackNode(rect.x, rect.y + h, rect.w, rect.h - h); - } - return child1.pack(img); - } - - private int getFit(int w, int h) { - if (w == rect.w && h == rect.h) { - return 2; - } - if (w == rect.h && h == rect.w) { - return 3; - } - if (rect.w >= w && rect.h >= h) { - return 4; - } - if (rect.w >= h && rect.h >= w) { - return 5; - } - - return 0; - } - - private static void nextSize(Rectangle4i rect, boolean square) { - if (square) { - rect.w <<= 1; - rect.h <<= 1; - } else { - if (rect.w == rect.h) { - rect.w *= 2; - } else { - rect.h *= 2; - } - } - } - - public static ImagePackNode pack(List images, boolean square) { - Collections.sort(images); - - int area = 0; - for (QBImage img : images) { - area += img.area(); - } - - ImagePackNode node = new ImagePackNode(0, 0, 2, 2); - while (node.rect.area() < area) { - nextSize(node.rect, square); - } - - while (true) { - boolean packed = true; - for (QBImage img : images) { - if (!node.pack(img)) { - packed = false; - break; - } - } - - if (packed) { - return node; - } - - node.child1 = node.child2 = null; - nextSize(node.rect, square); - } - } - - public BufferedImage toImage() { - BufferedImage img = new BufferedImage(rect.w, rect.h, BufferedImage.TYPE_INT_ARGB); - write(img); - return img; - } - - private void write(BufferedImage img) { - if (child1 != null) { - child1.write(img); - child2.write(img); - } else if (packed != null) { - ImageTransform t = packed.packT; - for (int u = 0; u < rect.w; u++) { - for (int v = 0; v < rect.h; v++) { - int rgba = t.access(packed, u, v); - img.setRGB(u + rect.x, v + rect.y, rgba >>> 8 | rgba << 24); - } - } - } - } - } - - private static class ImageTransform { - - int transform; - - public ImageTransform(int i) { - transform = i; - } - - public ImageTransform() { - this(0); - } - - public boolean transpose() { - return (transform & 4) != 0; - } - - public boolean flipU() { - return (transform & 1) != 0; - } - - public boolean flipV() { - return (transform & 2) != 0; - } - - public int access(QBImage img, int u, int v) { - if (transpose()) { - int tmp = u; - u = v; - v = tmp; - } - if (flipU()) { - u = img.width() - 1 - u; - } - if (flipV()) { - v = img.height() - 1 - v; - } - - return img.data[u][v]; - } - - public UV transform(UV uv) { - if (transpose()) { - double tmp = uv.u; - uv.u = uv.v; - uv.v = tmp; - } - if (flipU()) { - uv.u = 1 - uv.u; - } - if (flipV()) { - uv.v = 1 - uv.v; - } - - return uv; - } - } - - public static class QBImage implements Comparable { - - int[][] data; - ImageTransform packT; - Rectangle4i packSlot; - - public int width() { - return data.length; - } - - public int height() { - return data[0].length; - } - - public int area() { - return width() * height(); - } - - @Override - public int compareTo(QBImage o) { - int a = area(); - int b = o.area(); - return a > b ? -1 : a == b ? 0 : 1; - } - - public ImageTransform transformTo(QBImage img) { - if (width() == img.width() && height() == img.height()) { - for (int i = 0; i < 4; i++) { - ImageTransform t = new ImageTransform(i); - if (equals(img, t)) { - return t; - } - } - } - if (width() == img.height() && height() == img.width()) { - for (int i = 4; i < 8; i++) { - ImageTransform t = new ImageTransform(i); - if (equals(img, t)) { - return t; - } - } - } - return null; - } - - public boolean equals(QBImage img, ImageTransform t) { - for (int u = 0; u < img.width(); u++) { - for (int v = 0; v < img.height(); v++) { - if (t.access(this, u, v) != img.data[u][v]) { - return false; - } - } - } - - return true; - } - - public void transform(UV uv) { - packT.transform(uv); - uv.u *= packSlot.w; - uv.v *= packSlot.h; - uv.u += packSlot.x; - uv.v += packSlot.y; - } - } - - private static final int[][] vertOrder = new int[][] {//clockwise because MC is left handed - { 3, 0 }, { 1, 0 }, { 1, 2 }, { 3, 2 } }; - - public static class QBQuad { - - public Vertex5[] verts = new Vertex5[4]; - public QBImage image = new QBImage(); - public ImageTransform t = new ImageTransform(); - public int side; - - public QBQuad(int side) { - this.side = side; - } - - public void applyImageT() { - for (Vertex5 vert : verts) { - t.transform(vert.uv); - image.transform(vert.uv); - } - } - - public static QBQuad restore(Rectangle4i flat, int side, double d, QBImage img) { - QBQuad quad = new QBQuad(side); - quad.image = img; - - Transformation t = new Scale(-1, 1, -1).with(Rotation.sideOrientation(side, 0)).with(new Translation(new Vector3().setSide(side, d))); - quad.verts[0] = new Vertex5(flat.x, 0, flat.y, 0, 0); - quad.verts[1] = new Vertex5(flat.x + flat.w, 0, flat.y, 1, 0); - quad.verts[2] = new Vertex5(flat.x + flat.w, 0, flat.y + flat.h, 1, 1); - quad.verts[3] = new Vertex5(flat.x, 0, flat.y + flat.h, 0, 1); - for (Vertex5 vert : quad.verts) { - vert.apply(t); - } - - return quad; - } - - public Rectangle4i flatten() { - Transformation t = Rotation.sideOrientation(side, 0).inverse().with(new Scale(-1, 0, -1)); - Vector3 vmin = verts[0].vec.copy().apply(t); - Vector3 vmax = verts[2].vec.copy().apply(t); - return new Rectangle4i((int) vmin.x, (int) vmin.z, (int) (vmax.x - vmin.x), (int) (vmax.z - vmin.z)); - } - } - - public static class QBCuboid { - - public QBMatrix mat; - public CuboidCoord c; - public int sides; - - public QBCuboid(QBMatrix mat, CuboidCoord c) { - this.mat = mat; - this.c = c; - sides = 0; - } - - public static boolean intersects(QBCuboid a, QBCuboid b) { - CuboidCoord c = a.c; - CuboidCoord d = b.c; - return c.min.x <= d.max.x && d.min.x <= c.max.x && c.min.y <= d.max.y && d.min.y <= c.max.y && c.min.z <= d.max.z && d.min.z <= c.max.z; - } - - public static void clip(QBCuboid a, QBCuboid b) { - if (intersects(a, b)) { - a.clip(b); - b.clip(a); - } - } - - public void clip(QBCuboid o) { - CuboidCoord d = o.c; - for (int a = 0; a < 6; a += 2) { - int a1 = (a + 2) % 6; - int a2 = (a + 4) % 6; - if (c.getSide(a1 + 1) <= d.getSide(a1 + 1) && c.getSide(a1) >= d.getSide(a1) && c.getSide(a2 + 1) <= d.getSide(a2 + 1) && c.getSide(a2) >= d.getSide(a2)) { - - if (c.getSide(a) <= d.getSide(a + 1) && c.getSide(a) >= d.getSide(a)) { - c.setSide(a, d.getSide(a + 1) + 1); - sides |= 1 << a; - } - if (c.getSide(a + 1) >= d.getSide(a) && c.getSide(a + 1) <= d.getSide(a + 1)) { - c.setSide(a + 1, d.getSide(a) - 1); - sides |= 2 << a; - } - } - } - } - - public void extractQuads(List quads) { - Cuboid6 box = c.bounds(); - for (int s = 0; s < 6; s++) { - if ((sides & 1 << s) == 0) { - quads.add(extractQuad(s, box)); - } - } - } - - private QBQuad extractQuad(int side, Cuboid6 box) { - double[] da = new double[3]; - da[side >> 1] = box.getSide(side); - - QBQuad quad = new QBQuad(side); - for (int i = 0; i < 4; i++) { - int rU = vertOrder[i][0]; - int rV = vertOrder[i][1]; - int sideU = Rotation.rotateSide(side, rU); - int sideV = Rotation.rotateSide(side, rV); - da[sideU >> 1] = box.getSide(sideU); - da[sideV >> 1] = box.getSide(sideV); - quad.verts[i] = new Vertex5(Vector3.fromAxes(da), (3 - rU) / 2, rV / 2); - } - - int sideU = Rotation.rotateSide(side, 1); - int sideV = Rotation.rotateSide(side, 2); - quad.image.data = new int[c.size(sideU)][c.size(sideV)]; - QBImage image = quad.image; - - int[] ia = new int[3]; - ia[side >> 1] = c.getSide(side); - ia[sideU >> 1] = c.getSide(sideU ^ 1); - ia[sideV >> 1] = c.getSide(sideV ^ 1); - BlockCoord b = BlockCoord.fromAxes(ia); - BlockCoord bU = BlockCoord.sideOffsets[sideU]; - BlockCoord bV = BlockCoord.sideOffsets[sideV]; - for (int u = 0; u < image.width(); u++) { - for (int v = 0; v < image.height(); v++) { - image.data[u][v] = mat.matrix[b.x + bU.x * u + bV.x * v][b.y + bU.y * u + bV.y * v][b.z + bU.z * u + bV.z * v]; - } - } - - return quad; - } - } - - public static class QBMatrix { - - public String name; - public BlockCoord pos; - public BlockCoord size; - public int[][][] matrix; - - public void readMatrix(DataInputStream din, boolean compressed) throws IOException { - if (compressed) { - int z = 0; - while (z < size.z) { - int index = 0; - - while (true) { - int data = din.readInt(); - - if (data == NEXTSLICEFLAG) { - break; - } - - if (data == CODEFLAG) { - int count = readTni(din); - data = din.readInt(); - - for (int j = 0; j < count; j++, index++) { - matrix[index % size.x][index / size.x][z] = data; - } - } else { - matrix[index % size.x][index / size.x][z] = data; - index++; - } - } - z++; - } - } else { - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - for (int x = 0; x < size.x; x++) { - matrix[x][y][z] = din.readInt(); - } - } - } - } - } - - public void convertBGRAtoRGBA() { - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - for (int x = 0; x < size.x; x++) { - int i = matrix[x][y][z]; - matrix[x][y][z] = Integer.reverseBytes(i >>> 8) | i & 0xFF; - } - } - } - } - - private boolean voxelFull(boolean[][][] solid, CuboidCoord c) { - for (BlockCoord b : c) { - if (matrix[b.x][b.y][b.z] == 0) { - return false; - } - } - for (BlockCoord b : c) { - solid[b.x][b.y][b.z] = false; - } - return true; - } - - private QBCuboid expand(boolean[][][] solid, BlockCoord b) { - CuboidCoord c = new CuboidCoord(b); - solid[b.x][b.y][b.z] = false; - - for (int s = 0; s < 6; s++) { - CuboidCoord slice = c.copy(); - slice.expand(s ^ 1, -(slice.size(s) - 1)); - slice.expand(s, 1); - - while (slice.getSide(s) >= 0 && slice.getSide(s) < size.getSide(s)) { - if (!voxelFull(solid, slice)) { - break; - } - slice.expand(s ^ 1, -1); - slice.expand(s, 1); - c.expand(s, 1); - } - } - return new QBCuboid(this, c); - } - - public List rectangulate() { - List list = new ArrayList<>(); - boolean[][][] solid = new boolean[size.x][size.y][size.z]; - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - for (int x = 0; x < size.x; x++) { - solid[x][y][z] = matrix[x][y][z] != 0; - } - } - } - - for (int x = 0; x < size.x; x++) { - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - if (solid[x][y][z]) { - list.add(expand(solid, new BlockCoord(x, y, z))); - } - } - } - } - - for (int i = 0; i < list.size(); i++) { - for (int j = i + 1; j < list.size(); j++) { - QBCuboid.clip(list.get(i), list.get(j)); - } - } - - return list; - } - - public List extractQuads(boolean texturePlanes) { - List quads = new LinkedList<>(); - for (QBCuboid c : rectangulate()) { - c.extractQuads(quads); - } - - if (texturePlanes) { - optimisePlanes(quads); - } - - return quads; - } - - private void optimisePlanes(List quads) { - Multimap map = HashMultimap.create(); - for (QBQuad quad : quads) { - map.put(quad.side | ((int) quad.verts[0].vec.getSide(quad.side)) << 3, quad); - } - - quads.clear(); - for (Integer key : map.keySet()) { - Collection plane = map.get(key); - if (plane.size() == 1) { - quads.add(plane.iterator().next()); - continue; - } - - int side = key & 7; - Rectangle4i rect = null; - for (QBQuad q : plane) { - if (rect == null) { - rect = q.flatten(); - } else { - rect.include(q.flatten()); - } - } - - QBImage img = new QBImage(); - img.data = new int[rect.w][rect.h]; - for (QBQuad q : plane) { - QBImage from = q.image; - Rectangle4i r = q.flatten(); - int du = r.x - rect.x; - int dv = r.y - rect.y; - for (int u = 0; u < from.width(); u++) { - for (int v = 0; v < from.height(); v++) { - img.data[du + u][dv + v] = from.data[u][v]; - } - } - } - - quads.add(QBQuad.restore(rect, side, key >> 3, img)); - } - } - - public CCModel buildModel(List quads, BufferedImage img, boolean scaleMC) { - CCModel m = CCModel.quadModel(quads.size() * 4); - int i = 0; - for (QBQuad quad : quads) { - quad.applyImageT(); - m.verts[i++] = quad.verts[0]; - m.verts[i++] = quad.verts[1]; - m.verts[i++] = quad.verts[2]; - m.verts[i++] = quad.verts[3]; - } - m.apply(new UVScale(1D / img.getWidth(), 1D / img.getHeight())); - m.apply(new Translation(pos.x, pos.y, pos.z)); - if (scaleMC) { - m.apply(new Scale(1 / 16D)); - } - m.computeNormals(); - return m; - } - - private static void addImages(List quads, List images) { - for (QBQuad q : quads) { - QBImage img = q.image; - boolean matched = false; - for (QBImage img2 : images) { - ImageTransform t = img.transformTo(img2); - if (t != null) { - q.t = t; - q.image = img2; - matched = true; - break; - } - } - if (!matched) { - images.add(img); - } - } - } - } - - public static final int TEXTUREPLANES = 1; - public static final int SQUARETEXTURE = 2; - public static final int MERGETEXTURES = 4; - public static final int SCALEMC = 8; - - public static class QBModel { - - public QBMatrix[] matrices; - public boolean rightHanded; - - public RasterisedModel toRasterisedModel(int flags) { - List qbImages = new ArrayList<>(); - List> modelQuads = new ArrayList<>(); - List images = new ArrayList<>(); - - boolean texturePlanes = (flags & TEXTUREPLANES) != 0; - boolean squareTextures = (flags & SQUARETEXTURE) != 0; - boolean mergeTextures = (flags & MERGETEXTURES) != 0; - boolean scaleMC = (flags & SCALEMC) != 0; - - for (QBMatrix mat : matrices) { - List quads = mat.extractQuads(texturePlanes); - modelQuads.add(quads); - QBMatrix.addImages(quads, qbImages); - if (!mergeTextures) { - images.add(ImagePackNode.pack(qbImages, squareTextures).toImage()); - qbImages.clear(); - } - } - - if (mergeTextures) { - images.add(ImagePackNode.pack(qbImages, squareTextures).toImage()); - } - - RasterisedModel m = new RasterisedModel(images); - for (int i = 0; i < matrices.length; i++) { - QBMatrix mat = matrices[i]; - BufferedImage img = images.get(mergeTextures ? 0 : i); - m.add(mat.name, mat.buildModel(modelQuads.get(i), img, scaleMC)); - } - return m; - } - } - - public static class RasterisedModel { - - private class Holder { - - CCModel m; - int img; - - public Holder(CCModel m, int img) { - this.m = m; - this.img = img; - } - } - - private Map map = new HashMap<>(); - private List images; - - public RasterisedModel(List images) { - this.images = images; - } - - public void add(String name, CCModel m) { - map.put(name, new Holder(m, Math.min(map.size(), images.size() - 1))); - } - - public CCModel getModel(String key) { - return map.get(key).m; - } - - public TextureAtlasSprite getIcon(String key, TextureMap textureMap) { - int img = map.get(key).img; - String iconName = "QBModel" + hashCode() + "_img"; - TextureAtlasSprite icon = textureMap.getTextureExtry(iconName); - if (icon != null) { - return icon; - } - - return TextureUtils.getTextureSpecial(textureMap, iconName).addTexture(new TextureDataHolder(images.get(img))); - } - - private void exportImg(BufferedImage img, File imgFile) throws IOException { - if (!imgFile.exists()) { - imgFile.createNewFile(); - } - ImageIO.write(img, "PNG", imgFile); - } - - public void export(File objFile, File imgDir) { - try { - if (!objFile.exists()) { - objFile.createNewFile(); - } - if (!imgDir.exists()) { - imgDir.mkdirs(); - } - - Map modelMap = new HashMap<>(); - for (Map.Entry e : map.entrySet()) { - modelMap.put(e.getKey(), e.getValue().m); - } - - PrintWriter p = new PrintWriter(objFile); - CCOBJParser.exportObj(modelMap, p); - p.close(); - - if (images.size() < map.size()) { - exportImg(images.get(0), new File(imgDir, objFile.getName().replaceAll("(.+)\\..+", "$1.png"))); - } else { - for (Map.Entry e : map.entrySet()) { - exportImg(images.get(e.getValue().img), new File(imgDir, e.getKey() + ".png")); - } - } - - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private static String readAsciiString(DataInputStream din) throws IOException { - byte[] bytes = new byte[din.readByte() & 0xFF]; - din.readFully(bytes); - return new String(bytes, "US-ASCII"); - } - - private static int readTni(DataInputStream din) throws IOException { - return Integer.reverseBytes(din.readInt()); - } - - private static final int CODEFLAG = Integer.reverseBytes(2); - private static final int NEXTSLICEFLAG = Integer.reverseBytes(6); - - public static QBModel loadQB(InputStream input) throws IOException { - DataInputStream din = new DataInputStream(input); - - QBModel m = new QBModel(); - int version = din.readInt(); - int colorFormat = din.readInt(); - m.rightHanded = din.readInt() != 0; - boolean compressed = din.readInt() != 0; - boolean visEncoded = din.readInt() != 0; - - if (visEncoded) { - throw new IllegalArgumentException("Encoded Visiblity States not supported"); - } - - m.matrices = new QBMatrix[readTni(din)]; - for (int i = 0; i < m.matrices.length; i++) { - QBMatrix mat = new QBMatrix(); - m.matrices[i] = mat; - mat.name = readAsciiString(din); - mat.size = new BlockCoord(readTni(din), readTni(din), readTni(din)); - mat.pos = new BlockCoord(readTni(din), readTni(din), readTni(din)); - mat.matrix = new int[mat.size.x][mat.size.y][mat.size.z]; - mat.readMatrix(din, compressed); - if (colorFormat == 1) { - mat.convertBGRAtoRGBA(); - } - } - - return m; - } - - public static QBModel loadQB(ResourceLocation res) { - try { - return loadQB(Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream()); - } catch (Exception e) { - throw new RuntimeException("failed to load model: " + res, e); - } - } - - public static QBModel loadQB(File file) { - try { - FileInputStream fin = new FileInputStream(file); - try { - return loadQB(fin); - } finally { - fin.close(); - } - } catch (Exception e) { - throw new RuntimeException("failed to load model: " + file.getPath(), e); - } - } -} diff --git a/archive/codechicken/lib/tool/LibDownloader.java b/archive/codechicken/lib/tool/LibDownloader.java deleted file mode 100644 index 7840cfb3..00000000 --- a/archive/codechicken/lib/tool/LibDownloader.java +++ /dev/null @@ -1,111 +0,0 @@ -package codechicken.lib.tool; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLConnection; -import java.nio.ByteBuffer; -import java.util.LinkedList; -import java.util.List; - -public class LibDownloader { - - private static String[] libs = new String[] { "org/ow2/asm/asm-debug-all/5.0.3/asm-debug-all-5.0.3.jar", "com/google/guava/guava/14.0/guava-14.0.jar", "net/sf/jopt-simple/jopt-simple/4.5/jopt-simple-4.5.jar", "org/apache/logging/log4j/log4j-core/2.0-beta9/log4j-core-2.0-beta9.jar", "org/apache/logging/log4j/log4j-api/2.0-beta9/log4j-api-2.0-beta9.jar" }; - private static File libDir = new File("lib"); - - private static ByteBuffer downloadBuffer = ByteBuffer.allocateDirect(1 << 23); - - public static void load() { - if (!libDir.exists()) { - libDir.mkdir(); - } - if (!libDir.isDirectory()) { - throw new RuntimeException("/lib is not a directory"); - } - - List missing = checkExists(); - for (String lib : missing) { - download(lib); - } - addPaths(libs); - } - - private static void addPaths(String[] libs) { - try { - URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader(); - Method m_addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); - m_addURL.setAccessible(true); - for (String lib : libs) { - m_addURL.invoke(cl, new File(libDir, fileName(lib)).toURI().toURL()); - } - } catch (Exception e) { - throw new RuntimeException("Failed to add libraries to classpath", e); - } - } - - private static void download(String lib) { - File libFile = new File(libDir, fileName(lib)); - try { - URL libDownload = new URL("http://repo1.maven.org/maven2/" + lib); - URLConnection connection = libDownload.openConnection(); - connection.setConnectTimeout(5000); - connection.setReadTimeout(5000); - connection.setRequestProperty("User-Agent", "CodeChickenLib Downloader"); - int sizeGuess = connection.getContentLength(); - download(connection.getInputStream(), sizeGuess, libFile); - } catch (Exception e) { - libFile.delete(); - throw new RuntimeException("A download error occured", e); - } - } - - private static void download(InputStream is, int sizeGuess, File target) throws Exception { - String name = target.getName(); - if (sizeGuess > downloadBuffer.capacity()) { - throw new Exception(String.format("The file %s is too large to be downloaded", name)); - } - - downloadBuffer.clear(); - - int bytesRead, fullLength = 0; - - System.out.format("Downloading lib %s", name); - byte[] smallBuffer = new byte[1024]; - while ((bytesRead = is.read(smallBuffer)) >= 0) { - downloadBuffer.put(smallBuffer, 0, bytesRead); - fullLength += bytesRead; - System.out.format("\rDownloading lib %s %d%%", name, fullLength * 100 / sizeGuess); - } - System.out.format("\rDownloaded lib %s \n", name); - is.close(); - downloadBuffer.limit(fullLength); - - if (!target.exists()) { - target.createNewFile(); - } - - downloadBuffer.position(0); - FileOutputStream fos = new FileOutputStream(target); - fos.getChannel().write(downloadBuffer); - fos.close(); - } - - private static String fileName(String lib) { - return lib.replaceAll(".+/", ""); - } - - private static List checkExists() { - LinkedList list = new LinkedList<>(); - for (String lib : libs) { - File file = new File(libDir, fileName(lib)); - if (!file.exists()) { - list.add(lib); - } - } - return list; - } - -} diff --git a/archive/codechicken/lib/tool/MCStripTransformer.java b/archive/codechicken/lib/tool/MCStripTransformer.java deleted file mode 100644 index d9ad82df..00000000 --- a/archive/codechicken/lib/tool/MCStripTransformer.java +++ /dev/null @@ -1,49 +0,0 @@ -package codechicken.lib.tool; - -import codechicken.lib.asm.ASMHelper; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.commons.Remapper; -import org.objectweb.asm.commons.RemappingMethodAdapter; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; - -import java.util.Iterator; - -public class MCStripTransformer { - - public static class ReferenceDetector extends Remapper { - - boolean found = false; - - @Override - public String map(String typeName) { - if (typeName.startsWith("net/minecraft") || !typeName.contains("/")) { - found = true; - } - return typeName; - } - } - - public static byte[] transform(byte[] bytes) { - ClassNode cnode = ASMHelper.createClassNode(bytes, ClassReader.EXPAND_FRAMES); - - boolean changed = false; - Iterator it = cnode.methods.iterator(); - while (it.hasNext()) { - MethodNode mnode = it.next(); - ReferenceDetector r = new ReferenceDetector(); - mnode.accept(new RemappingMethodAdapter(mnode.access, mnode.desc, new MethodVisitor(Opcodes.ASM4) { - }, r)); - if (r.found) { - it.remove(); - changed = true; - } - } - if (changed) { - bytes = ASMHelper.createBytes(cnode, 0); - } - return bytes; - } -} diff --git a/archive/codechicken/lib/tool/Main.java b/archive/codechicken/lib/tool/Main.java deleted file mode 100644 index 039121ca..00000000 --- a/archive/codechicken/lib/tool/Main.java +++ /dev/null @@ -1,14 +0,0 @@ -package codechicken.lib.tool; - -public class Main { - - public static void main(String[] args) { - LibDownloader.load(); - try { - Class c_toolMain = new StripClassLoader().loadClass("codechicken.lib.tool.ToolMain"); - c_toolMain.getDeclaredMethod("main", String[].class).invoke(null, new Object[] { args }); - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/archive/codechicken/lib/tool/StripClassLoader.java b/archive/codechicken/lib/tool/StripClassLoader.java deleted file mode 100644 index 1a2f86db..00000000 --- a/archive/codechicken/lib/tool/StripClassLoader.java +++ /dev/null @@ -1,53 +0,0 @@ -package codechicken.lib.tool; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLClassLoader; - -public class StripClassLoader extends URLClassLoader { - - public StripClassLoader() { - super(new URL[0], StripClassLoader.class.getClassLoader()); - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if (!name.startsWith("codechicken.lib")) { - return super.loadClass(name); - } - - try { - String resName = name.replace('.', '/') + ".class"; - InputStream res = getResourceAsStream(resName); - if (res == null) { - throw new ClassNotFoundException("Could not find resource: " + resName); - } - byte[] bytes = readFully(res); - bytes = transform(bytes); - return defineClass(name, bytes, 0, bytes.length); - - } catch (IOException e) { - throw new ClassNotFoundException(name, e); - } - } - - public static byte[] readFully(InputStream is) throws IOException { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - int read; - byte[] data = new byte[16384]; - while ((read = is.read(data, 0, data.length)) > 0) { - buffer.write(data, 0, read); - } - - return buffer.toByteArray(); - } - - private byte[] transform(byte[] bytes) { - - bytes = MCStripTransformer.transform(bytes); - return bytes; - } -} diff --git a/archive/codechicken/lib/tool/ToolMain.java b/archive/codechicken/lib/tool/ToolMain.java deleted file mode 100644 index 46dd0353..00000000 --- a/archive/codechicken/lib/tool/ToolMain.java +++ /dev/null @@ -1,48 +0,0 @@ -package codechicken.lib.tool; - -import codechicken.lib.tool.module.ModuleQBConverter; - -public class ToolMain { - - public interface Module { - - void main(String[] args); - - String name(); - - void printHelp(); - } - - public static Module[] modules = new Module[] { new ModuleQBConverter() }; - - private static void printHelp() { - System.out.println("Usage: [module] [args]"); - System.out.println(" Modules: "); - for (Module m : modules) { - System.out.println(" - " + m.name()); - } - System.out.println("-h [module] for module help"); - } - - public static void main(String[] args) { - if (args.length > 0) { - for (Module m : modules) { - if (args[0].equals(m.name())) { - String[] args2 = new String[args.length - 1]; - System.arraycopy(args, 1, args2, 0, args2.length); - m.main(args2); - return; - } - } - if (args[0].equals("-h") && args.length >= 2) { - for (Module m : modules) { - if (args[1].equals(m.name())) { - m.printHelp(); - return; - } - } - } - } - printHelp(); - } -} diff --git a/archive/codechicken/lib/tool/module/JOptModule.java b/archive/codechicken/lib/tool/module/JOptModule.java deleted file mode 100644 index 54933995..00000000 --- a/archive/codechicken/lib/tool/module/JOptModule.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.tool.module; - -import codechicken.lib.tool.ToolMain; -import joptsimple.OptionException; -import joptsimple.OptionParser; -import joptsimple.OptionSet; - -import java.io.IOException; - -public abstract class JOptModule implements ToolMain.Module { - - OptionParser parser = new OptionParser(); - - @Override - public void main(String[] args) { - OptionSet options; - try { - options = parser.parse(args); - } catch (OptionException ex) { - System.err.println(ex.getLocalizedMessage()); - System.exit(-1); - return; - } - - try { - main(parser, options); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - protected abstract void main(OptionParser parser, OptionSet options); - - @Override - public void printHelp() { - try { - parser.printHelpOn(System.out); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/archive/codechicken/lib/tool/module/ModuleQBConverter.java b/archive/codechicken/lib/tool/module/ModuleQBConverter.java deleted file mode 100644 index 1110edce..00000000 --- a/archive/codechicken/lib/tool/module/ModuleQBConverter.java +++ /dev/null @@ -1,82 +0,0 @@ -package codechicken.lib.tool.module; - -import codechicken.lib.render.QBImporter; -import joptsimple.OptionParser; -import joptsimple.OptionSet; - -import java.io.File; - -import static java.util.Arrays.asList; - -public class ModuleQBConverter extends JOptModule { - - public ModuleQBConverter() { - parser.acceptsAll(asList("?", "h", "help"), "Show the help"); - parser.acceptsAll(asList("i", "input"), "comma separated list of paths to models (.qb or directories)").withRequiredArg().ofType(File.class).withValuesSeparatedBy(',').required(); - parser.acceptsAll(asList("o", "out"), "Output Directory").withRequiredArg().ofType(File.class); - parser.acceptsAll(asList("o2", "textureplanes"), "2nd level optimisation. Merges coplanar polygons. Increases texture size"); - parser.acceptsAll(asList("s", "squaretextures"), "Produce square textures"); - parser.acceptsAll(asList("t", "mergetextures"), "Use the same texture for all models"); - parser.acceptsAll(asList("r", "scalemc"), "Resize model to mc standard (shrink by factor of 16)"); - } - - protected void main(OptionParser parser, OptionSet options) { - int flags = 0; - if (options.has("o2")) { - flags |= QBImporter.TEXTUREPLANES; - } - if (options.has("s")) { - flags |= QBImporter.SQUARETEXTURE; - } - if (options.has("t")) { - flags |= QBImporter.MERGETEXTURES; - } - if (options.has("r")) { - flags |= QBImporter.SCALEMC; - } - - File[] input = options.valuesOf("input").toArray(new File[0]); - File[] outDir = new File[input.length]; - if (options.has("out")) { - File output = (File) options.valueOf("out"); - if (output.isFile()) { - throw new RuntimeException("Output Path is not a directory"); - } - if (!output.exists()) { - output.mkdirs(); - } - - for (int i = 0; i < input.length; i++) { - outDir[i] = output; - } - } else { - for (int i = 0; i < input.length; i++) { - outDir[i] = input[i].isDirectory() ? input[i] : input[i].getParentFile(); - } - } - - for (int i = 0; i < input.length; i++) { - File file = input[i]; - if (file.isDirectory()) { - for (File file2 : file.listFiles()) { - if (file2.getName().endsWith(".qb")) { - convert(file2, outDir[i], flags); - } - } - } else { - convert(file, outDir[i], flags); - } - } - } - - private void convert(File in, File outDir, int flags) { - System.out.println("Converting: " + in.getName()); - QBImporter.RasterisedModel m = QBImporter.loadQB(in).toRasterisedModel(flags); - m.export(new File(outDir, in.getName().replace(".qb", ".obj")), outDir); - } - - @Override - public String name() { - return "QBConverter"; - } -} diff --git a/build.gradle b/build.gradle index 77b639f8..7f154c2c 100644 --- a/build.gradle +++ b/build.gradle @@ -21,19 +21,14 @@ archivesBaseName = 'CodeChickenLib' sourceSets.main.resources.srcDirs += "src/main/generated" -file('build.properties').withReader { - def prop = new Properties() - prop.load(it) - project.ext.config = new ConfigSlurper().parse prop -} -config.mod_version = "${config.mod_version}." + (System.getenv("BUILD_NUMBER") ?: "1") -version = "${config.mc_version}-${config.mod_version}" -println "Starting build of ${archivesBaseName}, Version: ${config.mod_version}" -println "Using Forge: ${config.forge_version}, for Minecraft: ${config.mc_version}" +mod_version = "${mod_version}." + (System.getenv("BUILD_NUMBER") ?: "1") +version = "${mc_version}-${mod_version}" +println "Starting build of ${archivesBaseName}, Version: ${mod_version}" +println "Using Forge: ${forge_version}, for Minecraft: ${mc_version}" minecraft { - mappings channel: 'official', version: config.mc_version + mappings channel: 'official', version: mc_version accessTransformer = file("src/main/resources/META-INF/accesstransformer.cfg") runs { client { @@ -57,14 +52,14 @@ mixin { } processResources { - inputs.property 'mod_version', config.mod_version - inputs.property 'mc_version', config.mc_version + inputs.property 'mod_version', mod_version + inputs.property 'mc_version', mc_version filesMatching('META-INF/mods.toml') { - expand 'file': ['jarVersion': config.mod_version], - 'mc_version': config.mc_version, - 'forge_version': config.forge_version, - 'lang_version': config.forge_version.split('\\.')[0] + expand 'file': ['jarVersion': mod_version], + 'mc_version': mc_version, + 'forge_version': forge_version, + 'lang_version': forge_version.split('\\.')[0] } } @@ -80,7 +75,7 @@ repositories { } dependencies { - minecraft "net.neoforged:forge:${config.mc_version}-${config.forge_version}" + minecraft "net.neoforged:forge:${mc_version}-${forge_version}" shadow 'net.covers1624:Quack:0.4.7.72' @@ -103,7 +98,7 @@ def commonManifest = { attributes 'Specification-Version': "1" attributes 'Implementation-Title': archivesBaseName attributes 'Implementation-Vendor': 'covers1624' - attributes 'Implementation-Version': config.mod_version + attributes 'Implementation-Version': mod_version attributes 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") attributes 'MixinConfigs': 'mixins.codechickenlib.json' } @@ -222,34 +217,3 @@ signing { } sign publishing.publications.CodeChickenLib } - -/** - * Polls the 'compile' configuration for a dependency with the given module name - * and resolves, and returns its version. E.g: '1.2.+' will resolve to '1.2.3.4' - * - * @param module The module to search for. - * @param chop If the string should be chopped on the last '-' in its string. - * @param configuration The name of the configuration to search. - * @param errorMissing If an error should be thrown if it can't be found. - * @return The version string, '0' if 'errorMissing' is false and nothing was found. - */ -def resolve(module, chop = true, configuration = 'compile', errorMissing = true) { - //Copy and lenient resolve the configuration, Forge cant be resolved at this time so lenient is required. - def filtered = configurations.getByName(configuration).copy().incoming.artifactView({ it.lenient = true }).artifacts - .findAll { it.id.componentIdentifier.module == module } - .collect { it.id.componentIdentifier.version } - if (filtered.size() > 1) { - println "WARNING: Found ${filtered.size()} Dependencies with ModuleName '${module}' in configuration '${configuration.name}'" - } - if (errorMissing && filtered.isEmpty()) { - throw new RuntimeException("Failed resolve dependency version for '${module}'") - } - if (filtered.isEmpty()) return "0" - def version = filtered.first() as String - if (chop) { - def idx = version.lastIndexOf('-') - return version.substring(idx + 1) - } - return version -} - diff --git a/build.properties b/build.properties deleted file mode 100644 index 539ff8ac..00000000 --- a/build.properties +++ /dev/null @@ -1,3 +0,0 @@ -mc_version=1.20.1 -forge_version=47.1.65 -mod_version=4.4.0 diff --git a/gradle.properties b/gradle.properties index 6b1823d8..37d4aca9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,5 @@ org.gradle.daemon=false + +mc_version=1.20.1 +forge_version=47.1.65 +mod_version=4.4.0 From e062f78b9011f5b43e64600b18b86c3db92410a6 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 21:40:37 +1030 Subject: [PATCH 05/87] Remove obsolete code. --- .../internal/mixin/LevelRendererMixin.java | 34 ---- .../codechicken/lib/render/ModelHelper.java | 187 ------------------ src/main/resources/mixins.codechickenlib.json | 1 - 3 files changed, 222 deletions(-) delete mode 100644 src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java delete mode 100644 src/main/java/codechicken/lib/render/ModelHelper.java diff --git a/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java deleted file mode 100644 index 26af5cae..00000000 --- a/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.internal.mixin; - -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Camera; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.LightTexture; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** - * Credit to jozufozu and Flywheel for this mixin <3 - *

- * Created by covers1624 on 1/1/22. - */ -@Mixin (LevelRenderer.class) -public abstract class LevelRendererMixin { - -// @Inject ( -// method = "renderLevel", -// at = @At ( -// value = "INVOKE", -// ordinal = 1, -// target = "Lnet/minecraft/client/renderer/PostChain;process(F)V" -// ) -// ) -// private void disableTransparencyShaderDepth(PoseStack p1, float p2, long p3, boolean p4, Camera p5, GameRenderer p6, LightTexture p7, Matrix4f p8, CallbackInfo ci) { -// GlStateManager._depthMask(false); -// } -} diff --git a/src/main/java/codechicken/lib/render/ModelHelper.java b/src/main/java/codechicken/lib/render/ModelHelper.java deleted file mode 100644 index d127a629..00000000 --- a/src/main/java/codechicken/lib/render/ModelHelper.java +++ /dev/null @@ -1,187 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.vec.Vector3; -import codechicken.lib.vec.Vertex5; -import com.mojang.blaze3d.vertex.VertexFormat; - -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -/** - * Various helpers for CCModels - *

- * Created by covers1624 on 21/06/2017. - */ -public class ModelHelper { - - /** - * Quadulates a CCModel. - * Only Position and UV data is copied. - * - * @param inModel The in model. - * @return The new model. - */ - public static CCModel quadulate(CCModel inModel) { - if (inModel.vertexMode == VertexFormat.Mode.QUADS) { - throw new IllegalArgumentException("Cannot quadulate a quad model. Check if the model is triangles before calling this"); - } - List verts = new LinkedList<>(); - Iterator iter = verts.iterator(); - while (iter.hasNext()) { - verts.add(iter.next()); - verts.add(iter.next()); - Vertex5 copy = iter.next(); - verts.add(copy); - verts.add(copy.copy()); - } - CCModel outModel = CCModel.quadModel(verts.size()); - outModel.verts = verts.toArray(outModel.verts); - return outModel; - } - - /** - * Attempts to combine square faces. - * A NEW model is returned with combined faces. - * You WILL need to copy / compute normals yourself. - * - * @param model Input. - * @return New model with combined faces. - */ - public static CCModel simplifyModel(CCModel model) { - List verts = new LinkedList<>(); - Collections.addAll(verts, model.getVertices()); - List combinedVerts = simplifyModel(verts); - CCModel outModel = CCModel.quadModel(combinedVerts.size()); - outModel.verts = combinedVerts.toArray(outModel.verts); - return outModel; - } - - /** - * Attempts to combine square faces. - * - * @param in Quads in. - * @return Quads out. - * @author RwTema - */ - public static LinkedList simplifyModel(List in) { - - LinkedList faces = new LinkedList<>(); - Iterator iter = in.iterator(); - while (iter.hasNext()) { - Face f = Face.loadFromIterator(iter); - - faces.removeIf(f::attemptToCombine); - faces.add(f); - } - - LinkedList out = new LinkedList<>(); - for (Face f : faces) { - Collections.addAll(out, f.verts); - } - - return out; - } - - private static class Face { - - public static Face loadFromIterator(Iterator iter) { - - Face f = new Face(new Vertex5[4]); - for (int i = 0; i < 4; i++) { - f.verts[i] = iter.next(); - } - - return f; - } - - public Vertex5[] verts; - - public Vertex5 vec(int s) { - - return verts[s & 3]; - } - - public void setVec(int s, Vertex5 newVec) { - - verts[s & 3] = newVec; - } - - public Face(Vertex5... v) { - - assert v.length == 4; - this.verts = v; - } - - public boolean isPolygon() { - - for (int i = 0; i < 4; i++) { - if (vec(i).vec.equalsT(vec(i + 1).vec)) { - return true; - } - } - return false; - } - - public Face reverse() { - - verts = new Vertex5[] { verts[3], verts[2], verts[1], verts[0] }; - return this; - } - - public boolean attemptToCombine(Face other) { - - if (isPolygon() || other.isPolygon()) { - return false; - } - - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - other.reverse(); - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - other.reverse(); - return false; - } - - public boolean equalVert(Vertex5 a, Vertex5 b) { - - return a.vec.equalsT(b.vec) && a.uv.equals(b.uv); - } - - public boolean attemptToCombineUnflipped(Face other) { - - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - if (equalVert(vec(i), vec(j)) && equalVert(vec(i + 1), vec(j - 1))) { - Vector3 l1 = (vec(i - 1).vec.copy().subtract(vec(i).vec)).normalize(); - Vector3 l2 = (vec(i + 2).vec.copy().subtract(vec(i + 1).vec)).normalize(); - - Vector3 l3 = (other.vec(j).vec.copy().subtract(other.vec(j + 1).vec)).normalize(); - Vector3 l4 = (other.vec(j - 1).vec.copy().subtract(other.vec(j - 2).vec)).normalize(); - - if (l1.equalsT(l3) && l2.equalsT(l4)) { - setVec(i, other.vec(j + 1)); - setVec(i + 1, other.vec(j - 2)); - return true; - } - } - } - } - return false; - } - } -} diff --git a/src/main/resources/mixins.codechickenlib.json b/src/main/resources/mixins.codechickenlib.json index 5d495d86..63d374ff 100644 --- a/src/main/resources/mixins.codechickenlib.json +++ b/src/main/resources/mixins.codechickenlib.json @@ -7,7 +7,6 @@ "compatibilityLevel": "JAVA_17", "client": [ "ItemRendererMixin", - "LevelRendererMixin", "MinecraftMixin", "ShaderInstanceMixin" ] From 74d09048dc0de092fb5eff7a7c36f6d7657f227f Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 21:41:04 +1030 Subject: [PATCH 06/87] Fix some javadoc warnings. --- .../java/codechicken/lib/capability/CapabilityCache.java | 1 + src/main/java/codechicken/lib/data/MCDataOutput.java | 8 ++++---- src/main/java/codechicken/lib/math/MathHelper.java | 2 +- .../codechicken/lib/model/pipeline/BakedPipeline.java | 2 +- .../lib/model/pipeline/transformers/QuadCornerKicker.java | 2 +- .../lib/model/pipeline/transformers/QuadFaceStripper.java | 2 +- .../java/codechicken/lib/raytracer/IndexedVoxelShape.java | 4 ++-- .../lib/render/particle/CustomParticleHandler.java | 6 ++++-- src/main/java/codechicken/lib/util/RotationUtils.java | 2 +- 9 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/codechicken/lib/capability/CapabilityCache.java b/src/main/java/codechicken/lib/capability/CapabilityCache.java index 401c0044..d6b5c151 100644 --- a/src/main/java/codechicken/lib/capability/CapabilityCache.java +++ b/src/main/java/codechicken/lib/capability/CapabilityCache.java @@ -6,6 +6,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; diff --git a/src/main/java/codechicken/lib/data/MCDataOutput.java b/src/main/java/codechicken/lib/data/MCDataOutput.java index d380f706..89bcb3b6 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutput.java +++ b/src/main/java/codechicken/lib/data/MCDataOutput.java @@ -386,7 +386,7 @@ default MCDataOutput append(byte[] bytes) { /** * Writes a Variable length int. * Doesn't handle Signed ints well, they end up as 5 bytes, - * instead of 4, Use {@link #writeSignedVarInt} if you requires numbers <= -1 + * instead of 4, Use {@link #writeSignedVarInt} if you require numbers {@code <= -1} * * @param i The int. * @return The same stream. @@ -404,7 +404,7 @@ default MCDataOutput writeVarInt(int i) { /** * Writes a Variable length long. * Doesn't handle Signed longs well, they end up as 10 bytes, - * instead of 8, Use {@link #writeSignedVarLong} if you requires numbers <= -1 + * instead of 8, Use {@link #writeSignedVarLong} if you require numbers {@code <= -1} * * @param l The long. * @return The same stream. @@ -420,7 +420,7 @@ default MCDataOutput writeVarLong(long l) { /** * Writes a Signed Variable length int. - * Favourable for numbers <= -1 + * Favourable for numbers {@code <= -1} * * @param i The int. * @return The same stream. @@ -431,7 +431,7 @@ default MCDataOutput writeSignedVarInt(int i) { /** * Writes a Signed Variable length long. - * Favourable for numbers <= -1 + * Favourable for numbers {@code <= -1} * * @param i The long. * @return The same stream. diff --git a/src/main/java/codechicken/lib/math/MathHelper.java b/src/main/java/codechicken/lib/math/MathHelper.java index 7cb2898f..bf055bac 100644 --- a/src/main/java/codechicken/lib/math/MathHelper.java +++ b/src/main/java/codechicken/lib/math/MathHelper.java @@ -220,7 +220,7 @@ public static float round(float number, float multiplier) { } /** - * @return min <= value <= max + * @return {@code min <= value <= max} */ public static boolean between(double min, double value, double max) { return min <= value && value <= max; diff --git a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java b/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java index bb6415bd..41866bec 100644 --- a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java +++ b/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java @@ -57,7 +57,7 @@ * Now you should disable / enable any optional elements that are needed, NOTE: Element states are reset when resetting * the pipeline. * Now you will need to call {@link #prepare(IVertexConsumer)} on the pipeline, here you will pass your collector, - * usually this is some form of {@link BakedQuadBuilder}, or {@link Quad} can also pack things. + * usually {@link Quad}. * Now final step, simply pipe the quad you want to transform INTO the pipeline 'quad.pipe(pipeline)' * And that's it! hell, Pipe a pipeline into each other for all i care, the system is efficient enough that there * would be no performance penalty for doing so. diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java index 265866a0..d605f2b0 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java @@ -81,7 +81,7 @@ public void setSide(int side) { /** * Sets the bitmask of Facades / Covers in the blockspace. - * This is as simple as, mask = (1 << side) + * This is as simple as, {@code mask = (1 << side)} * * @param mask The mask. */ diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java index c2f67693..6bdbb977 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java @@ -72,7 +72,7 @@ public void setBounds(AABB bounds) { /** * The mask to strip edges. * This is an opt-in system, - * the mask is simple 'mask = (1 << side)'. + * the mask is simple {@code mask = (1 << side)} * * @param mask The mask. */ diff --git a/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java b/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java index e459d887..322845ad 100644 --- a/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java +++ b/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java @@ -11,8 +11,8 @@ /** * A VoxelShape implementation, produces a {@link VoxelShapeBlockHitResult} when ray traced. - * {@link IndexedVoxelShape#data} will be passed through to {@link RayTraceResult#hitInfo} and - * to {@link RayTraceResult#subHit} if its an integer. + * {@link IndexedVoxelShape#data} will be passed through to {@link VoxelShapeBlockHitResult#hitInfo} and + * to {@link VoxelShapeBlockHitResult#subHit} if it's an integer. *

* Created by covers1624 on 5/12/20. */ diff --git a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java index ff630200..97282afb 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java +++ b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java @@ -18,12 +18,14 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.client.extensions.common.IClientBlockExtensions; import net.minecraftforge.client.model.data.ModelData; import java.util.ArrayList; @@ -114,14 +116,14 @@ public static boolean handleHitEffects(BlockState state, Level world, HitResult } /** - * {@link Block#addHitEffects} + * {@link IClientBlockExtensions#addHitEffects} * Provided the model bound is an instance of IModelParticleProvider, you will have landing particles just handled for you. * Use the default PerspectiveModel implementations inside CCL, Destroy effects will just be handled for you. * * @param world The world. * @param pos The position of the block. * @param manager The ParticleManager. - * @return True if particles were added, basically just return the result of this method inside {@link Block#addHitEffects} + * @return True if particles were added, basically just return the result of this method inside {@link IClientBlockExtensions#addHitEffects} */ @OnlyIn (Dist.CLIENT) public static boolean handleDestroyEffects(Level world, BlockPos pos, BlockState state, ParticleEngine manager) { diff --git a/src/main/java/codechicken/lib/util/RotationUtils.java b/src/main/java/codechicken/lib/util/RotationUtils.java index 2c7a17a6..b94cb9ea 100644 --- a/src/main/java/codechicken/lib/util/RotationUtils.java +++ b/src/main/java/codechicken/lib/util/RotationUtils.java @@ -155,7 +155,7 @@ public static Direction rotateBackwards(Direction facing) { /** * Turns Entity rotation in to Direction. * - * @param rotation The entity rotation, Generally MathHelper.floor_double((entity.rotationYaw * 4F) / 360F + 0.5D) & 3; + * @param rotation The entity rotation, Generally {@code MathHelper.floor_double((entity.rotationYaw * 4F) / 360F + 0.5D) & 3}; * @return The rotation in Direction. */ public static Direction entityRotationToSide(int rotation) { From a3f44b64999094921ca6a40dd424fa46b1d768d3 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 21:41:22 +1030 Subject: [PATCH 07/87] Move to new maven group. --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 7f154c2c..ab39166c 100644 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ java { withJavadocJar() } -group = 'codechicken' +group = 'io.codechicken' archivesBaseName = 'CodeChickenLib' sourceSets.main.resources.srcDirs += "src/main/generated" From 27bbe356ce27182da58a011a05598319bb7a0869 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 21:46:09 +1030 Subject: [PATCH 08/87] Add foojay toolchain resolver. --- settings.gradle | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/settings.gradle b/settings.gradle index 3a4d862d..5141985a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,11 +1,13 @@ pluginManagement { repositories { + mavenLocal() gradlePluginPortal() - maven { - name = 'NeoForged' - url = 'https://maven.neoforged.net/releases' - } + maven { url 'https://maven.neoforged.net/releases' } } } +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' +} + rootProject.name = 'CodeChickenLib' From 8939ac03ad6e5a20aa1ffa48425e3d65f5e0cffb Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 Nov 2023 22:40:46 +1030 Subject: [PATCH 09/87] Invoke ant signjar directly. Fix publishing not using classifier. --- .gitignore | 2 -- build.gradle | 38 ++++++++++++++++++++------------------ 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.gitignore b/.gitignore index be21d4f2..1030c646 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,6 @@ # exclude all /* -# Include important folders - # Gradle stuff !gradle/ !gradlew diff --git a/build.gradle b/build.gradle index ab39166c..179446e2 100644 --- a/build.gradle +++ b/build.gradle @@ -3,7 +3,6 @@ plugins { id 'maven-publish' id 'signing' id 'com.github.johnrengelman.shadow' version '7.1.2' - id "net.covers1624.signing" version '1.1.4' apply false id 'net.neoforged.gradle' version '[6.0.18,6.2)' id 'org.spongepowered.mixin' version '0.7.+' } @@ -21,7 +20,6 @@ archivesBaseName = 'CodeChickenLib' sourceSets.main.resources.srcDirs += "src/main/generated" - mod_version = "${mod_version}." + (System.getenv("BUILD_NUMBER") ?: "1") version = "${mc_version}-${mod_version}" println "Starting build of ${archivesBaseName}, Version: ${mod_version}" @@ -106,6 +104,7 @@ def commonManifest = { jar.enabled = false shadowJar { finalizedBy 'reobfShadowJar' + finalizedBy 'signShadowJar' archiveClassifier = 'universal' manifest commonManifest @@ -113,29 +112,32 @@ shadowJar { from file("LICENSE") } -def jarArchive = shadowJar -if (System.getenv("KEY_STORE") || project.hasProperty('keyStore')) { - jarArchive = tasks.register("signShadowJar", net.covers1624.jarsign.jar.SignJarTask) { - dependsOn("shadowJar") - dependsOn("reobfShadowJar") +tasks.register("signShadowJar") { + dependsOn("shadowJar") + dependsOn("reobfShadowJar") - input = shadowJar.archiveFile.get().asFile - output = shadowJar.archiveFile.get().asFile + doFirst { + def args = [:] + args['jar'] = shadowJar.archiveFile.get().asFile if (System.getenv("KEY_STORE")) { - keyStore = System.getenv("KEY_STORE") + args['keyStore'] = System.getenv("KEY_STORE") file(System.getenv("KEY_STORE_PROPS")).withReader { def props = new Properties() props.load(it) - alias = props['alias'] - storePass = props['storePass'] - keyPass = props['keyPass'] + args.addAll(props) } + } else if (project.hasProperty('keyStore')) { + args['keyStore'] = project.getProperty('keyStore') + args['alias'] = project.getProperty('keyStoreAlias') + args['storePass'] = project.getProperty('keyStorePass') + args['keyPass'] = project.getProperty('keyStoreKeyPass') } else { - keyStore = project.getProperty('keyStore') - alias = project.getProperty('keyStoreAlias') - storePass = project.getProperty('keyStorePass') - keyPass = project.getProperty('keyStoreKeyPass') + println "No signing properties." + state.setOutcome(org.gradle.api.internal.tasks.TaskExecutionOutcome.UP_TO_DATE) + didWork = false + return } + project.ant.invokeMethod('signjar', args) } } @@ -160,7 +162,7 @@ publishing { groupId project.group artifactId project.archivesBaseName version project.version - artifact jarArchive + artifact shadowJar artifact sourcesJar artifact javadocJar From b686a1daecfad6565b2874edef5335cd607ff466 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 13 Nov 2023 04:03:41 +1030 Subject: [PATCH 10/87] In-dev mixin to nuke the narrator. --- .../lib/internal/mixin/CCLMixinPlugin.java | 32 +++++++++++++++++++ .../lib/internal/mixin/ItemRendererMixin.java | 2 +- .../internal/mixin/dev/GameNarratorMixin.java | 26 +++++++++++++++ src/main/resources/mixins.codechickenlib.json | 2 ++ 4 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java diff --git a/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java b/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java new file mode 100644 index 00000000..6f42475b --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java @@ -0,0 +1,32 @@ +package codechicken.lib.internal.mixin; + +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Set; + +/** + * Created by covers1624 on 13/11/23. + */ +public class CCLMixinPlugin implements IMixinConfigPlugin { + + private static final boolean USE_DEV_MIXINS = Boolean.getBoolean("ccl.dev.mixins"); + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + // Don't load development mixins unless explicitly enabled. + // These mixins are usually quite hacky/aggressive and accomplish specific things for my dev environment. + return !mixinClassName.startsWith("codechicken.lib.internal.mixin.dev") || USE_DEV_MIXINS; + } + + // @formatter:off + @Override public void onLoad(String mixinPackage) { } + @Override public String getRefMapperConfig() { return null; } + @Override public void acceptTargets(Set myTargets, Set otherTargets) { } + @Override public List getMixins() { return null; } + @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } + @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } + // @formatter:on +} diff --git a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java index 521c70df..0157a042 100644 --- a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java +++ b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java @@ -19,7 +19,7 @@ * Created by covers1624 on 9/8/20. */ @Mixin (ItemRenderer.class) -public class ItemRendererMixin { +abstract class ItemRendererMixin { @Inject ( method = "render", diff --git a/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java b/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java new file mode 100644 index 00000000..ba833319 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java @@ -0,0 +1,26 @@ +package codechicken.lib.internal.mixin.dev; + +import com.mojang.text2speech.Narrator; +import net.minecraft.client.GameNarrator; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +/** + * Created by covers1624 on 13/11/23. + */ +@Mixin (GameNarrator.class) +abstract class GameNarratorMixin { + + @Redirect ( + method = "", + at = @At ( + value = "INVOKE", + target = "Lcom/mojang/text2speech/Narrator;getNarrator()Lcom/mojang/text2speech/Narrator;" + ) + ) + private Narrator redirectGetNarator() { + // GO AWAY NARRATOR ERRORS! + return Narrator.EMPTY; + } +} diff --git a/src/main/resources/mixins.codechickenlib.json b/src/main/resources/mixins.codechickenlib.json index 63d374ff..72815248 100644 --- a/src/main/resources/mixins.codechickenlib.json +++ b/src/main/resources/mixins.codechickenlib.json @@ -3,9 +3,11 @@ "minVersion": "0.8", "package": "codechicken.lib.internal.mixin", "refmap": "mixins.codechickenlib.refmap.json", + "plugin": "codechicken.lib.internal.mixin.CCLMixinPlugin", "target": "@env(DEFAULT)", "compatibilityLevel": "JAVA_17", "client": [ + "dev.GameNarratorMixin", "ItemRendererMixin", "MinecraftMixin", "ShaderInstanceMixin" From 42456376ce364b97e7de448fa3db3288a25fdd3b Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 13 Nov 2023 04:04:11 +1030 Subject: [PATCH 11/87] Pass PackOutput directly into LootTableProvider. --- .../java/codechicken/lib/datagen/LootTableProvider.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/codechicken/lib/datagen/LootTableProvider.java b/src/main/java/codechicken/lib/datagen/LootTableProvider.java index c1330534..bf3bf7ef 100644 --- a/src/main/java/codechicken/lib/datagen/LootTableProvider.java +++ b/src/main/java/codechicken/lib/datagen/LootTableProvider.java @@ -45,8 +45,8 @@ public abstract class LootTableProvider implements DataProvider { private final PackOutput.PathProvider output; private final Map tables = new HashMap<>(); - protected LootTableProvider(PackOutput.PathProvider output) { - this.output = output; + protected LootTableProvider(PackOutput output) { + this.output = output.createPathProvider(PackOutput.Target.DATA_PACK, "loot_tables"); } @Override @@ -99,7 +99,7 @@ public static abstract class BlockLootProvider extends LootTableProvider { ); protected static final LootItemCondition.Builder NO_SILK_TOUCH = SILK_TOUCH.invert(); - protected BlockLootProvider(PackOutput.PathProvider output) { + protected BlockLootProvider(PackOutput output) { super(output); } From fa868eb4fc159d6aa5fec78a95df1a140d26419b Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 13 Nov 2023 04:04:33 +1030 Subject: [PATCH 12/87] Add system property to force disable mod update checks for dev time. --- src/main/java/codechicken/lib/CodeChickenLib.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/codechicken/lib/CodeChickenLib.java b/src/main/java/codechicken/lib/CodeChickenLib.java index 37ae617f..f2eaed20 100644 --- a/src/main/java/codechicken/lib/CodeChickenLib.java +++ b/src/main/java/codechicken/lib/CodeChickenLib.java @@ -9,6 +9,7 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.loading.FMLConfig; import java.nio.file.Paths; @@ -18,6 +19,12 @@ @Mod (CodeChickenLib.MOD_ID) public class CodeChickenLib { + static { + if (Boolean.getBoolean("ccl.noModUpdateChecking")) { + FMLConfig.updateConfig(FMLConfig.ConfigValue.VERSION_CHECK, false); + } + } + public static final String MOD_ID = "codechickenlib"; public static ConfigCategory config; From 0589d18f154d406a3e5559d2f1e9abdaf7336557 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 13 Nov 2023 04:05:38 +1030 Subject: [PATCH 13/87] Add 'ClassModelLoader' - Instantiates a specific class for the model. --- .../lib/datagen/ItemModelProvider.java | 44 ++++++++++++++++ .../codechicken/lib/internal/ClientInit.java | 2 + .../lib/model/ClassModelLoader.java | 51 +++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 src/main/java/codechicken/lib/model/ClassModelLoader.java diff --git a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java index a91a4d8a..96b21847 100644 --- a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java +++ b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java @@ -2,6 +2,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import net.minecraft.client.resources.model.BakedModel; import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; @@ -17,6 +18,8 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; @@ -138,6 +141,18 @@ protected void simpleItemBlock(Block block) { .parent(new ModelFile.UncheckedModelFile(modLoc("block/" + name(block)))) .noTexture(); } + + protected SimpleItemModelBuilder clazz(Supplier item, Class clazz) { + return clazz(item.get(), clazz); + } + + protected SimpleItemModelBuilder clazz(ItemLike item, Class clazz) { + return generated(item) + .noTexture() + .customLoader(ClassCustomLoaderBuilder::new) + .clazz(clazz) + .end(); + } //endregion private SimpleItemModelBuilder makeNested(ItemLike item) { @@ -328,6 +343,35 @@ protected JsonObject toJson(JsonObject json) { } } + public static class ClassCustomLoaderBuilder extends CustomLoaderBuilder { + + private @Nullable Class clazz; + + protected ClassCustomLoaderBuilder(SimpleItemModelBuilder parent) { + super(new ResourceLocation(MOD_ID, "class"), parent); + } + + public ClassCustomLoaderBuilder clazz(Class clazz) { + try { + Constructor ctor = clazz.getConstructor(); + if (!Modifier.isPublic(ctor.getModifiers())) { + throw new IllegalArgumentException("Expected single no-args public constructor."); + } + } catch (NoSuchMethodException ex) { + throw new IllegalStateException("Expected single no-args public constructor.", ex); + } + this.clazz = clazz; + return this; + } + + @Override + protected JsonObject toJson(JsonObject json) { + super.toJson(json); + json.addProperty("class", Objects.requireNonNull(clazz).getName()); + return json; + } + } + public static class CompositeLoaderBuilder extends CustomLoaderBuilder { private final Map children = new LinkedHashMap<>(); diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java index ed96cd2c..a0186ba8 100644 --- a/src/main/java/codechicken/lib/internal/ClientInit.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -4,6 +4,7 @@ import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigSyncManager; import codechicken.lib.model.CompositeItemModel; +import codechicken.lib.model.ClassModelLoader; import codechicken.lib.render.CCRenderEventHandler; import codechicken.lib.render.block.BlockRenderingRegistry; import net.covers1624.quack.util.CrashLock; @@ -71,5 +72,6 @@ private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut eve private static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) { event.register("item_composite", new CompositeItemModel()); + event.register("class", new ClassModelLoader()); } } diff --git a/src/main/java/codechicken/lib/model/ClassModelLoader.java b/src/main/java/codechicken/lib/model/ClassModelLoader.java new file mode 100644 index 00000000..8238e397 --- /dev/null +++ b/src/main/java/codechicken/lib/model/ClassModelLoader.java @@ -0,0 +1,51 @@ +package codechicken.lib.model; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import net.covers1624.quack.gson.JsonUtils; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.Material; +import net.minecraft.client.resources.model.ModelBaker; +import net.minecraft.client.resources.model.ModelState; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.client.model.geometry.IGeometryBakingContext; +import net.minecraftforge.client.model.geometry.IGeometryLoader; +import net.minecraftforge.client.model.geometry.IUnbakedGeometry; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.function.Function; + +import static net.covers1624.quack.util.SneakyUtils.unsafeCast; + +/** + * Created by covers1624 on 13/11/23. + */ +public class ClassModelLoader implements IGeometryLoader { + + @Override + public Geometry read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) throws JsonParseException { + try { + Class clazz = Class.forName(JsonUtils.getString(jsonObject, "class")); + Constructor ctor = unsafeCast(clazz.getConstructor()); + return new Geometry(ctor); + } catch (ClassNotFoundException | NoSuchMethodException ex) { + throw new RuntimeException(ex); + } + } + + public record Geometry(Constructor ctor) implements IUnbakedGeometry { + + @Override + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + try { + return ctor.newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException("Failed to construct class.", ex); + } + } + } +} From 5eda7dad07472d96d5fe612a9e59214703cdcab3 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 6 Jan 2024 19:36:25 +1030 Subject: [PATCH 14/87] Add publishing metadata. --- build.gradle | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/build.gradle b/build.gradle index 179446e2..192df6fc 100644 --- a/build.gradle +++ b/build.gradle @@ -1,3 +1,5 @@ +import groovy.json.JsonOutput + plugins { id 'java' id 'maven-publish' @@ -101,6 +103,24 @@ def commonManifest = { attributes 'MixinConfigs': 'mixins.codechickenlib.json' } +def publishingMetadata = project.layout.buildDirectory.file("libs/$archivesBaseName-$version-publishing.json") +def publishingMetadataTask = tasks.register("publishingMetadata") { + outputs.file(publishingMetadata) + doFirst { + publishingMetadata.get().asFile.text = JsonOutput.prettyPrint(JsonOutput.toJson([ + [ + 'displayName' : "CodeChicken Lib ${version}", + 'mcVersion' : "${mc_version}", + 'version' : "${mod_version}", + 'classifier' : 'universal', + 'modLoader' : 'neoforge', + 'curseforgeId': '242818', + 'modrinthId' : '2gq0ALnz' + ] + ])) + } +} + jar.enabled = false shadowJar { finalizedBy 'reobfShadowJar' @@ -165,6 +185,10 @@ publishing { artifact shadowJar artifact sourcesJar artifact javadocJar + artifact(publishingMetadata) { + builtBy publishingMetadataTask + classifier 'publishing' + } pom { name = archivesBaseName From b4954cfce8d11a99275e3e7e6bc601adc1913548 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 6 Jan 2024 19:39:17 +1030 Subject: [PATCH 15/87] Fix derp in signing task. --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 192df6fc..35fb7af0 100644 --- a/build.gradle +++ b/build.gradle @@ -144,7 +144,7 @@ tasks.register("signShadowJar") { file(System.getenv("KEY_STORE_PROPS")).withReader { def props = new Properties() props.load(it) - args.addAll(props) + args.putAll(props) } } else if (project.hasProperty('keyStore')) { args['keyStore'] = project.getProperty('keyStore') From 9fbd40b1ce99b13129e65c8d77a87da8d4de651b Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Fri, 26 Jan 2024 15:41:10 +1100 Subject: [PATCH 16/87] Feature/modular gui (#451) * Modular GUI Implementation. * First round of tweaks based on covers feedback. * Made requested changes * Update JEI maven --- build.gradle | 4 + gradle.properties | 1 + .../java/codechicken/lib/colour/Colour.java | 72 + .../codechicken/lib/compat/JEIPlugin.java | 37 + .../lib/gui/modular/ModularGui.java | 597 ++++++ .../lib/gui/modular/ModularGuiContainer.java | 280 +++ .../lib/gui/modular/ModularGuiScreen.java | 121 ++ .../lib/gui/modular/elements/GuiButton.java | 335 ++++ .../gui/modular/elements/GuiColourPicker.java | 232 +++ .../gui/modular/elements/GuiContextMenu.java | 135 ++ .../lib/gui/modular/elements/GuiDVD.java | 97 + .../lib/gui/modular/elements/GuiDialog.java | 241 +++ .../lib/gui/modular/elements/GuiElement.java | 491 +++++ .../gui/modular/elements/GuiEnergyBar.java | 143 ++ .../modular/elements/GuiEntityRenderer.java | 264 +++ .../modular/elements/GuiEventProvider.java | 122 ++ .../gui/modular/elements/GuiFluidTank.java | 252 +++ .../gui/modular/elements/GuiItemStack.java | 118 ++ .../lib/gui/modular/elements/GuiList.java | 221 +++ .../gui/modular/elements/GuiManipulable.java | 401 ++++ .../gui/modular/elements/GuiProgressIcon.java | 115 ++ .../gui/modular/elements/GuiRectangle.java | 165 ++ .../gui/modular/elements/GuiScrolling.java | 219 +++ .../lib/gui/modular/elements/GuiSlider.java | 266 +++ .../lib/gui/modular/elements/GuiSlots.java | 312 +++ .../lib/gui/modular/elements/GuiText.java | 268 +++ .../gui/modular/elements/GuiTextField.java | 660 +++++++ .../lib/gui/modular/elements/GuiTextList.java | 173 ++ .../lib/gui/modular/elements/GuiTexture.java | 110 ++ .../lib/gui/modular/lib/BackgroundRender.java | 34 + .../lib/gui/modular/lib/ColourState.java | 72 + .../lib/gui/modular/lib/Constraints.java | 209 ++ .../lib/gui/modular/lib/ContentElement.java | 14 + .../lib/gui/modular/lib/CursorHelper.java | 100 + .../lib/gui/modular/lib/DynamicTextures.java | 30 + .../lib/gui/modular/lib/ElementEvents.java | 272 +++ .../lib/gui/modular/lib/ForegroundRender.java | 32 + .../lib/gui/modular/lib/GuiProvider.java | 42 + .../lib/gui/modular/lib/GuiRender.java | 1728 +++++++++++++++++ .../lib/gui/modular/lib/ScissorHandler.java | 75 + .../lib/gui/modular/lib/SliderState.java | 139 ++ .../lib/gui/modular/lib/TextState.java | 56 + .../lib/gui/modular/lib/TooltipHandler.java | 105 + .../lib/container/ContainerGuiProvider.java | 33 + .../lib/container/ContainerScreenAccess.java | 22 + .../gui/modular/lib/container/DataSync.java | 48 + .../gui/modular/lib/container/SlotGroup.java | 119 ++ .../lib/gui/modular/lib/geometry/Align.java | 14 + .../lib/gui/modular/lib/geometry/Axis.java | 13 + .../gui/modular/lib/geometry/AxisConfig.java | 96 + .../lib/gui/modular/lib/geometry/Borders.java | 118 ++ .../lib/geometry/ConstrainedGeometry.java | 376 ++++ .../gui/modular/lib/geometry/Constraint.java | 154 ++ .../modular/lib/geometry/ConstraintImpl.java | 294 +++ .../gui/modular/lib/geometry/Direction.java | 40 + .../gui/modular/lib/geometry/GeoParam.java | 32 + .../lib/gui/modular/lib/geometry/GeoRef.java | 36 + .../gui/modular/lib/geometry/GuiParent.java | 190 ++ .../gui/modular/lib/geometry/Position.java | 103 + .../gui/modular/lib/geometry/Rectangle.java | 308 +++ .../lib/gui/modular/sprite/CCGuiTextures.java | 59 + .../lib/gui/modular/sprite/Material.java | 126 ++ .../gui/modular/sprite/ModAtlasHolder.java | 101 + .../codechicken/lib/internal/ClientInit.java | 12 + .../lib/internal/network/CCLNetwork.java | 6 +- .../internal/network/ClientPacketHandler.java | 5 +- .../internal/network/ServerPacketHandler.java | 22 + .../container/data/AbstractDataStore.java | 45 + .../inventory/container/data/BooleanData.java | 42 + .../inventory/container/data/ByteData.java | 42 + .../inventory/container/data/DoubleData.java | 42 + .../inventory/container/data/FloatData.java | 42 + .../inventory/container/data/FluidData.java | 53 + .../lib/inventory/container/data/IntData.java | 42 + .../inventory/container/data/LongData.java | 42 + .../inventory/container/data/ShortData.java | 42 + .../modular/ModularGuiContainerMenu.java | 321 +++ .../container/modular/ModularSlot.java | 121 ++ .../lib/render/CCRenderEventHandler.java | 2 + .../java/codechicken/lib/util/FormatUtil.java | 46 + .../resources/META-INF/accesstransformer.cfg | 24 + .../assets/codechickenlib/atlases/gui.json | 9 + .../textures/gui/cursors/drag.png | Bin 0 -> 4183 bytes .../textures/gui/cursors/resize_diag_tlbr.png | Bin 0 -> 3987 bytes .../textures/gui/cursors/resize_diag_trbl.png | Bin 0 -> 4339 bytes .../textures/gui/cursors/resize_h.png | Bin 0 -> 3325 bytes .../textures/gui/cursors/resize_v.png | Bin 0 -> 3955 bytes .../gui/dynamic/button_borderless.png | Bin 0 -> 8152 bytes .../gui/dynamic/button_borderless_pressed.png | Bin 0 -> 12424 bytes .../textures/gui/dynamic/button_highlight.png | Bin 0 -> 10447 bytes .../dynamic/button_highlight_borderless.png | Bin 0 -> 14008 bytes .../gui/dynamic/button_highlight_pressed.png | Bin 0 -> 14458 bytes .../textures/gui/dynamic/button_pressed.png | Bin 0 -> 12741 bytes .../textures/gui/dynamic/button_vanilla.png | Bin 0 -> 8373 bytes .../gui/dynamic/button_vanilla_disabled.png | Bin 0 -> 6849 bytes .../textures/gui/dynamic/gui_borderless.png | Bin 0 -> 6281 bytes .../textures/gui/dynamic/gui_vanilla.png | Bin 0 -> 6532 bytes .../textures/gui/widgets/energy_empty.png | Bin 0 -> 8061 bytes .../textures/gui/widgets/energy_full.png | Bin 0 -> 13959 bytes .../gui/widgets/progress_arrow_empty.png | Bin 0 -> 7299 bytes .../gui/widgets/progress_arrow_full.png | Bin 0 -> 6769 bytes .../textures/gui/widgets/slot.png | Bin 0 -> 2123 bytes .../textures/gui/widgets/slot_large.png | Bin 0 -> 5546 bytes 103 files changed, 12599 insertions(+), 3 deletions(-) create mode 100644 src/main/java/codechicken/lib/compat/JEIPlugin.java create mode 100644 src/main/java/codechicken/lib/gui/modular/ModularGui.java create mode 100644 src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java create mode 100644 src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiList.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiText.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java create mode 100644 src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/ColourState.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/Constraints.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/ContentElement.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/GuiProvider.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/SliderState.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/TextState.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/container/ContainerGuiProvider.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/Align.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/Axis.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/AxisConfig.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/Borders.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/Direction.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoParam.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoRef.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/GuiParent.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/Position.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java create mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java create mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/Material.java create mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java create mode 100644 src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/BooleanData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/ByteData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/DoubleData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/FloatData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/FluidData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/IntData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/LongData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/ShortData.java create mode 100644 src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java create mode 100644 src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java create mode 100644 src/main/java/codechicken/lib/util/FormatUtil.java create mode 100644 src/main/resources/assets/codechickenlib/atlases/gui.json create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/cursors/drag.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_tlbr.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_trbl.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_h.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_v.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless_pressed.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_borderless.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_pressed.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_pressed.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla_disabled.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_borderless.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_vanilla.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/widgets/energy_empty.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/widgets/energy_full.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/widgets/progress_arrow_empty.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/widgets/progress_arrow_full.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/widgets/slot.png create mode 100644 src/main/resources/assets/codechickenlib/textures/gui/widgets/slot_large.png diff --git a/build.gradle b/build.gradle index 35fb7af0..6c3b0857 100644 --- a/build.gradle +++ b/build.gradle @@ -72,6 +72,7 @@ configurations { repositories { mavenLocal() maven { url "https://maven.covers1624.net/" } + maven { url "https://maven.blamejared.com/" } } dependencies { @@ -81,6 +82,9 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' + + compileOnly(fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")) + compileOnly(fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")) } test { diff --git a/gradle.properties b/gradle.properties index 37d4aca9..6f3ff3aa 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,3 +3,4 @@ org.gradle.daemon=false mc_version=1.20.1 forge_version=47.1.65 mod_version=4.4.0 +jei_version=15.2.0.27 diff --git a/src/main/java/codechicken/lib/colour/Colour.java b/src/main/java/codechicken/lib/colour/Colour.java index 00edece3..61b22b05 100644 --- a/src/main/java/codechicken/lib/colour/Colour.java +++ b/src/main/java/codechicken/lib/colour/Colour.java @@ -134,6 +134,78 @@ public Colour set(float[] floats) { return set(floats[0], floats[1], floats[2], floats[3]); } + public Colour rF(float r) { + this.r = (byte) (255F * r); + return this; + } + + public Colour gF(float g) { + this.g = (byte) (255F * g); + return this; + } + + public Colour bF(float b) { + this.b = (byte) (255F * b); + return this; + } + + public Colour aF(float a) { + this.a = (byte) (255F * a); + return this; + } + + public Colour rF(int r) { + this.r = (byte) r; + return this; + } + + public Colour gF(int g) { + this.g = (byte) g; + return this; + } + + public Colour bF(int b) { + this.b = (byte) b; + return this; + } + + public Colour aF(int a) { + this.a = (byte) a; + return this; + } + + public float rF() { + return r / 255F; + } + + public float gF() { + return g / 255F; + } + + public float bF() { + return b / 255F; + } + + public float aF() { + return a / 255F; + } + + public int r() { + return r & 0xFF; + } + + public int g() { + return g & 0xFF; + } + + public int b() { + return b & 0xFF; + } + + public int a() { + return a & 0xFF; + } + /** * Flips a color between ABGR and RGBA. * diff --git a/src/main/java/codechicken/lib/compat/JEIPlugin.java b/src/main/java/codechicken/lib/compat/JEIPlugin.java new file mode 100644 index 00000000..c9608464 --- /dev/null +++ b/src/main/java/codechicken/lib/compat/JEIPlugin.java @@ -0,0 +1,37 @@ +package codechicken.lib.compat; + +import codechicken.lib.CodeChickenLib; +import codechicken.lib.gui.modular.ModularGuiContainer; +import mezz.jei.api.IModPlugin; +import mezz.jei.api.JeiPlugin; +import mezz.jei.api.gui.handlers.IGuiContainerHandler; +import mezz.jei.api.registration.IGuiHandlerRegistration; +import net.minecraft.client.renderer.Rect2i; +import net.minecraft.resources.ResourceLocation; + +import java.util.List; + +/** + * Created by brandon3055 on 31/12/2023 + */ +@JeiPlugin +public class JEIPlugin implements IModPlugin { + private static final ResourceLocation ID = new ResourceLocation(CodeChickenLib.MOD_ID, "jei_plugin"); + + public JEIPlugin() {} + + @Override + public ResourceLocation getPluginUid() { + return ID; + } + + @Override + public void registerGuiHandlers(IGuiHandlerRegistration registration) { + registration.addGuiContainerHandler(ModularGuiContainer.class, new IGuiContainerHandler<>() { + @Override + public List getGuiExtraAreas(ModularGuiContainer screen) { + return screen.getModularGui().getJeiExclusions().map(e -> e.getRectangle().toRect2i()).toList(); + } + }); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGui.java b/src/main/java/codechicken/lib/gui/modular/ModularGui.java new file mode 100644 index 00000000..b0a9d527 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/ModularGui.java @@ -0,0 +1,597 @@ +package codechicken.lib.gui.modular; + +import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.Slot; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.util.TriConsumer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Stream; + +/** + * The modular gui system is built around "Gui Elements" but those elements need to be rendered by a base parent element. That's what this class is. + * This class is essentially just a container for the root gui element. + *

+ * Created by brandon3055 on 18/08/2023 + * + * @see GuiProvider + * @see ContainerGuiProvider + */ +public class ModularGui implements GuiParent { + private static final Logger LOGGER = LogManager.getLogger(); + + private final GuiProvider provider; + private final GuiElement root; + + private boolean guiBuilt = false; + private boolean pauseScreen = false; + private boolean closeOnEscape = true; + private boolean renderBackground = true; + private boolean vanillaSlotRendering = false; + + private Font font; + private Minecraft mc; + private int screenWidth; + private int screenHeight; + private Screen screen; + private Screen parentScreen; + + private Component guiTitle = Component.empty(); + private ResourceLocation newCursor = null; + + private final Map> slotHandlers = new HashMap<>(); + private final List tickListeners = new ArrayList<>(); + private final List resizeListeners = new ArrayList<>(); + private final List closeListeners = new ArrayList<>(); + private final List> preClickListeners = new ArrayList<>(); + private final List> postClickListeners = new ArrayList<>(); + private final List> preKeyPressListeners = new ArrayList<>(); + private final List> postKeyPressListeners = new ArrayList<>(); + + private final List> jeiExclusions = new ArrayList<>(); + + /** + * @param provider The gui builder that will be used to construct this modular gui when the screen is initialized. + */ + public ModularGui(GuiProvider provider) { + this.provider = provider; + if (provider instanceof DynamicTextures textures) textures.makeTextures(DynamicTextures.DynamicTexture::guiTexturePath); + Minecraft mc = Minecraft.getInstance(); + updateScreenData(mc, mc.font, mc.getWindow().getGuiScaledWidth(), mc.getWindow().getGuiScaledHeight()); + try { + this.root = provider.createRootElement(this); + } catch (Throwable ex) { + LOGGER.error("An error occurred while constructing a modular gui", ex); + throw ex; + } + } + + public ModularGui(GuiProvider provider, Screen parentScreen) { + this(provider); + this.parentScreen = parentScreen; + } + + public void setScreen(Screen screen) { + this.screen = screen; + } + + public GuiProvider getProvider() { + return provider; + } + + //=== Modular Gui Setup ===// + + public void setGuiTitle(@NotNull Component guiTitle) { + this.guiTitle = guiTitle; + } + + @NotNull + public Component getGuiTitle() { + return guiTitle; + } + + /** + * @param pauseScreen Should a single-player game pause while this screen is open? + */ + public void setPauseScreen(boolean pauseScreen) { + this.pauseScreen = pauseScreen; + } + + public boolean isPauseScreen() { + return pauseScreen; + } + + public void setCloseOnEscape(boolean closeOnEscape) { + this.closeOnEscape = closeOnEscape; + } + + public boolean closeOnEscape() { + return closeOnEscape; + } + + /** + * Enable / disable the default screen background. (Default Enabled) + * This will be the usual darkened background when in-game, or the dirt background when not in game. + */ + public void renderScreenBackground(boolean renderBackground) { + this.renderBackground = renderBackground; + } + + public boolean renderBackground() { + return renderBackground; + } + + /** + * @return the root element to which content elements should be added. + */ + public GuiElement getRoot() { + return root instanceof ContentElement ? ((ContentElement) root).getContentElement() : root; + } + + public GuiElement getDirectRoot() { + return root; + } + + /** + * Sets up this gui to render like any other standards gui with the specified width and height. + * Meaning, the root element (usually the gui background image) will be centered on the screen, and will have the specified width and height. + *

+ * + * @param guiWidth Gui Width + * @param guiHeight Gui Height + * @see #initFullscreenGui() + */ + public ModularGui initStandardGui(int guiWidth, int guiHeight) { + root.constrain(GeoParam.WIDTH, Constraint.literal(guiWidth)); + root.constrain(GeoParam.HEIGHT, Constraint.literal(guiHeight)); + root.constrain(GeoParam.LEFT, Constraint.midPoint(get(GeoParam.LEFT), get(GeoParam.RIGHT), guiWidth / -2D)); + root.constrain(GeoParam.TOP, Constraint.midPoint(get(GeoParam.TOP), get(GeoParam.BOTTOM), guiHeight / -2D)); + return this; + } + + /** + * Sets up this gui to render as a full screen gui. + * Meaning the root element's geometry will match that of the underlying minecraft screen. + *

+ * + * @see #initStandardGui(int, int) + */ + public ModularGui initFullscreenGui() { + root.constrain(GeoParam.WIDTH, Constraint.match(get(GeoParam.WIDTH))); + root.constrain(GeoParam.HEIGHT, Constraint.match(get(GeoParam.HEIGHT))); + root.constrain(GeoParam.TOP, Constraint.match(get(GeoParam.TOP))); + root.constrain(GeoParam.LEFT, Constraint.match(get(GeoParam.LEFT))); + return this; + } + + /** + * By default, modular gui completely overrides vanillas default slot rendering. + * This ensures slots render within the depth constraint of the slot element and avoids situations where + * stacks in slots render on top of other parts of the gui. + * Meaning you can do things like hide slots by disabling the slot element, Or render elements on top of the slots. + *

+ * This method allow you to return full rendering control to vanilla if you need to for whatever reason. + */ + public void setVanillaSlotRendering(boolean vanillaSlotRendering) { + this.vanillaSlotRendering = vanillaSlotRendering; + } + + public boolean vanillaSlotRendering() { + return vanillaSlotRendering; + } + + //=== Modular Gui Passthrough Methods ===// + + /** + * Create a new {@link GuiRender} for the current render call. + * + * @param buffers BufferSource can be retried from {@link GuiGraphics} + * @return A new {@link GuiRender} for the current render call. + */ + public GuiRender createRender(MultiBufferSource.BufferSource buffers) { + return new GuiRender(mc, buffers); + } + + /** + * Primary render method for ModularGui. The screen implementing ModularGui must call this in its render method. + * Followed by the {@link #renderOverlay(GuiRender, float)} method to handle overlay rendering. + * + * @param render A new gui render call should be constructed for each frame via {@link #createRender(MultiBufferSource.BufferSource)} + */ + public void render(GuiRender render, float partialTicks) { + root.clearGeometryCache(); + double mouseX = computeMouseX(); + double mouseY = computeMouseY(); + root.render(render, mouseX, mouseY, partialTicks); + + //Ensure overlay is rendered at a depth of ether 400 or total element depth + 100 (whichever is greater) + double depth = root.getCombinedElementDepth(); + if (depth <= 300) { + render.pose().translate(0, 0, 400 - depth); + } else { + render.pose().translate(0, 0, 100); + } + } + + /** + * Handles gui overlay rendering. This is where things like tool tips are rendered. + * This should be called immediately after {@link #render(GuiRender, float)} + *

+ * The reason this is split out from {@link #render(GuiRender, float)} is to allow + * stack tool tips to override gui overlay rendering in {@link ModularGuiContainer} + * + * @param render This should be the same render instance that was passed to the previous {@link #render(GuiRender, float)} call. + * @return true if an overlay such as a tooltip is currently being drawn. + */ + public boolean renderOverlay(GuiRender render, float partialTicks) { + double mouseX = computeMouseX(); + double mouseY = computeMouseY(); + return root.renderOverlay(render, mouseX, mouseY, partialTicks, false); + } + + /** + * Primary update / tick method. Must be called from the tick method of the implementing screen. + */ + public void tick() { + newCursor = null; + double mouseX = computeMouseX(); + double mouseY = computeMouseY(); + root.updateMouseOver(mouseX, mouseY, false); + tickListeners.forEach(Runnable::run); + root.tick(mouseX, mouseY); + CursorHelper.setCursor(newCursor); + } + + /** + * Pass through for the mouseMoved event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param mouseX new mouse X position + * @param mouseY new mouse Y position + */ + public void mouseMoved(double mouseX, double mouseY) { + root.mouseMoved(mouseX, mouseY); + } + + /** + * Pass through for the mouseClicked event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param button Mouse Button + * @return true if this event has been consumed. + */ + public boolean mouseClicked(double mouseX, double mouseY, int button) { + preClickListeners.forEach(e -> e.accept(mouseX, mouseY, button)); + boolean consumed = root.mouseClicked(mouseX, mouseY, button, false); + if (!consumed) { + postClickListeners.forEach(e -> e.accept(mouseX, mouseY, button)); + } + return consumed; + } + + /** + * Pass through for the mouseReleased event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param button Mouse Button + * @return true if this event has been consumed. + */ + public boolean mouseReleased(double mouseX, double mouseY, int button) { + return root.mouseReleased(mouseX, mouseY, button, false); + } + + /** + * Pass through for the keyPressed event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param key the keyboard key that was pressed. + * @param scancode the system-specific scancode of the key + * @param modifiers bitfield describing which modifier keys were held down. + * @return true if this event has been consumed. + */ + public boolean keyPressed(int key, int scancode, int modifiers) { + preKeyPressListeners.forEach(e -> e.accept(key, scancode, modifiers)); + boolean consumed = root.keyPressed(key, scancode, modifiers, false); + if (!consumed) { + postKeyPressListeners.forEach(e -> e.accept(key, scancode, modifiers)); + } + return consumed; + } + + /** + * Pass through for the keyReleased event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param key the keyboard key that was released. + * @param scancode the system-specific scancode of the key + * @param modifiers bitfield describing which modifier keys were held down. + * @return true if this event has been consumed. + */ + public boolean keyReleased(int key, int scancode, int modifiers) { + return root.keyReleased(key, scancode, modifiers, false); + } + + /** + * Pass through for the charTyped event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param character The character typed. + * @param modifiers bitfield describing which modifier keys were held down. + * @return true if this event has been consumed. + */ + public boolean charTyped(char character, int modifiers) { + return root.charTyped(character, modifiers, false); + } + + /** + * Pass through for the mouseScrolled event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scroll Scroll direction and amount + * @return true if this event has been consumed. + */ + public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + return root.mouseScrolled(mouseX, mouseY, scroll, false); + } + + /** + * Must be called by the screen when this gui is closed. + */ + public void onGuiClose() { + CursorHelper.resetCursor(); + closeListeners.forEach(Runnable::run); + } + + //=== Basic Minecraft Stuff ===// + + protected void updateScreenData(Minecraft mc, Font font, int screenWidth, int screenHeight) { + this.mc = mc; + this.font = font; + this.screenWidth = screenWidth; + this.screenHeight = screenHeight; + } + + @Override + public void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + updateScreenData(mc, font, screenWidth, screenHeight); + root.clearGeometryCache(); + try { + root.onScreenInit(mc, font, screenWidth, screenHeight); + if (!guiBuilt) { + guiBuilt = true; + provider.buildGui(this); + } else { + resizeListeners.forEach(Runnable::run); + } + } catch (Throwable ex) { + //Because it seems the default behavior is to just silently consume init errors... Not helpful! + LOGGER.error("An error occurred while building a modular gui", ex); + throw ex; + } + } + + @Override + public Minecraft mc() { + return mc; + } + + @Override + public Font font() { + return font; + } + + @Override + public int scaledScreenWidth() { + return screenWidth; + } + + @Override + public int scaledScreenHeight() { + return screenHeight; + } + + @Override + public ModularGui getModularGui() { + return this; + } + + /** + * Returns the Screen housing this {@link ModularGui} + * With custom ModularGui implementations this may be null. + */ + public Screen getScreen() { + return screen; + } + + @Nullable + public Screen getParentScreen() { + return parentScreen; + } + + //=== Child Elements ===// + + @Override + public List> getChildren() { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public void addChild(GuiElement child) { + if (root == null) { //If child is null, we are adding the root element. + child.initElement(this); + return; + } + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public ModularGui addChild(Consumer createChild) { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public void adoptChild(GuiElement child) { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public void removeChild(GuiElement child) { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + //=== Geometry ===// + //The geometry of the base ModularGui class should always match the underlying minecraft screen. + + @Override + public double xMin() { + return 0; + } + + @Override + public double xMax() { + return screenWidth; + } + + @Override + public double xSize() { + return screenWidth; + } + + @Override + public double yMin() { + return 0; + } + + @Override + public double yMax() { + return screenHeight; + } + + @Override + public double ySize() { + return screenHeight; + } + + //=== Other ===// + + public double computeMouseX() { + return mc.mouseHandler.xpos() * (double) mc.getWindow().getGuiScaledWidth() / (double) mc.getWindow().getScreenWidth(); + } + + public double computeMouseY() { + return mc.mouseHandler.ypos() * (double) mc.getWindow().getGuiScaledHeight() / (double) mc.getWindow().getScreenHeight(); + } + + /** + * Provides a way to later retrieve the gui element responsible for positioning and rendering a slot. + */ + public void setSlotHandler(Slot slot, GuiElement handler) { + if (slotHandlers.containsKey(slot)) throw new IllegalStateException("A gui slot can only have a single handler!"); + slotHandlers.put(slot, handler); + } + + /** + * Returns the gui element responsible for managing a gui slot. + */ + public GuiElement getSlotHandler(Slot slot) { + return slotHandlers.get(slot); + } + + /** + * Sets the current mouse cursor. + * The cursor is reset at the end of each UI tick so this must be set every tick for as long as you want your custom cursor to be active. + * */ + public void setCursor(ResourceLocation cursor) { + this.newCursor = cursor; + } + + /** + * Add an element to the list of jei exclusions. + * Use this for any elements that render outside the normal gui bounds. + * This will ensure JEI does not try to render on top of these elements. + */ + public void jeiExclude(GuiElement element) { + if (!jeiExclusions.contains(element)) { + jeiExclusions.add(element); + } + } + + /** + * Remove an element from the list of jei exclusions. + */ + public void removeJEIExclude(GuiElement element) { + jeiExclusions.remove(element); + } + + public FastStream> getJeiExclusions() { + return FastStream.of(jeiExclusions).filter(GuiElement::isEnabled); + } + + /** + * Allows you to attach a callback that will be fired at the start of each gui tick. + */ + public void onTick(Runnable onTick) { + tickListeners.add(onTick); + } + + /** + * Allows you to attach a callback that will be fired when the parent screen is resized. + */ + public void onResize(Runnable onResize) { + resizeListeners.add(onResize); + } + + public void onClose(Runnable onClose) { + closeListeners.add(onClose); + } + + /** + * Allows you to attach a callback that will be fired on mouse click, before the click is handled by the rest of the gui. + */ + public void onMouseClickPre(TriConsumer onClick) { + preClickListeners.add(onClick); + } + + /** + * Allows you to attach a callback that will be fired on mouse click, after the click has been handled by the rest of the gui. + * Will only be fired if the event was not consumed by an element. + */ + public void onMouseClickPost(TriConsumer onClick) { + postClickListeners.add(onClick); + } + + + /** + * Allows you to attach a callback that will be fired on key press, before the is handled by the rest of the gui. + */ + public void onKeyPressPre(TriConsumer preKeyPress) { + preKeyPressListeners.add(preKeyPress); + } + + /** + * Allows you to attach a callback that will be fired on key press, after it has been handled by the rest of the gui. + * Will only be fired if the event was not consumed by an element. + */ + public void onKeyPressPost(TriConsumer postKeyPress) { + postKeyPressListeners.add(postKeyPress); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java new file mode 100644 index 00000000..0063b6a6 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -0,0 +1,280 @@ +package codechicken.lib.gui.modular; + +import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; +import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import net.minecraft.ChatFormatting; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Container screen implementation for {@link ModularGui}. + * + *

+ * Created by brandon3055 on 08/09/2023 + */ +public class ModularGuiContainer extends AbstractContainerScreen implements ContainerScreenAccess { + + public final ModularGui modularGui; + + public ModularGuiContainer(T containerMenu, Inventory inventory, ContainerGuiProvider provider) { + super(containerMenu, inventory, Component.empty()); + provider.setMenuAccess(this); + this.modularGui = new ModularGui(provider); + this.modularGui.setScreen(this); + } + + public ModularGui getModularGui() { + return modularGui; + } + + @NotNull + @Override + public Component getTitle() { + return modularGui.getGuiTitle(); + } + + @Override + public boolean shouldCloseOnEsc() { + return modularGui.closeOnEscape(); + } + + @Override + protected void init() { + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void resize(@NotNull Minecraft minecraft, int width, int height) { + super.resize(minecraft, width, height); + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + GuiElement root = modularGui.getRoot(); + topPos = (int) root.getValue(GeoParam.TOP); + leftPos = (int) root.getValue(GeoParam.LEFT); + imageWidth = (int) root.getValue(GeoParam.WIDTH); + imageHeight = (int) root.getValue(GeoParam.HEIGHT); + + if (modularGui.renderBackground()) { + renderBackground(graphics); + } + GuiRender render = modularGui.createRender(graphics.bufferSource()); + modularGui.render(render, partialTicks); + + super.render(graphics, mouseX, mouseY, partialTicks); + + if (!handleFloatingItemRender(render, mouseX, mouseY) && !renderHoveredStackToolTip(render, mouseX, mouseY)) { + modularGui.renderOverlay(render, partialTicks); + } + } + + protected boolean handleFloatingItemRender(GuiRender render, int mouseX, int mouseY) { + if (modularGui.vanillaSlotRendering()) return false; + boolean ret = false; + + ItemStack stack = draggingItem.isEmpty() ? menu.getCarried() : draggingItem; + if (!stack.isEmpty()) { + int yOffset = draggingItem.isEmpty() ? 8 : 16; + String countOverride = null; + if (!draggingItem.isEmpty() && isSplittingStack) { + stack = stack.copyWithCount(Mth.ceil((float) stack.getCount() / 2.0F)); + } else if (isQuickCrafting && quickCraftSlots.size() > 1) { + stack = stack.copyWithCount(this.quickCraftingRemainder); + if (stack.isEmpty()) { + countOverride = ChatFormatting.YELLOW + "0"; + } + } + renderFloatingItem(render, stack, mouseX - 8, mouseY - yOffset, countOverride); + ret = true; + } + + if (!this.snapbackItem.isEmpty()) { + float anim = (float) (Util.getMillis() - this.snapbackTime) / 100.0F; + if (anim >= 1.0F) { + anim = 1.0F; + this.snapbackItem = ItemStack.EMPTY; + } + + int xDist = snapbackEnd.x - snapbackStartX; + int yDist = snapbackEnd.y - snapbackStartY; + int xPos = snapbackStartX + (int) ((float) xDist * anim); + int yPos = snapbackStartY + (int) ((float) yDist * anim); + renderFloatingItem(render, snapbackItem, xPos + leftPos, yPos + topPos, null); + ret = true; + } + + return ret; + } + + protected boolean renderHoveredStackToolTip(GuiRender guiGraphics, int mouseX, int mouseY) { + if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) { + GuiElement handler = modularGui.getSlotHandler(hoveredSlot); + if (handler != null && handler.blockMouseOver(handler, mouseX, mouseY)) { + return false; + } + ItemStack itemStack = this.hoveredSlot.getItem(); + guiGraphics.toolTipWithImage(this.getTooltipFromContainerItem(itemStack), itemStack.getTooltipImage(), mouseX, mouseY); + return true; + } + return false; + } + + @Override + protected void containerTick() { + modularGui.tick(); + } + + @Override + public void removed() { + super.removed(); + modularGui.onGuiClose(); + } + + //=== Input Pass-though ===// + + @Override + public void mouseMoved(double mouseX, double mouseY) { + modularGui.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + return modularGui.mouseClicked(mouseX, mouseY, button) || super.mouseClicked(mouseX, mouseY, button); + } + + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button) { + return modularGui.mouseReleased(mouseX, mouseY, button) || super.mouseReleased(mouseX, mouseY, button); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + return modularGui.mouseScrolled(mouseX, mouseY, scroll) || super.mouseScrolled(mouseX, mouseY, scroll); + } + + @Override + public boolean keyPressed(int key, int scancode, int modifiers) { + return modularGui.keyPressed(key, scancode, modifiers) || super.keyPressed(key, scancode, modifiers); + } + + @Override + public boolean keyReleased(int key, int scancode, int modifiers) { + return modularGui.keyReleased(key, scancode, modifiers) || super.keyReleased(key, scancode, modifiers); + } + + @Override + public boolean charTyped(char character, int modifiers) { + return modularGui.charTyped(character, modifiers) || super.charTyped(character, modifiers); + } + + //=== AbstractContainerMenu Overrides ===// + + @Override + protected void renderBg(GuiGraphics guiGraphics, float f, int i, int j) { + } + + @Override + public void renderSlot(GuiGraphics guiGraphics, Slot slot) { + if (modularGui.vanillaSlotRendering()) super.renderSlot(guiGraphics, slot); + } + + //Modular gui friendly version of the slot render + @Override + public void renderSlot(GuiRender render, Slot slot) { + if (modularGui.vanillaSlotRendering()) return; + int slotX = slot.x + leftPos; + int slotY = slot.y + topPos; + ItemStack slotStack = slot.getItem(); + boolean dragingToSlot = false; + boolean dontRenderItem = slot == this.clickedSlot && !this.draggingItem.isEmpty() && !this.isSplittingStack; + + ItemStack carriedStack = this.menu.getCarried(); + String countString = null; + if (slot == this.clickedSlot && !this.draggingItem.isEmpty() && this.isSplittingStack && !slotStack.isEmpty()) { + slotStack = slotStack.copyWithCount(slotStack.getCount() / 2); + } else if (this.isQuickCrafting && this.quickCraftSlots.contains(slot) && !carriedStack.isEmpty()) { + if (this.quickCraftSlots.size() == 1) { + return; + } + + if (AbstractContainerMenu.canItemQuickReplace(slot, carriedStack, true) && this.menu.canDragTo(slot)) { + dragingToSlot = true; + int k = Math.min(carriedStack.getMaxStackSize(), slot.getMaxStackSize(carriedStack)); + int l = slot.getItem().isEmpty() ? 0 : slot.getItem().getCount(); + int m = AbstractContainerMenu.getQuickCraftPlaceCount(this.quickCraftSlots, this.quickCraftingType, carriedStack) + l; + if (m > k) { + m = k; + countString = ChatFormatting.YELLOW.toString() + k; + } + + slotStack = carriedStack.copyWithCount(m); + } else { + this.quickCraftSlots.remove(slot); + this.recalculateQuickCraftRemaining(); + } + } + + if (!dontRenderItem) { + if (dragingToSlot) { + //Highlights slots when doing a drag place operation. + render.fill(slotX, slotY, slotX + 16, slotY + 16, 0x80ffffff); + } + render.renderItem(slotStack, slotX, slotY, 16, slot.x + (slot.y * this.imageWidth)); //TODO May want a random that does not change if the slot is moved. + render.renderItemDecorations(slotStack, slotX, slotY, countString); + } + } + + @Override //Disable vanilla title and inventory name rendering + protected void renderLabels(GuiGraphics guiGraphics, int i, int j) { + } + + @Override + public void renderFloatingItem(GuiGraphics guiGraphics, ItemStack itemStack, int i, int j, String string) { + if (modularGui.vanillaSlotRendering()) super.renderFloatingItem(guiGraphics, itemStack, i, j, string); + } + + public void renderFloatingItem(GuiRender render, ItemStack itemStack, int x, int y, String string) { + render.pose().pushPose(); + render.pose().translate(0.0F, 0.0F, 50F); + render.renderItem(itemStack, x, y); + render.renderItemDecorations(itemStack, x, y - (this.draggingItem.isEmpty() ? 0 : 8), string); + render.pose().popPose(); + } + + @Nullable + @Override + public Slot findSlot(double mouseX, double mouseY) { + Slot slot = super.findSlot(mouseX, mouseY); + if (slot == null) return null; + GuiElement handler = modularGui.getSlotHandler(slot); + if (handler != null && (!handler.isEnabled() || !handler.isMouseOver())) { + return null; + } + return slot; + } + + @Override + protected void slotClicked(Slot slot, int i, int j, ClickType clickType) { + if (slot != null) { + GuiElement handler = modularGui.getSlotHandler(slot); + if (handler != null && !handler.isEnabled()) return; + } + super.slotClicked(slot, i, j, clickType); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java new file mode 100644 index 00000000..10fd1060 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java @@ -0,0 +1,121 @@ +package codechicken.lib.gui.modular; + +import codechicken.lib.gui.modular.lib.GuiProvider; +import codechicken.lib.gui.modular.lib.GuiRender; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; + +/** + * A simple ModularGui screen implementation. + * This is simply a wrapper for a {@link ModularGui} that takes a {@link GuiProvider} + * This should be suitable for most basic gui screens. + *

+ * Created by brandon3055 on 19/08/2023 + */ +public class ModularGuiScreen extends Screen { + + protected final ModularGui modularGui; + + public ModularGuiScreen(GuiProvider provider) { + super(Component.empty()); + this.modularGui = new ModularGui(provider); + this.modularGui.setScreen(this); + } + + public ModularGuiScreen(GuiProvider builder, Screen parentScreen) { + super(Component.empty()); + this.modularGui = new ModularGui(builder, parentScreen); + this.modularGui.setScreen(this); + } + + public ModularGui getModularGui() { + return modularGui; + } + + @NotNull + @Override + public Component getTitle() { + return modularGui.getGuiTitle(); + } + + @Override + public boolean isPauseScreen() { + return modularGui.isPauseScreen(); + } + + @Override + public boolean shouldCloseOnEsc() { + return modularGui.closeOnEscape(); + } + + @Override + protected void init() { + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void resize(@NotNull Minecraft minecraft, int width, int height) { + super.resize(minecraft, width, height); + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + if (modularGui.renderBackground()) { + renderBackground(graphics); + } + GuiRender render = modularGui.createRender(graphics.bufferSource()); + modularGui.render(render, partialTicks); + modularGui.renderOverlay(render, partialTicks); + } + + @Override + public void tick() { + modularGui.tick(); + } + + @Override + public void removed() { + modularGui.onGuiClose(); + } + + //=== Input Pass-though ===// + + @Override + public void mouseMoved(double mouseX, double mouseY) { + modularGui.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + return modularGui.mouseClicked(mouseX, mouseY, button) || super.mouseClicked(mouseX, mouseY, button); + } + + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button) { + return modularGui.mouseReleased(mouseX, mouseY, button) || super.mouseReleased(mouseX, mouseY, button); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + return modularGui.mouseScrolled(mouseX, mouseY, scroll) || super.mouseScrolled(mouseX, mouseY, scroll); + } + + @Override + public boolean keyPressed(int key, int scancode, int modifiers) { + return modularGui.keyPressed(key, scancode, modifiers) || super.keyPressed(key, scancode, modifiers); + } + + @Override + public boolean keyReleased(int key, int scancode, int modifiers) { + return modularGui.keyReleased(key, scancode, modifiers) || super.keyReleased(key, scancode, modifiers); + } + + @Override + public boolean charTyped(char character, int modifiers) { + return modularGui.charTyped(character, modifiers) || super.charTyped(character, modifiers); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java new file mode 100644 index 00000000..b8df4d2b --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java @@ -0,0 +1,335 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.core.Holder; +import net.minecraft.network.chat.Component; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundEvents; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Created by brandon3055 on 28/08/2023 + */ +public class GuiButton extends GuiElement { + public static final int LEFT_CLICK = 0; + public static final int RIGHT_CLICK = 1; + public static final int MIDDLE_CLICK = 2; + + private final Map onClick = new HashMap<>(); + private final Map onPress = new HashMap<>(); + private boolean pressed = false; + private Holder pressSound = SoundEvents.UI_BUTTON_CLICK; + private Holder releaseSound = null; + private Supplier disabled = () -> false; + private Supplier toggleState; + private GuiText label = null; + + /** + * In its default state this is a blank, invisible element that can fire callbacks when pressed. + * To make an actual usable button, ether use one of the builtin static create methods, + * Or add your own elements to make this button look and function in a way that meets your needs. + * + * @param parent parent {@link GuiParent}. + */ + public GuiButton(@NotNull GuiParent parent) { + super(parent); + } + + /** + * Creates a new gui button that looks and acts exactly like a standard vanilla button. + */ + public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Component label, Runnable onClick) { + return vanilla(parent, label).onClick(onClick); + } + + /** + * Creates a new gui button that looks and acts exactly like a standard vanilla button. + */ + public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Component label) { + GuiButton button = new GuiButton(parent); + GuiTexture texture = new GuiTexture(button, CCGuiTextures.getter(() -> button.toggleState() ? "dynamic/button_highlight" : "dynamic/button_vanilla")); + texture.dynamicTexture(); + GuiRectangle highlight = new GuiRectangle(button).border(() -> button.hoverTime() > 0 ? 0xFFFFFFFF : 0); + + Constraints.bind(texture, button); + Constraints.bind(highlight, button); + + if (label != null) { + button.setLabel(new GuiText(button, label)); + Constraints.bind(button.getLabel(), button, 0, 2, 0, 2); + } + + return button; + } + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(@NotNull GuiParent parent, Component label, Runnable onPress) { + return vanillaAnimated(parent, label == null ? null : () -> label, onPress); + } + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(@NotNull GuiParent parent, @Nullable Supplier label, Runnable onPress) { + return vanillaAnimated(parent, label).onPress(onPress); + } + + //TODO Could use a quad-sliced texture for this. + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(@NotNull GuiParent parent, Component label) { + return vanillaAnimated(parent, label == null ? null : () -> label); + } + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(@NotNull GuiParent parent, @Nullable Supplier label) { + GuiButton button = new GuiButton(parent); + GuiTexture texture = new GuiTexture(button, CCGuiTextures.getter(() -> button.toggleState() || button.isPressed() ? "dynamic/button_pressed" : "dynamic/button_vanilla")); + texture.dynamicTexture(); + GuiRectangle highlight = new GuiRectangle(button).border(() -> button.isMouseOver() ? 0xFFFFFFFF : 0); + + Constraints.bind(texture, button); + Constraints.bind(highlight, button); + + if (label != null) { + button.setLabel(new GuiText(button, label) + .constrain(TOP, Constraint.relative(button.get(TOP), () -> button.isPressed() ? -0.5D : 0.5D).precise()) + .constrain(LEFT, Constraint.relative(button.get(LEFT), () -> button.isPressed() ? 1.5D : 2.5D).precise()) + .constrain(WIDTH, Constraint.relative(button.get(WIDTH), -4)) + .constrain(HEIGHT, Constraint.match(button.get(HEIGHT))) + ); + } + + return button; + } + + /** + * Super simple button that is just a coloured rectangle with a label. + */ + public static GuiButton flatColourButton(@NotNull GuiParent parent, @Nullable Supplier label, Function buttonColour) { + return flatColourButton(parent, label, buttonColour, null); + } + + /** + * Super simple button that is just a coloured rectangle with a label. + */ + public static GuiButton flatColourButton(@NotNull GuiParent parent, @Nullable Supplier label, Function buttonColour, @Nullable Function borderColour) { + GuiButton button = new GuiButton(parent); + GuiRectangle background = new GuiRectangle(button) + .fill(() -> buttonColour.apply(button.isMouseOver() || button.toggleState() || button.isPressed())) + .border(borderColour == null ? null : () -> borderColour.apply(button.isMouseOver() || button.toggleState() || button.isPressed())); + Constraints.bind(background, button); + + if (label != null) { + GuiText text = new GuiText(button, label); + button.setLabel(text); + Constraints.bind(text, button, 0, 2, 0, 2); + } + + return button; + } + + /** + * When creating buttons with labels, use this method to store a reference to the label in the button fore easy retrival later. + * + * @param label The button label. + */ + public GuiButton setLabel(GuiText label) { + this.label = label; + return this; + } + + /** + * @return The buttons label element, If it has one. + */ + public GuiText getLabel() { + return label; + } + + /** + * This event is fired immediately when this button is left-clicked. + * This is the logic used by most vanilla gui buttons. + * + * @see #onPress(Runnable) + */ + public GuiButton onClick(Runnable onClick) { + return onClick(onClick, LEFT_CLICK); + } + + /** + * This event is fired immediately when this button is clicked with the specified mouse button. + * This is the logic used by most vanilla gui buttons. + * Note: You can apply one listener per mouse button. + * + * @see #onPress(Runnable, int) + */ + public GuiButton onClick(Runnable onClick, int mouseButton) { + this.onClick.put(mouseButton, onClick); + return this; + } + + /** + * This event is fired when the button is pressed and then released using the left mosue button. + * The event is only fired if the cursor is still over the button when left click is released. + * This is the standard logic for most buttons in the world, but not vanillas. + * Note: You can apply one listener per mouse button. + * + * @see #onPress(Runnable, int) + */ + public GuiButton onPress(Runnable onPress) { + return onPress(onPress, LEFT_CLICK); + } + + /** + * This event is fired when the button is pressed and then released using the specified mouse button. + * The event is only fired if the cursor is still over the button when left click is released. + * This is the standard logic for most buttons in the world, but not vanillas. + * + * @see #onPress(Runnable, int) + */ + public GuiButton onPress(Runnable onPress, int mouseButton) { + this.onPress.put(mouseButton, onPress); + return this; + } + + /** + * Allows set the disabled status of this button + * Note: This is not the same as {@link #setEnabled(boolean)} the "enabled" allows you to completely disable an element. + * This "disabled" status is specific to {@link GuiButton}, + * When disabled via this method a button is still visible but greyed out / not clickable. + */ + public GuiButton setDisabled(boolean disabled) { + this.disabled = () -> disabled; + return this; + } + + /** + * Allows you to install a suppler that controls the disabled state of this button. + * Note: This is not the same as {@link #setEnabled(Supplier)} the "enabled" allows you to completely disable an element. + * This "disabled" status is specific to {@link GuiButton}, + * When disabled via this method a button is still visible but greyed out / not clickable. + */ + public GuiButton setDisabled(Supplier disabled) { + this.disabled = disabled; + return this; + } + + /** + * Allows this button to be used as a toggle or radio button. + * This method allows you to install a suppler that controls the current "selected / toggled" state. + * + * @param toggleState supplier that indicates weather or not this button should currently render as pressed/selected. + */ + public GuiButton setToggleMode(@Nullable Supplier toggleState) { + this.toggleState = toggleState; + return this; + } + + /** + * @return the "disabled" status. + * @see #setDisabled(boolean) + * @see #setDisabled(Supplier) + */ + public boolean isDisabled() { + return disabled.get(); + } + + /** + * @return true if this button is currently pressed by the user (left click held down on button) + */ + public boolean isPressed() { + return pressed && hoverTime() > 0; + } + + public boolean toggleState() { + return toggleState != null && toggleState.get(); + } + + /** + * Sets the sound to be played when this button is pressed. + */ + public GuiButton setPressSound(Holder pressSound) { + this.pressSound = pressSound; + return this; + } + + /** + * Sets the sound to be played when this button is released. + */ + public GuiButton setReleaseSound(Holder releaseSound) { + this.releaseSound = releaseSound; + return this; + } + + public Holder getPressSound() { + return pressSound; + } + + public Holder getReleaseSound() { + return releaseSound; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (!isMouseOver() || isDisabled()) return false; + Runnable onClick = this.onClick.get(button); + Runnable onPress = this.onPress.get(button); + if (onClick == null && onPress == null) return false; + pressed = true; + hoverTime = 1; + + boolean consume = false; + if (onClick != null) { + onClick.run(); + consume = true; + } + if (onPress != null) { + consume = true; + } + + if (getPressSound() != null) { + mc().getSoundManager().play(SimpleSoundInstance.forUI(getPressSound(), 1F)); + } + return consume; + } + + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + consumed = super.mouseReleased(mouseX, mouseY, button, consumed); + if (!pressed) return consumed; + Runnable onClick = this.onClick.get(button); + Runnable onPress = this.onPress.get(button); + if (onClick == null && onPress == null) return consumed; + hoverTime = 1; + + if (!isDisabled() && isMouseOver()) { + if (pressed && onPress != null) { + onPress.run(); + consumed = true; + } + if (getReleaseSound() != null && (toggleState == null || !toggleState.get())) { + mc().getSoundManager().play(SimpleSoundInstance.forUI(getReleaseSound(), 1F)); + } + } + pressed = false; + return consumed; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java new file mode 100644 index 00000000..c576a7e8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java @@ -0,0 +1,232 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.colour.Colour; +import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.geometry.Axis; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Created by brandon3055 on 17/11/2023 + */ +public class GuiColourPicker extends GuiManipulable { + + private ColourState colourState = ColourState.create(); + private GuiButton okButton; + private GuiButton cancelButton; + + public GuiColourPicker(@NotNull GuiParent parent) { + super(parent); + } + + public static GuiColourPicker create(GuiParent guiParent, ColourState colourState) { + return create(guiParent, colourState, true); + } + + public static GuiColourPicker create(GuiParent guiParent, ColourState colourState, boolean hasAlpha) { + Colour initialColour = colourState.getColour(); + GuiColourPicker picker = new GuiColourPicker(guiParent.getModularGui().getRoot()); + picker.setOpaque(true); + picker.setColourState(colourState); + Constraints.size(picker, 80, hasAlpha ? 80 : 68); + + GuiRectangle background = GuiRectangle.toolTipBackground(picker.getContentElement()); + Constraints.bind(background, picker.getContentElement()); + + var hexField = GuiTextField.create(background, 0xFF000000, 0xFF505050, 0xe0e0e0); + hexField.field() + .setTextState(picker.getTextState()) + .setMaxLength(hasAlpha ? 8 : 6) + .setFilter(s -> s.isEmpty() || validHex(s)); + hexField.container() + .setOpaque(true) + .constrain(HEIGHT, literal(12)) + .constrain(TOP, relative(background.get(TOP), 4)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + SliderBG slider = makeSlider(background, 0xFFFF0000, picker.sliderStateRed()) + .constrain(TOP, relative(hexField.container().get(BOTTOM), 2)); + + slider = makeSlider(background, 0xFF00FF00, picker.sliderStateGreen()) + .constrain(TOP, relative(slider.get(BOTTOM), 1)); + + slider = makeSlider(background, 0xFF0000FF, picker.sliderStateBlue()) + .constrain(TOP, relative(slider.get(BOTTOM), 1)); + + if (hasAlpha) { + slider = makeSlider(background, 0xFFFFFFFF, picker.sliderStateAlpha()) + .constrain(TOP, relative(slider.get(BOTTOM), 1)); + } else { + colourState.set(colourState.getColour().aF(0)); + } + + ColourPreview preview = new ColourPreview(background, () -> hasAlpha ? colourState.get() : (colourState.get() | 0xFF000000)) + .setOpaque(true) + .constrain(HEIGHT, literal(6)) + .constrain(TOP, relative(slider.get(BOTTOM), 2)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + picker.cancelButton = GuiButton.flatColourButton(background, () -> Component.translatable("gui.cancel"), e -> 0xFF000000, e -> e ? 0xFF777777 : 0xFF555555) + .setOpaque(true) + .onPress(() -> { + colourState.set(initialColour); + picker.getParent().removeChild(picker); + }) + .constrain(HEIGHT, literal(10)) + .constrain(TOP, relative(preview.get(BOTTOM), 2)) + .constrain(LEFT, midPoint(background.get(LEFT), background.get(RIGHT), -4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + picker.okButton = GuiButton.flatColourButton(background, () -> Component.translatable("gui.ok"), e -> 0xFF000000, e -> e ? 0xFF777777 : 0xFF555555) + .setOpaque(true) + .onPress(() -> picker.getParent().removeChild(picker)) + .constrain(HEIGHT, literal(10)) + .constrain(TOP, relative(preview.get(BOTTOM), 2)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, dynamic(() -> picker.cancelButton.isEnabled() ? picker.cancelButton.xMin() - 2 : background.xMax() - 4)); + + return picker; + } + + public static SliderBG makeSlider(GuiElement background, int colour, SliderState state) { + SliderBG slideBG = new SliderBG(background, 0xFF505050, 0x30FFFFFF) + .setOpaque(true) + .constrain(HEIGHT, literal(9)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + GuiSlider slider = new GuiSlider(slideBG, Axis.X) + .setSliderState(state); + Constraints.bind(slider, slideBG, 0, 1, 0, 1); + slideBG.slider = slider; + + GuiRectangle handle = new GuiRectangle(slider) + .fill(colour) + .border(0xFF000000) + .borderWidth(0.5) + .constrain(WIDTH, literal(4)); + + slider.installSlider(handle) + .bindSliderWidth(); + + return slideBG; + } + + private static boolean validHex(String value) { + try { + Integer.parseUnsignedInt(value, 16); + return true; + } catch (Throwable ignored) { + return false; + } + } + + public static class SliderBG extends GuiElement implements BackgroundRender { + public int colour; + public int highlight; + public GuiSlider slider; + public boolean pressed = false; + + public SliderBG(@NotNull GuiParent parent, int colour, int highlight) { + super(parent); + this.colour = colour; + this.highlight = highlight; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + pressed = button == 0; + return super.mouseClicked(mouseX, mouseY, button, consumed); + } + + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + if (button == 0) pressed = false; + return super.mouseReleased(mouseX, mouseY, button, consumed); + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + render.fill(xMin(), yMin(), xMin() + 1, yMax(), colour); + render.fill(xMax() - 1, yMin(), xMax(), yMax(), colour); + render.fill(xMin() + 1, yCenter() - 0.5, xMax() - 1, yCenter() + 0.5, colour); + + if ((isMouseOver() && !pressed) || slider.isDragging()) { + render.rect(getRectangle(), highlight); + } + } + } + + public static class ColourPreview extends GuiElement implements BackgroundRender { + private final Supplier colour; + public int colourA = 0xFF999999; + public int colourB = 0xFF666666; + + public ColourPreview(@NotNull GuiParent parent, Supplier colour) { + super(parent); + this.colour = colour; + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + render.pushScissorRect(xMin(), yMin(), xSize(), ySize()); + for (int x = 0; xMin() + (x * 2) < xMax(); x++) { + for (int y = 0; yMin() + (y * 2) < yMax(); y++) { + int col = (y & 1) == 0 ? ((x & 1) == 0 ? colourA : colourB) : ((x & 1) == 0 ? colourB : colourA); + render.rect(xMin() + (x * 2), yMin() + (y * 2), 2, 2, col); + } + } + render.popScissor(); + render.rect(getRectangle(), colour.get()); + } + } + + public GuiColourPicker setColourState(ColourState colourState) { + this.colourState = colourState; + return this; + } + + public ColourState getState() { + return colourState; + } + + public SliderState sliderStateAlpha() { + return SliderState.forSlider(() -> (double) colourState.getColour().aF(), e -> colourState.set(colourState.getColour().aF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + } + + public SliderState sliderStateRed() { + return SliderState.forSlider(() -> (double) colourState.getColour().rF(), e -> colourState.set(colourState.getColour().rF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + } + + public SliderState sliderStateGreen() { + return SliderState.forSlider(() -> (double) colourState.getColour().gF(), e -> colourState.set(colourState.getColour().gF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + } + + public SliderState sliderStateBlue() { + return SliderState.forSlider(() -> (double) colourState.getColour().bF(), e -> colourState.set(colourState.getColour().bF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + } + + public TextState getTextState() { + return TextState.create(colourState::getHexColour, colourState::setHexColour); + } + + public GuiButton getOkButton() { + return okButton; + } + + /** + * If cancel button is disabled, ok button will automatically resize. + */ + public GuiButton getCancelButton() { + return cancelButton; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java new file mode 100644 index 00000000..77c2b343 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java @@ -0,0 +1,135 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.network.chat.Component; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Context menus get added to the root element when they are created so as long as no new elements are added after the menu is opened, + * the menu will always be on top. + * It will also automatically close when an option is selected, or when the user clicks outside the context menu. + *

+ * Created by brandon3055 on 21/11/2023 + */ +public class GuiContextMenu extends GuiElement { + + private BiFunction, GuiButton> buttonBuilder = (menu, label) -> GuiButton.flatColourButton(menu, label, hover -> hover ? 0xFF475b6a : 0xFF151515).constrain(HEIGHT, literal(12)); + private final Map, Runnable> options = new HashMap<>(); + private final Map, Supplier>> tooltips = new HashMap<>(); + private final List buttons = new ArrayList<>(); + private boolean closeOnItemClicked = true; + private boolean closeOnOutsideClick = true; + + public GuiContextMenu(ModularGui gui) { + super(gui.getRoot()); + } + + public static GuiContextMenu tooltipStyleMenu(GuiParent parent) { + GuiContextMenu menu = new GuiContextMenu(parent.getModularGui()); + Constraints.bind(GuiRectangle.toolTipBackground(menu), menu); + return menu; + } + + public GuiContextMenu setCloseOnItemClicked(boolean closeOnItemClicked) { + this.closeOnItemClicked = closeOnItemClicked; + return this; + } + + public GuiContextMenu setCloseOnOutsideClick(boolean closeOnOutsideClick) { + this.closeOnOutsideClick = closeOnOutsideClick; + return this; + } + + /** + * Only height should be constrained, with will be set automatically to accommodate the provided label. + */ + public GuiContextMenu setButtonBuilder(BiFunction, GuiButton> buttonBuilder) { + this.buttonBuilder = buttonBuilder; + return this; + } + + public GuiContextMenu addOption(Supplier label, Runnable action) { + options.put(label, action); + rebuildButtons(); + return this; + } + + public GuiContextMenu addOption(Supplier label, Supplier> tooltip, Runnable action) { + options.put(label, action); + tooltips.put(label, tooltip); + rebuildButtons(); + return this; + } + + public GuiContextMenu addOption(Supplier label, List tooltip, Runnable action) { + return addOption(label, () -> tooltip, action); + } + + public GuiContextMenu addOption(Supplier label, Runnable action, Component... tooltip) { + return addOption(label, () -> List.of(tooltip), action); + } + + private void rebuildButtons() { + buttons.forEach(this::removeChild); + buttons.clear(); + + //Menu options can be dynamic so the width constraint needs to be dynamic. + //This is probably a little expensive, but its only while a context menu is open. + constrain(WIDTH, dynamic(() -> FastStream.of(options.keySet()).map(Supplier::get).intSum(font()::width) + 6D + 4D)); + + double height = 3; + for (Supplier label : options.keySet()) { + Runnable action = options.get(label); + GuiButton button = buttonBuilder.apply(this, label) + .onPress(action) + .constrain(TOP, relative(get(TOP), height)) + .constrain(LEFT, relative(get(LEFT), 3)) + .constrain(RIGHT, relative(get(RIGHT), -3)); + if (tooltips.containsKey(label)) { + button.setTooltip(tooltips.get(label)); + } + button.getLabel().setScroll(false); + buttons.add(button); + height += button.ySize(); + } + constrain(HEIGHT, literal(height + 3)); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + consumed = super.mouseClicked(mouseX, mouseY, button, consumed); + if (isMouseOver() || consumed) { + if (consumed && closeOnItemClicked) { + close(); + } + return true; + } else if (closeOnOutsideClick) { + close(); + return true; + } + + return consumed; + } + + public void close() { + getParent().removeChild(this); + } + + public GuiContextMenu setNormalizedPos(double x, double y) { + constrain(LEFT, dynamic(() -> Math.min(Math.max(x, 0), scaledScreenWidth() - xSize()))); + constrain(TOP, dynamic(() -> Math.min(Math.max(y, 0), scaledScreenHeight() - ySize()))); + return this; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java new file mode 100644 index 00000000..a3195c62 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java @@ -0,0 +1,97 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.math.MathHelper; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import org.jetbrains.annotations.NotNull; +import org.joml.Vector2d; + +import java.util.Random; +import java.util.function.Consumer; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Just for fun! + * Created by brandon3055 on 10/09/2023 + */ +public class GuiDVD extends GuiElement implements ContentElement> { + private static final Random randy = new Random(); + + private final GuiElement movingElement; + private double xOffset = 0; + private double yOffset = 0; + private Vector2d velocity = null; + private int bounce = 0; + private Consumer onBounce = bounce -> { + }; + + public GuiDVD(@NotNull GuiParent parent) { + super(parent); + this.movingElement = new GuiElement<>(this) + .constrain(TOP, Constraint.relative(get(TOP), () -> yOffset)) + .constrain(LEFT, Constraint.relative(get(LEFT), () -> xOffset)) + .constrain(WIDTH, Constraint.match(get(WIDTH))) + .constrain(HEIGHT, Constraint.match(get(HEIGHT))); + } + + @Override + public GuiElement getContentElement() { + return movingElement; + } + + public void start() { + if (velocity == null) { + velocity = new Vector2d(randy.nextBoolean() ? 1 : -1, randy.nextBoolean() ? 1 : -1); + velocity.normalize(); + } else { + velocity = null; + xOffset = yOffset = 0; + bounce = 0; + } + } + + public void onBounce(Consumer onBounce) { + this.onBounce = onBounce; + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + } + + @Override + public void render(GuiRender render, double mouseX, double mouseY, float partialTicks) { + super.render(render, mouseX, mouseY, partialTicks); + if (velocity == null) return; + + double speed = 5 * partialTicks; + xOffset += velocity.x * speed; + yOffset += velocity.y * speed; + Rectangle rect = movingElement.getRectangle(); + + int bounces = 0; + if ((velocity.y < 0 && rect.y() < 0) || (velocity.y > 0 && rect.yMax() > scaledScreenHeight())) { + velocity.y *= -1; + onBounce.accept(bounce++); + bounces++; + } + + if ((velocity.x < 0 && rect.x() < 0) || (velocity.x > 0 && rect.xMax() > scaledScreenWidth())) { + velocity.x *= -1; + onBounce.accept(bounce++); + bounces++; + } + + if (bounce > 0) { + velocity.y += -0.05 + (randy.nextGaussian() * 0.1); + velocity.x += -0.05 + (randy.nextGaussian() * 0.1); + velocity.x = velocity.x > 0 ? MathHelper.clip(velocity.x, 0.4, 0.6) : MathHelper.clip(velocity.x, -0.4, -0.6); + velocity.y = velocity.y > 0 ? MathHelper.clip(velocity.y, 0.4, 0.6) : MathHelper.clip(velocity.y, -0.4, -0.6); + velocity.normalize(); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java new file mode 100644 index 00000000..064e1f9f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java @@ -0,0 +1,241 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This class is designed to assist with the easy creation of a number of standard dialog windows. + *

+ * Created by brandon3055 on 14/12/2023 + */ +public class GuiDialog extends GuiElement { + + private boolean blockKeyInput = true; + private boolean blockMouseInput = true; + + protected GuiDialog(@NotNull GuiParent parent) { + super(parent); + } + + /** + * Option dialog builder with pre-configured background and button builders. + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + * @param options The list of options for this dialog. + */ + public static GuiDialog optionsDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, int width, Option... options) { + return optionsDialog(parent, title, dialogText, GuiRectangle::toolTipBackground, GuiDialog::defaultButton, width, options); + } + + /** + * Option dialog builder with pre-configured background and button builders. + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + * @param options The list of options for this dialog. + */ + public static GuiDialog optionsDialog(@NotNull GuiParent parent, Component dialogText, int width, Option... options) { + return optionsDialog(parent, null, dialogText, width, options); + } + + /** + * Creates a simple info dialog for displaying information to the user. + * The dialog has a single "Ok" button that will close the dialog + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + */ + public static GuiDialog infoDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, int width, @Nullable Runnable okAction) { + return optionsDialog(parent, title, dialogText, width, neutral(Component.translatable("gui.ok"), okAction)); + } + + /** + * Creates a simple info dialog for displaying information to the user. + * The dialog has a single "Ok" button that will close the dialog + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + */ + public static GuiDialog infoDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, int width) { + return infoDialog(parent, title, dialogText, width, null); + } + + /** + * Creates a simple info dialog for displaying information to the user. + * The dialog has a single "Ok" button that will close the dialog + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + */ + public static GuiDialog infoDialog(@NotNull GuiParent parent, Component dialogText, int width) { + return infoDialog(parent, null, dialogText, width); + } + + /** + * Create a green "Primary" button option. + */ + public static Option primary(Component text, @Nullable Runnable action) { + return new Option(text, action, hovered -> hovered ? 0xFF44AA44 : 0xFF118811); + } + + /** + * Create a grey "Neutral" button option. + */ + public static Option neutral(Component text, @Nullable Runnable action) { + return new Option(text, action, hovered -> hovered ? 0xFF909090 : 0xFF505050); + } + + /** + * Create a red "Caution" button option. + */ + public static Option caution(Component text, @Nullable Runnable action) { + return new Option(text, action, hovered -> hovered ? 0xFFAA4444 : 0xFF881111); + } + + /** + * @param blockKeyInput Prevent keyboard inputs from being sent to the rest of the gui while this dialog is open. + * Default: true. + */ + public GuiDialog setBlockKeyInput(boolean blockKeyInput) { + this.blockKeyInput = blockKeyInput; + return this; + } + + /** + * @param blockMouseInput Prevent mouse inputs from being sent to the rest of the gui while this dialog is open. + * Default: true. + */ + public GuiDialog setBlockMouseInput(boolean blockMouseInput) { + this.blockMouseInput = blockMouseInput; + return this; + } + + public void close() { + getParent().removeChild(this); + } + + @Override + public boolean keyPressed(int key, int scancode, int modifiers) { + return blockKeyInput; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + return blockMouseInput; + } + + /** + * This is the core dialog builder method. + * It takes a title text component and a map of Component>Runnable map that is used to define the options. + * Dialog will automatically be centered on the screen. + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param backgroundBuilder A function that is used to create the background of the dialog. + * @param buttonBuilder A function that is used to create the dialog buttons. + * @param width The dialog width, (Height will automatically adjust based on content.) + * @param options The list of options for this dialog. + */ + public static GuiDialog optionsDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, Function> backgroundBuilder, BiFunction buttonBuilder, int width, Option... options) { + if (options.length == 0) throw new IllegalStateException("Can not create gui dialog with no options!"); + ModularGui gui = parent.getModularGui(); + + GuiDialog dialog = new GuiDialog(gui.getRoot()) + .constrain(WIDTH, literal(width)) + .setOpaque(true); + Constraints.bind(backgroundBuilder.apply(dialog), dialog); + + Constraint left = relative(dialog.get(LEFT), 5); + Constraint right = relative(dialog.get(RIGHT), -5); + + if (title != null) { + GuiText titleText = new GuiText(dialog, title) + .setWrap(true) + .constrain(TOP, relative(dialog.get(TOP), 5)) + .constrain(LEFT, left) + .constrain(RIGHT, right) + .autoHeight(); + + GuiText bodyText = new GuiText(dialog, dialogText) + .setWrap(true) + .constrain(TOP, relative(titleText.get(BOTTOM), 5)) + .constrain(LEFT, left) + .constrain(RIGHT, right) + .autoHeight(); + dialog.constrain(HEIGHT, dynamic(() -> 5 + titleText.ySize() + 5 + bodyText.ySize() + 5 + 14 + 5)); + } else { + GuiText bodyText = new GuiText(dialog, dialogText) + .setWrap(true) + .constrain(TOP, relative(dialog.get(TOP), 5)) + .constrain(LEFT, left) + .constrain(RIGHT, right) + .autoHeight(); + dialog.constrain(HEIGHT, dynamic(() -> 5 + bodyText.ySize() + 5 + 14 + 5)); + } + + double totalWidth = FastStream.of(options).doubleSum(e -> dialog.font().width(e.text)); + double pos = 5; + int spacing = 2; + for (Option option : options) { + double fraction = dialog.font().width(option.text) / totalWidth; + double opWidth = (dialog.xSize() - 10 - ((options.length - 1) * spacing)) * fraction; + buttonBuilder.apply(dialog, option) + .constrain(BOTTOM, relative(dialog.get(BOTTOM), -5)) + .constrain(HEIGHT, literal(14)) + .constrain(LEFT, relative(dialog.get(LEFT), pos).precise()) + .constrain(WIDTH, literal(opWidth).precise()); + pos += opWidth + spacing; + } + + dialog.constrain(TOP, midPoint(gui.get(TOP), gui.get(BOTTOM), () -> -(dialog.ySize() / 2D))); + dialog.constrain(LEFT, midPoint(gui.get(LEFT), gui.get(RIGHT), -(width / 2D))); + return dialog; + } + + private static GuiButton defaultButton(GuiDialog dialog, Option option) { + GuiButton button = new GuiButton(dialog); + + GuiRectangle background = new GuiRectangle(button) + .fill(() -> option.colour.apply(button.isMouseOver())); + Constraints.bind(background, button); + + GuiText text = new GuiText(button, option.text()); + button.setLabel(text); + Constraints.bind(text, button, 0, 2, 0, 2); + + button.onPress(() -> { + if (option.action != null) { + option.action.run(); + } + dialog.close(); + }); + + return button; + } + + public record Option(Component text, @Nullable Runnable action, Function colour) {} +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java new file mode 100644 index 00000000..8942e51f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java @@ -0,0 +1,491 @@ +package codechicken.lib.gui.modular.elements; + +import com.google.common.collect.Lists; +import com.mojang.blaze3d.vertex.PoseStack; +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.geometry.ConstrainedGeometry; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Position; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import net.covers1624.quack.util.SneakyUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.security.InvalidParameterException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; + +/** + * This is the Base class for all gui elements in Modular Gui Version 3. + *

+ * In v2 this vas a massive monolithic class that had way too much crammed into it. + * The primary goals of v3 are the following: + * - Build a new, Extremely flexible system for handling element geometry, including relative positions, anchoring, etc. + * This was archived using the new Geometry system. For details see {@link GuiParent} and {@link ConstrainedGeometry} + * - Implement a system to properly handle element z offsets. + * This was archived by giving all elements a 'depth' property which defines an elements size on the z axis. + * This is then used to properly layer elements and child elements when they are rendered. + * - Switch everything over to the new RenderType system. (This is mostly handled behind the scenes. You don't need to mess with it when creating a GUI) + * - Consolidate all the various rendering helper methods into one convenient utility class. + * The new {@link GuiGraphics} system showed me a good way to implement this. + * - Reduce the amount of ambiguity when building GUIs. (Whether I succeeded here is up for debate xD) + * - Cut out a lot of random bloat that was never used in v2. + *

+ *

+ * Created by brandon3055 on 04/07/2023 + */ +public class GuiElement> extends ConstrainedGeometry implements ElementEvents, TooltipHandler { + + @NotNull + private GuiParent parent; + + private final List> addedQueue = new ArrayList<>(); + private final List> removeQueue = new ArrayList<>(); + private final List> childElements = new ArrayList<>(); + private final List> childElementsUnmodifiable = Collections.unmodifiableList(childElements); + public boolean initialized = false; + + private Minecraft mc; + private Font font; + private int screenWidth; + private int screenHeight; + + protected int hoverTime = 0; + private int hoverTextDelay = 10; + private boolean isMouseOver = false; + private boolean opaque = false; + private boolean removed = true; + private boolean zStacking = true; + private Supplier enabled = () -> true; + private Supplier enableToolTip = () -> true; + private Supplier> toolTip = null; + private Rectangle renderCull = Rectangle.create(Position.create(0, 0), () -> (double) screenWidth, () -> (double) screenHeight); + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiElement(@NotNull GuiParent parent) { + this.parent = parent; + this.parent.addChild(this); + } + + @NotNull + @Override + public GuiParent getParent() { + return parent; + } + + //=== Child Element Handling ===// + + @Override + public List> getChildren() { + return childElementsUnmodifiable; + } + + /** + * In Modular GUI v3, The add child method is primarily for internal use, + * Child elements are automatically added to their parent on construction. + * + * @param child The child element to be added. + */ + @Override + public void addChild(GuiElement child) { + if (!initialized) throw new IllegalStateException("Attempted to add a child to an element before that element has been initialised!"); + if (child == this) throw new InvalidParameterException("Attempted to add element to itself as a child element."); + if (child.getParent() != this) throw new UnsupportedOperationException("Attempted to add an already initialized element to a different parent element."); + if (removeQueue.contains(child)) { + removeQueue.remove(child); + if (!childElements.contains(child)) { + addedQueue.add(child); + } + child.initElement(this); + } else if (!childElements.contains(child)) { + addedQueue.add(child); + child.initElement(this); + } + } + + protected void applyQueuedChildUpdates() { + if (!removeQueue.isEmpty()) { + childElements.removeAll(removeQueue); + removeQueue.clear(); + } + + if (!addedQueue.isEmpty()) { + childElements.addAll(addedQueue); + addedQueue.clear(); + } + } + + /** + * Called immediately after an element is added to its parent, use to initialize the child element. + */ + public void initElement(GuiParent parent) { + removed = false; + updateScreenData(parent.mc(), parent.font(), parent.scaledScreenWidth(), parent.scaledScreenHeight()); + initialized = true; + } + + @Override + public void adoptChild(GuiElement child) { + child.getParent().removeChild(child); + child.parent = this; + addChild(child); + } + + @Override + public void removeChild(GuiElement child) { + if (childElements.contains(child)) { + child.removed = true; + removeQueue.add(child); + } + addedQueue.remove(child); + } + + @Override + public boolean isDescendantOf(GuiElement ancestor) { + return ancestor == parent || parent.isDescendantOf(ancestor); + } + + //=== Minecraft Properties / Initialisation ===// + //TODO I can probably just pass these calls all the way up to the root parent... + + @Override + public Minecraft mc() { + return mc; + } + + @Override + public Font font() { + return font; + } + + @Override + public int scaledScreenWidth() { + return screenWidth; + } + + @Override + public int scaledScreenHeight() { + return screenHeight; + } + + @Override + public ModularGui getModularGui() { + return getParent().getModularGui(); + } + + @Override + public void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + updateScreenData(mc, font, screenWidth, screenHeight); + super.onScreenInit(mc, font, screenWidth, screenHeight); + } + + protected void updateScreenData(Minecraft mc, Font font, int screenWidth, int screenHeight) { + this.mc = mc; + this.font = font; + this.screenWidth = screenWidth; + this.screenHeight = screenHeight; + } + + //=== Element Status ===// + + public T setEnabled(boolean enabled) { + this.enabled = () -> enabled; + return SneakyUtils.unsafeCast(this); + } + + public T setEnabled(@Nullable Supplier enabled) { + this.enabled = enabled; + return SneakyUtils.unsafeCast(this); + } + + public boolean isEnabled() { + return !removed && enabled.get(); + } + + public boolean isRemoved() { + return removed; + } + + public T setEnableToolTip(Supplier enableToolTip) { + this.enableToolTip = enableToolTip; + return SneakyUtils.unsafeCast(this); + } + + @Override + public boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return getParent().blockMouseOver(element, mouseX, mouseY); + } + + @Override + public boolean blockMouseEvents() { + return isMouseOver() && isOpaque(); + } + + /** + * @return True if the cursor is within the bounds of this element, and there is no opaque element above this one obstructing the cursor. + */ + public boolean isMouseOver() { + return isMouseOver; + } + + public boolean isOpaque() { + return opaque; + } + + /** + * If an element is marked as opaque it will consume mouseOver updates, thereby preventing elements bellow from accepting mouseOver input. + * Also prevents mouse events within this element from being passed to elements bellow. + */ + public T setOpaque(boolean opaque) { + this.opaque = opaque; + return SneakyUtils.unsafeCast(this); + } + + /** + * @return the amount of time the cursor has spent inside this element's bounds, + * resets to zero when the cursor leaves this element's bounds. + */ + public int hoverTime() { + return hoverTime; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "{" + + "geometry=" + getRectangle() + + '}'; + } + + /** + * Add this element to the list of jei exclusions. + * Use this for any elements that render outside the normal gui bounds. + * This will ensure JEI does not try to render on top of these elements. + */ + public T jeiExclude() { + getModularGui().jeiExclude(this); + return SneakyUtils.unsafeCast(this); + } + + /** + * Remove this element from the list of jei exclusions. + */ + public T removeJEIExclude() { + getModularGui().removeJEIExclude(this); + return SneakyUtils.unsafeCast(this); + } + + //=== Render / Update ===// + + /** + * Any child elements completely outside this rectangle will not be rendered at all. + * By default, this is set to the screen bounds (meaning the minecraft window) + * Setting this to null will disable culling. + */ + public T setRenderCull(@Nullable Rectangle renderCull) { + this.renderCull = renderCull; + return SneakyUtils.unsafeCast(this); + } + + /** + * Allows you to disable child z-stacking, Meaning all child elements will be rendered at the same z-level + * rather than being stacked. (Not Recursive, children their sub elements with stacking) + *

+ * This can be useful when rendering a lot of high z depth elements such as ItemStacks. + * As long as you know for sure none of the elements intersect, it should be safe to disable stacking. + * + * @param zStacking Enable z stacking (default true) + */ + public T setZStacking(boolean zStacking) { + this.zStacking = zStacking; + return SneakyUtils.unsafeCast(this); + } + + public boolean zStacking() { + return zStacking; + } + + /** + * Returns the depth of this element plus all of its children (recursively) + * Note: You should almost never need to override this! Depth of background and / or foreground content + * should be specified via {@link BackgroundRender#getBackgroundDepth()} and {@link ForegroundRender#getForegroundDepth()} + * + * @return The depth (z height) of this element plus all of its children. + */ + public double getCombinedElementDepth() { + double depth = 0; + if (this instanceof BackgroundRender bgr) depth += bgr.getBackgroundDepth(); + if (this instanceof ForegroundRender fgr) depth += fgr.getForegroundDepth(); + + double childDepth = 0; + for (GuiElement child : childElements) { + if (!child.isEnabled()) continue; + if (zStacking) { + childDepth += child.getCombinedElementDepth(); + } else { + childDepth = Math.max(childDepth, child.getCombinedElementDepth()); + } + } + + return depth + childDepth; + } + + /** + * This is the main render method that handles rendering this element and any child elements it may have. + * This method almost never needs to be overridden, instead when creating custom elements with custom rendering, + * your element should implement {@link BackgroundRender} and / or {@link ForegroundRender} in or order to implement + * its rendering. + *

+ * Note: After the render is complete, the poseStack's z pos will be offset by the total depth of this element and its children. + * This is intended behavior, + * + * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param partialTicks Partial render ticks + */ + public void render(GuiRender render, double mouseX, double mouseY, float partialTicks) { + applyQueuedChildUpdates(); + if (this instanceof BackgroundRender bgr) { + double depth = bgr.getBackgroundDepth(); + bgr.renderBackground(render, mouseX, mouseY, partialTicks); + if (depth > 0) { + render.pose().translate(0, 0, depth); + } + } + + double maxDepth = 0; + for (GuiElement child : childElements) { + if (child.isEnabled()) { + boolean rendered = renderChild(child, render, mouseX, mouseY, partialTicks); + //If z-stacking is disabled, we need to undo the z offset that was applied by the child element. + if (!zStacking && rendered) { + double depth = child.getCombinedElementDepth(); + maxDepth = Math.max(maxDepth, depth); + render.pose().translate(0, 0, -depth); + } + } + } + + if (!zStacking) { + //Now we need to apply the z offset of the tallest child. + render.pose().translate(0, 0, maxDepth); + } + + if (this instanceof ForegroundRender fgr) { + double depth = fgr.getForegroundDepth(); + fgr.renderForeground(render, mouseX, mouseY, partialTicks); + if (depth > 0) { + render.pose().translate(0, 0, depth); + } + } + } + + protected boolean renderChild(GuiElement child, GuiRender render, double mouseX, double mouseY, float partialTicks) { + if (renderCull != null && !renderCull.intersects(child.getRectangle())) return false; + child.render(render, mouseX, mouseY, partialTicks); + return true; + } + + /** + * Used to render overlay's such as hover text. Anything rendered in this method will be rendered on top of everything else on the screen. + * Only one overlay should be rendered at a time, When an element renders content via the overlay method it must return true to indicate the render call has been 'consumed' + * If the render call has already been consumed (Check via the consumed boolean) then this element should avoid rendering its overlay. + *

+ * When rendering overlay content, always use the {@link PoseStack} available via the provided {@link GuiRender} + * This stack will already have the correct Z translation to ensure the overlay renders above everything else on the screen. + *

+ * To check if the cursor is over this element, use 'render.hoveredElement() == this' + * {@link #isMouseOver()} Will also work, but may be problematic when multiple, stacked elements have overlay content. + * + * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param partialTicks Partial render ticks + * @param consumed Will be true if the overlay render call has already been consumed by another element. + * @return true if the render call has been consumed. + */ + public boolean renderOverlay(GuiRender render, double mouseX, double mouseY, float partialTicks, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.renderOverlay(render, mouseX, mouseY, partialTicks, consumed); + } + } + return consumed || (showToolTip() && renderTooltip(render, mouseX, mouseY)); + } + + private boolean showToolTip() { + return isMouseOver() && enableToolTip.get() && hoverTime() >= getTooltipDelay(); + } + + /** + * Called every tick to update the element. Note this is called regardless of weather or not the element is actually enabled. + * + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + */ + public void tick(double mouseX, double mouseY) { + if (isMouseOver()) { + hoverTime++; + } else { + hoverTime = 0; + } + + for (GuiElement childElement : childElements) { + childElement.tick(mouseX, mouseY); + } + } + + /** + * Called at the start of each tick to update the 'mouseOver' state of each element. + * If the cursor is over an element that is marked as opaque, the update will be consumed. + * This ensures no elements below the opaque element will have their mouseOver flag set to true. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param consumed True if mouseover event has been consumed. + * @return true if this event has been consumed. + */ + public boolean updateMouseOver(double mouseX, double mouseY, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.updateMouseOver(mouseX, mouseY, consumed); + } + } + + isMouseOver = !consumed && GuiRender.isInRect(xMin(), yMin(), xSize(), ySize(), mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY); + return consumed || (isMouseOver && isOpaque()); + } + + //=== Hover Text ===// + + @Override + public Supplier> getTooltip() { + return toolTip; + } + + @Override + public T setTooltipDelay(int tooltipDelay) { + this.hoverTextDelay = tooltipDelay; + return SneakyUtils.unsafeCast(this); + } + + @Override + public int getTooltipDelay() { + return hoverTextDelay; + } + + @Override + public T setTooltip(@Nullable Supplier> tooltip) { + this.toolTip = tooltip; + return SneakyUtils.unsafeCast(this); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java new file mode 100644 index 00000000..478e86a8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java @@ -0,0 +1,143 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import codechicken.lib.gui.modular.sprite.Material; +import codechicken.lib.util.FormatUtil; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +import static net.minecraft.ChatFormatting.*; + +/** + * Created by brandon3055 on 10/09/2023 + */ +public class GuiEnergyBar extends GuiElement implements BackgroundRender { + public static final DecimalFormat COMMA_FORMAT = new DecimalFormat("###,###,###,###,###", DecimalFormatSymbols.getInstance(Locale.ROOT)); + public static final Material EMPTY = CCGuiTextures.getUncached("widgets/energy_empty"); + public static final Material FULL = CCGuiTextures.getUncached("widgets/energy_full"); + + private Supplier energy = () -> 0L; + private Supplier capacity = () -> 0L; + private Material emptyTexture = EMPTY; + private Material fullTexture = FULL; + private BiFunction> toolTipFormatter; + + public GuiEnergyBar(@NotNull GuiParent parent) { + super(parent); + setTooltipDelay(0); + setToolTipFormatter(defaultFormatter()); + } + + /** + * Creates a simple energy bar using a simple slot as a background to make it look nice. + */ + public static EnergyBar simpleBar(@NotNull GuiParent parent) { + GuiRectangle container = GuiRectangle.vanillaSlot(parent); + GuiEnergyBar energyBar = new GuiEnergyBar(container); + Constraints.bind(energyBar, container, 1); + return new EnergyBar(container, energyBar); + } + + public static BiFunction> defaultFormatter() { + return (energy, capacity) -> { + List tooltip = new ArrayList<>(); + tooltip.add(Component.translatable("energy_bar.polylib.energy_storage").withStyle(DARK_AQUA)); + boolean shift = Screen.hasShiftDown(); + tooltip.add(Component.translatable("energy_bar.polylib.capacity") + .withStyle(GOLD) + .append(" ") + .append(Component.literal(shift ? FormatUtil.addCommas(capacity) : FormatUtil.formatNumber(capacity)) + .withStyle(GRAY) + .append(" ") + .append(Component.translatable("energy_bar.polylib.rf") + .withStyle(GRAY) + ) + ) + ); + tooltip.add(Component.translatable("energy_bar.polylib.stored") + .withStyle(GOLD) + .append(" ") + .append(Component.literal(shift ? FormatUtil.addCommas(energy) : FormatUtil.formatNumber(energy)) + .withStyle(GRAY) + ) + .append(" ") + .append(Component.translatable("energy_bar.polylib.rf") + .withStyle(GRAY) + ) + .append(Component.literal(String.format(" (%.2f%%)", ((double) energy / (double) capacity) * 100D)) + .withStyle(GRAY) + ) + ); + return tooltip; + }; + } + + public GuiEnergyBar setEmptyTexture(Material emptyTexture) { + this.emptyTexture = emptyTexture; + return this; + } + + public GuiEnergyBar setFullTexture(Material fullTexture) { + this.fullTexture = fullTexture; + return this; + } + + public GuiEnergyBar setCapacity(long capacity) { + return setCapacity(() -> capacity); + } + + public GuiEnergyBar setCapacity(Supplier capacity) { + this.capacity = capacity; + return this; + } + + public GuiEnergyBar setEnergy(long energy) { + return setEnergy(() -> energy); + } + + public GuiEnergyBar setEnergy(Supplier energy) { + this.energy = energy; + return this; + } + + public long getEnergy() { + return energy.get(); + } + + public long getCapacity() { + return capacity.get(); + } + + /** + * Install a custom formatter to control how the energy tool tip renders. + */ + public GuiEnergyBar setToolTipFormatter(BiFunction> toolTipFormatter) { + this.toolTipFormatter = toolTipFormatter; + setTooltip(() -> this.toolTipFormatter.apply(getEnergy(), getCapacity())); + return this; + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + float p = 1 / 128F; + float height = getCapacity() <= 0 ? 0 : (float) ySize() * (getEnergy() / (float) getCapacity()); + float texHeight = height * p; + render.partialSprite(EMPTY.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), EMPTY.sprite(), 0F, 1F - (p * (float) ySize()), p * (float) xSize(), 1F, 0xFFFFFFFF); + render.partialSprite(FULL.renderType(GuiRender::texColType), xMin(), yMin() + (ySize() - height), xMax(), yMax(), FULL.sprite(), 0F, 1F - texHeight, p * (float) xSize(), 1F, 0xFFFFFFFF); + } + + public record EnergyBar(GuiRectangle container, GuiEnergyBar bar) {} +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java new file mode 100644 index 00000000..ac09f9b3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java @@ -0,0 +1,264 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import codechicken.lib.render.CCRenderEventHandler; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; +import net.minecraft.client.player.RemotePlayer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraftforge.registries.ForgeRegistries; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.joml.Quaternionf; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 15/11/2023 + */ +public class GuiEntityRenderer extends GuiElement implements BackgroundRender { + public static final Logger LOGGER = LogManager.getLogger(); + private static final Map entityCache = new HashMap<>(); + private static final List invalidEntities = new ArrayList<>(); + + private Supplier rotationSpeed = () -> 1F; + private Supplier lockedRotation = () -> 0F; + private Entity entity; + private ResourceLocation entityName; + private boolean invalidEntity = false; + private Supplier rotationLocked = () -> false; + private Supplier trackMouse = () -> false; + private Supplier drawName = () -> false; + public boolean force2dSize = false; + + public GuiEntityRenderer(@NotNull GuiParent parent) { + super(parent); + } + + public GuiEntityRenderer setEntity(Entity entity) { + this.entity = entity; + if (this.entity == null) { + invalidEntity = true; + return this; + } + + this.entityName = ForgeRegistries.ENTITY_TYPES.getKey(entity.getType()); + invalidEntity = invalidEntities.contains(entityName); + return this; + } + + public GuiEntityRenderer setEntity(ResourceLocation entity) { + this.entityName = entity; + this.entity = entityCache.computeIfAbsent(entity, resourceLocation -> { + EntityType type = ForgeRegistries.ENTITY_TYPES.getValue(entity); + return type == null ? null : type.create(mc().level); + }); + + invalidEntity = this.entity == null; + if (invalidEntities.contains(entityName)) { + invalidEntity = true; + } + + return this; + } + + public GuiEntityRenderer setRotationSpeed(float rotationSpeed) { + this.rotationSpeed = () -> rotationSpeed; + return this; + } + + public GuiEntityRenderer setRotationSpeed(Supplier rotationSpeed) { + this.rotationSpeed = rotationSpeed; + return this; + } + + public float getRotationSpeed() { + return rotationSpeed.get(); + } + + public GuiEntityRenderer setLockedRotation(float lockedRotation) { + this.lockedRotation = () -> lockedRotation; + return this; + } + + public GuiEntityRenderer setLockedRotation(Supplier lockedRotation) { + this.lockedRotation = lockedRotation; + return this; + } + + public float getLockedRotation() { + return lockedRotation.get(); + } + + public GuiEntityRenderer setRotationLocked(boolean rotationLocked) { + this.rotationLocked = () -> rotationLocked; + return this; + } + + public GuiEntityRenderer setRotationLocked(Supplier rotationLocked) { + this.rotationLocked = rotationLocked; + return this; + } + + public boolean isRotationLocked() { + return rotationLocked.get(); + } + + public GuiEntityRenderer setTrackMouse(boolean trackMouse) { + this.trackMouse = () -> trackMouse; + return this; + } + + public GuiEntityRenderer setTrackMouse(Supplier trackMouse) { + this.trackMouse = trackMouse; + return this; + } + + public boolean isTrackMouse() { + return trackMouse.get(); + } + + public GuiEntityRenderer setDrawName(boolean drawName) { + this.drawName = () -> drawName; + return this; + } + + public GuiEntityRenderer setDrawName(Supplier drawName) { + this.drawName = drawName; + return this; + } + + public boolean isDrawName() { + return drawName.get(); + } + + public GuiEntityRenderer setForce2dSize(boolean force2dSize) { + this.force2dSize = force2dSize; + return this; + } + + @Override + public double getBackgroundDepth() { + Rectangle rect = getRectangle(); + float scale = (float) (force2dSize ? (Math.min(rect.height() / entity.getBbHeight(), rect.width() / entity.getBbWidth())) : rect.height() / entity.getBbHeight()); + return scale * 2; + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + if (invalidEntity) return; + + try { + if (entity != null) { + Rectangle rect = getRectangle(); + float scale = (float) (force2dSize ? (Math.min(rect.height() / entity.getBbHeight(), rect.width() / entity.getBbWidth())) : rect.height() / entity.getBbHeight()); + float xPos = (float) (rect.x() + (rect.width() / 2D)); + float yPos = (float) ((yMin() + (ySize() / 2)) + (rect.height() / 2)); + float rotation = rotationLocked.get() ? lockedRotation.get() : (CCRenderEventHandler.renderTime + partialTicks) * rotationSpeed.get(); + if (entity instanceof LivingEntity living) { + int eyeOffset = (int) ((entity.getEyeHeight()) * scale); + if (trackMouse.get()) { + renderEntityInInventoryFollowsMouse(render, xPos, yPos, scale, xPos - (float) mouseX, yPos - (float) mouseY - eyeOffset, living); + } else { + renderEntityInInventoryWithRotation(render, xPos, yPos, scale, rotation, living); + } + } + } + } catch (Throwable e) { + invalidEntity = true; + invalidEntities.add(entityName); + LOGGER.error("Failed to render entity in GUI. This is not a bug there are just some entities that can not be rendered like this."); + LOGGER.error("Entity: " + entity, e); + } + } + + public static void renderEntityInInventoryFollowsMouse(GuiRender render, double pX, double pY, double pScale, float offsetX, float offsetY, LivingEntity pEntity) { + float xAngle = (float)Math.atan(offsetX / 40.0F); + float yAngle = (float)Math.atan(offsetY / 40.0F); + renderEntityInInventoryFollowsAngle(render, pX, pY, pScale, xAngle, yAngle, pEntity); + } + + public static void renderEntityInInventoryFollowsAngle(GuiRender render, double pX, double pY, double pScale, float angleX, float angleY, LivingEntity pEntity) { + Quaternionf quaternionf = (new Quaternionf()).rotateZ((float)Math.PI); + Quaternionf quaternionf1 = (new Quaternionf()).rotateX(angleY * 20.0F * ((float)Math.PI / 180F)); + quaternionf.mul(quaternionf1); + float f2 = pEntity.yBodyRot; + float f3 = pEntity.getYRot(); + float f4 = pEntity.getXRot(); + float f5 = pEntity.yHeadRotO; + float f6 = pEntity.yHeadRot; + pEntity.yBodyRot = 180.0F + angleX * 20.0F; + pEntity.setYRot(180.0F + angleX * 40.0F); + pEntity.setXRot(-angleY * 20.0F); + pEntity.yHeadRot = pEntity.getYRot(); + pEntity.yHeadRotO = pEntity.getYRot(); + renderEntityInInventory(render, pX, pY, pScale, quaternionf, quaternionf1, pEntity); + pEntity.yBodyRot = f2; + pEntity.setYRot(f3); + pEntity.setXRot(f4); + pEntity.yHeadRotO = f5; + pEntity.yHeadRot = f6; + } + + public static void renderEntityInInventoryWithRotation(GuiRender render, double xPos, double yPos, double scale, double rotation, LivingEntity living) { + Quaternionf quaternionf = new Quaternionf().rotateZ((float)Math.PI); + Quaternionf quaternionf1 = Axis.YP.rotationDegrees((float) rotation); + quaternionf.mul(quaternionf1); + float f2 = living.yBodyRot; + float f3 = living.getYRot(); + float f4 = living.getXRot(); + float f5 = living.yHeadRotO; + float f6 = living.yHeadRot; + living.yBodyRot = 180.0F; + living.setYRot(180.0F); + living.setXRot(0); + living.yHeadRot = living.getYRot(); + living.yHeadRotO = living.getYRot(); + renderEntityInInventory(render, xPos, yPos, scale, quaternionf, quaternionf1, living); + living.yBodyRot = f2; + living.setYRot(f3); + living.setXRot(f4); + living.yHeadRotO = f5; + living.yHeadRot = f6; + } + + public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, LivingEntity pEntity) { + render.pose().pushPose(); + render.pose().translate(pX, pY, 50.0D); + render.pose().mulPoseMatrix((new Matrix4f()).scaling((float)pScale, (float)pScale, (float)(-pScale))); + render.pose().mulPose(quat); + Lighting.setupForEntityInInventory(); + EntityRenderDispatcher entityrenderdispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); + if (pCameraOrientation != null) { + pCameraOrientation.conjugate(); + entityrenderdispatcher.overrideCameraOrientation(pCameraOrientation); + } + + entityrenderdispatcher.setRenderShadow(false); + RenderSystem.runAsFancy(() -> entityrenderdispatcher.render(pEntity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F, render.pose(), render.buffers(), 15728880)); + render.flush(); + entityrenderdispatcher.setRenderShadow(true); + render.pose().popPose(); + Lighting.setupFor3DItems(); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java new file mode 100644 index 00000000..393ba6c3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java @@ -0,0 +1,122 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import org.apache.logging.log4j.util.TriConsumer; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiConsumer; + +/** + * Created by brandon3055 on 15/11/2023 + */ +public class GuiEventProvider extends GuiElement { + + private boolean ignoreConsumed = false; + private final List> clickListeners = new ArrayList<>(); + private final List> releaseListeners = new ArrayList<>(); + private final List> movedListeners = new ArrayList<>(); + private final List> scrollListeners = new ArrayList<>(); + private final List> keyPressListeners = new ArrayList<>(); + private final List> keyReleaseListeners = new ArrayList<>(); + private final List> charTypedListeners = new ArrayList<>(); + + public GuiEventProvider(@NotNull GuiParent parent) { + super(parent); + } + + public GuiEventProvider setIgnoreConsumed(boolean ignoreConsumed) { + this.ignoreConsumed = ignoreConsumed; + return this; + } + + public GuiEventProvider onMouseClick(TriConsumer listener) { + clickListeners.add(listener); + return this; + } + + public GuiEventProvider onMouseRelease(TriConsumer listener) { + releaseListeners.add(listener); + return this; + } + + public GuiEventProvider onMouseMove(BiConsumer listener) { + movedListeners.add(listener); + return this; + } + + public GuiEventProvider onScroll(TriConsumer listener) { + scrollListeners.add(listener); + return this; + } + + public GuiEventProvider onKeyPress(TriConsumer listener) { + keyPressListeners.add(listener); + return this; + } + + public GuiEventProvider onKeyRelease(TriConsumer listener) { + keyReleaseListeners.add(listener); + return this; + } + + public GuiEventProvider onCharTyped(BiConsumer listener) { + charTypedListeners.add(listener); + return this; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + if (ignoreConsumed || !consumed) { + clickListeners.forEach(e -> e.accept(mouseX, mouseY, button)); + } + return super.mouseClicked(mouseX, mouseY, button, consumed); + } + + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + if (ignoreConsumed || !consumed) { + releaseListeners.forEach(e -> e.accept(mouseX, mouseY, button)); + } + return super.mouseReleased(mouseX, mouseY, button, consumed); + } + + @Override + public void mouseMoved(double mouseX, double mouseY) { + movedListeners.forEach(e -> e.accept(mouseX, mouseY)); + super.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scroll, boolean consumed) { + if (ignoreConsumed || !consumed) { + scrollListeners.forEach(e -> e.accept(mouseX, mouseY, scroll)); + } + return super.mouseScrolled(mouseX, mouseY, scroll, consumed); + } + + @Override + public boolean keyPressed(int key, int scancode, int modifiers, boolean consumed) { + if (ignoreConsumed || !consumed) { + keyPressListeners.forEach(e -> e.accept(key, scancode, modifiers)); + } + return super.keyPressed(key, scancode, modifiers, consumed); + } + + @Override + public boolean keyReleased(int key, int scancode, int modifiers, boolean consumed) { + if (ignoreConsumed || !consumed) { + keyReleaseListeners.forEach(e -> e.accept(key, scancode, modifiers)); + } + return super.keyReleased(key, scancode, modifiers, consumed); + } + + @Override + public boolean charTyped(char character, int modifiers, boolean consumed) { + if (ignoreConsumed || !consumed) { + charTypedListeners.forEach(e -> e.accept(character, modifiers)); + } + return super.charTyped(character, modifiers, consumed); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java new file mode 100644 index 00000000..a2d4eb9a --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java @@ -0,0 +1,252 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import codechicken.lib.gui.modular.sprite.Material; +import codechicken.lib.util.FormatUtil; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Fluids; +import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; +import net.minecraftforge.fluids.FluidStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +import static net.minecraft.ChatFormatting.*; + +/** + * When implementing this tank, you must specify the tank capacity in mb, + * And then you have two options for specifying the tank contents. + * You can set the fluid and the amount stored, + * Or you can provide a {@link FluidStack} + *

+ * Created by brandon3055 on 11/09/2023 + */ +public class GuiFluidTank extends GuiElement implements BackgroundRender { + //TODO make a better texture, This feels a little too.. cluttered. + public static final Material DEFAULT_WINDOW = CCGuiTextures.getUncached("widgets/tank_window"); + + private int gaugeColour = 0xFF909090; + private boolean drawGauge = true; + private Material window = null; + private Supplier capacity = () -> 10000L; + private Supplier fluidStack = () -> FluidStack.EMPTY; + + private BiFunction> toolTipFormatter; + + public GuiFluidTank(@NotNull GuiParent parent) { + super(parent); + setTooltipDelay(0); + setToolTipFormatter(defaultFormatter()); + } + + /** + * Creates a simple tank using a simple slot as a background to make it look nice. + */ + public static FluidTank simpleTank(@NotNull GuiParent parent) { + GuiRectangle container = GuiRectangle.vanillaSlot(parent); + GuiFluidTank energyBar = new GuiFluidTank(container); + Constraints.bind(energyBar, container, 1); + return new FluidTank(container, energyBar); + } + + /** + * Sets the capacity of this tank in milli-buckets. + */ + public GuiFluidTank setCapacity(long capacity) { + return setCapacity(() -> capacity); + } + + /** + * Supply the capacity of this tank in milli-buckets. + */ + public GuiFluidTank setCapacity(Supplier capacity) { + this.capacity = capacity; + return this; + } + + /** + * Allows you to set the current stored fluid stack. + */ + public GuiFluidTank setFluidStack(FluidStack fluidStack) { + return setFluidStack(() -> fluidStack); + } + + /** + * Allows you to supply the current stored fluid stack. + */ + public GuiFluidTank setFluidStack(Supplier fluidStack) { + this.fluidStack = fluidStack; + return this; + } + + /** + * Install a custom formatter to control how the fluid tool tip renders. + */ + public GuiFluidTank setToolTipFormatter(BiFunction> toolTipFormatter) { + this.toolTipFormatter = toolTipFormatter; + setTooltip(() -> this.toolTipFormatter.apply(getFluidStack(), getCapacity())); + return this; + } + + /** + * Sets the tank window texture, Will be tiled to fit the tank size. + * + * @param window New window texture or null for no window texture. + */ + public GuiFluidTank setWindow(@Nullable Material window) { + this.window = window; + return this; + } + + /** + * Enable the built-in fluid gauge lines. + */ + public GuiFluidTank setDrawGauge(boolean drawGauge) { + this.drawGauge = drawGauge; + return this; + } + + /** + * Sets the colour of the built-in fluid gauge lines + */ + public GuiFluidTank setGaugeColour(int gaugeColour) { + this.gaugeColour = gaugeColour; + return this; + } + + public Long getCapacity() { + return capacity.get(); + } + + public FluidStack getFluidStack() { + return fluidStack.get(); + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + FluidStack stack = getFluidStack(); + Material fluidMat = Material.fromSprite(getStillTexture(stack)); + + if (!stack.isEmpty() && fluidMat != null) { + int fluidColor = getColour(stack); + float height = getCapacity() <= 0 ? 0 : (float) ySize() * (stack.getAmount() / (float) getCapacity()); + render.tileSprite(fluidMat.renderType(GuiRender::texColType), xMin(), yMax() - height, xMax(), yMax(), fluidMat.sprite(), fluidColor); + } + + if (window != null) { + render.tileSprite(window.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), window.sprite(), 0xFFFFFFFF); + } + + gaugeColour = 0xFF000000; + if (drawGauge) { + double spacing = computeGaugeSpacing(); + if (spacing == 0) return; + + double pos = spacing; + while (pos + 1 < ySize()) { + double width = xSize() / 4; + double yPos = yMax() - 1 - pos; + render.fill(xMax() - width, yPos, xMax(), yPos + 1, gaugeColour); + pos += spacing; + } + } + } + + private double computeGaugeSpacing() { + double ySize = ySize(); + double capacity = getCapacity(); + if (ySize / (capacity / 100D) > 3) return ySize / (capacity / 100D); + else if (ySize / (capacity / 500D) > 3) return ySize / (capacity / 500D); + else if (ySize / (capacity / 1000D) > 3) return ySize / (capacity / 1000D); + else if (ySize / (capacity / 5000D) > 3) return ySize / (capacity / 5000D); + else if (ySize / (capacity / 10000D) > 3) return ySize / (capacity / 10000D); + else if (ySize / (capacity / 50000D) > 3) return ySize / (capacity / 50000D); + else if (ySize / (capacity / 100000D) > 3) return ySize / (capacity / 100000D); + return 0; + } + + public static BiFunction> defaultFormatter() { + return (fluidStack, capacity) -> { + List tooltip = new ArrayList<>(); + tooltip.add(Component.translatable("fluid_tank.polylib.fluid_storage").withStyle(DARK_AQUA)); + if (!fluidStack.isEmpty()) { + tooltip.add(Component.translatable("fluid_tank.polylib.contains") + .withStyle(GOLD) + .append(" ") + .append(fluidStack.getDisplayName().copy() + .setStyle(Style.EMPTY + .withColor(getColour(fluidStack)) + ) + ) + ); + } + + tooltip.add(Component.translatable("fluid_tank.polylib.capacity") + .withStyle(GOLD) + .append(" ") + .append(Component.literal(FormatUtil.addCommas(capacity)) + .withStyle(GRAY) + .append(" ") + .append(Component.translatable("fluid_tank.polylib.mb") + .withStyle(GRAY) + ) + ) + ); + tooltip.add(Component.translatable("fluid_tank.polylib.stored") + .withStyle(GOLD) + .append(" ") + .append(Component.literal(FormatUtil.addCommas(fluidStack.getAmount())) + .withStyle(GRAY) + ) + .append(" ") + .append(Component.translatable("fluid_tank.polylib.mb") + .withStyle(GRAY) + ) + .append(Component.literal(String.format(" (%.2f%%)", ((double) fluidStack.getAmount() / (double) capacity) * 100D)) + .withStyle(GRAY) + ) + ); + return tooltip; + }; + } + + //TODO These could maybe go in FluidUtils? but they are client side only so... + + public static int getColour(FluidStack fluidStack) { + return fluidStack.getFluid() == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluidStack.getFluid()).getTintColor(fluidStack); + } + + public static int getColour(Fluid fluid) { + return fluid == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluid).getTintColor(); + } + + @Nullable + public static TextureAtlasSprite getStillTexture(FluidStack stack) { + if (stack.getFluid() == Fluids.EMPTY) return null; + ResourceLocation texture = IClientFluidTypeExtensions.of(stack.getFluid()).getStillTexture(stack); + return Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(texture); + } + + @Nullable + public static TextureAtlasSprite getStillTexture(Fluid fluid) { + if (fluid == Fluids.EMPTY) return null; + ResourceLocation texture = IClientFluidTypeExtensions.of(fluid).getStillTexture(); + return Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(texture); + } + + public record FluidTank(GuiRectangle container, GuiFluidTank tank) {} +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java new file mode 100644 index 00000000..2ff85905 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java @@ -0,0 +1,118 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.HEIGHT; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.WIDTH; + +/** + * A simple gui element that renders an item stack. + * This width and height of this element should be constrained to the same value, + * The stack size is based on the element size. + * constrain size to 16x16 for the standard gui stack size. + *

+ * Created by brandon3055 on 03/09/2023 + */ +public class GuiItemStack extends GuiElement implements BackgroundRender { + private Supplier stack; + private Supplier decorate = () -> true; + private Supplier toolTip = () -> true; + + public GuiItemStack(@NotNull GuiParent parent) { + this(parent, () -> ItemStack.EMPTY); + } + + public GuiItemStack(@NotNull GuiParent parent, ItemStack itemStack) { + super(parent); + setStack(itemStack); + } + + public GuiItemStack(@NotNull GuiParent parent, Supplier provider) { + super(parent); + setStack(provider); + } + + public GuiItemStack setStack(Supplier stackProvider) { + this.stack = stackProvider; + return this; + } + + public GuiItemStack setStack(ItemStack stack) { + this.stack = () -> stack; + return this; + } + + /** + * Enable item stack decorations. + * Meaning, Damage bar, Stack size, Item cool down, etc. (Default Enabled) + */ + public GuiItemStack enableStackDecoration(boolean enableDecoration) { + return enableStackDecoration(() -> enableDecoration); + } + + /** + * Enable item stack decorations. + * Meaning, Damage bar, Stack size, Item cool down, etc. (Default Enabled) + */ + public GuiItemStack enableStackDecoration(Supplier enableDecoration) { + this.decorate = enableDecoration; + return this; + } + + /** + * Enable the default item stack tooltip. (Default Enabled) + * Note: If the {@link GuiItemStack} element has a tooltip applied via one of the element #setTooltip methods, + * That will override the item stack tool tip. + */ + public GuiItemStack enableStackToolTip(boolean enableToolTip) { + return enableStackToolTip(() -> enableToolTip); + } + + /** + * Enable the default item stack tooltip. (Default Enabled) + * Note: If the {@link GuiItemStack} element has a tooltip applied via one of the element #setTooltip methods, + * That will override the item stack tool tip. + */ + public GuiItemStack enableStackToolTip(Supplier enableToolTip) { + this.toolTip = enableToolTip; + return this; + } + + //=== Internal methods ===// + + public double getStackSize() { + return Math.max(getValue(WIDTH), getValue(HEIGHT)); + } + + @Override + public double getBackgroundDepth() { + return getStackSize(); + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + ItemStack stack = this.stack.get(); + if (stack.isEmpty()) return; + + render.renderItem(stack, xMin(), yMin(), getStackSize(), (int) (xMin() + (xSize() * yMin()))); + if (decorate.get()) { + render.renderItemDecorations(stack, xMin(), yMin(), getStackSize()); + } + } + + @Override + public boolean renderOverlay(GuiRender render, double mouseX, double mouseY, float partialTicks, boolean consumed) { + if (super.renderOverlay(render, mouseX, mouseY, partialTicks, consumed)) return true; + if (isMouseOver() && !stack.get().isEmpty()) { + render.renderTooltip(stack.get(), mouseX, mouseY); + return true; + } + return false; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java new file mode 100644 index 00000000..909d5d53 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java @@ -0,0 +1,221 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.SliderState; +import codechicken.lib.gui.modular.lib.geometry.*; +import codechicken.lib.math.MathHelper; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.function.BiFunction; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * GuiList, as the name suggests allows you to display a list of objects. + * The list type can be whatever you want, and you can install a converter to + * map list objects to elements for display. + *

+ * The default converter simply displays the toString() value of the object. + *

+ * Element width will be fixed to the width of the GuiList, element height can be whatever you want. + *

+ * Note on adding child elements to this: + * If any child elements extend beyond the bounds of this element, that part will be culled. + * Also, child elements will always end up bellow the list items when the list is updated. + *

+ * Created by brandon3055 on 21/09/2023 + */ +public class GuiList extends GuiElement> { + + /** + * This is made available primarily for debugging purposes where it can be useful to see what's going on behind the scenes. + */ + public boolean enableScissor = true; + private double yScrollPos = 0; + private double contentHeight = 0; + private double itemSpacing = 1; + private boolean rebuild = true; + private GuiSlider hiddenBar = null; + + private final List listContent = new ArrayList<>(); + private final Map> elementMap = new HashMap<>(); + private final LinkedList> visible = new LinkedList<>(); + + private BiFunction, E, ? extends GuiElement> displayBuilder = (parent, e) -> { + GuiText text = new GuiText(parent, () -> Component.literal(String.valueOf(e))).setWrap(true); + text.constrain(GeoParam.HEIGHT, Constraint.dynamic(() -> (double) font().wordWrapHeight(text.getText(), (int) text.xSize()))); + return text; + }; + + public GuiList(@NotNull GuiParent parent) { + super(parent); + this.setZStacking(false); + this.setRenderCull(getRectangle()); + } + + public boolean add(E e) { + rebuild = true; + return listContent.add(e); + } + + public boolean remove(E e) { + rebuild = true; + return listContent.remove(e); + } + + /** + * You are allowed to modify this list directly, but if you do you must call + * {@link #markDirty()} otherwise the display elements will not get updated. + */ + public List getList() { + return listContent; + } + + public void markDirty() { + this.rebuild = true; + } + + public GuiList setDisplayBuilder(BiFunction, E, ? extends GuiElement> displayBuilder) { + this.displayBuilder = displayBuilder; + return this; + } + + public GuiList setItemSpacing(double itemSpacing) { + this.itemSpacing = itemSpacing; + return this; + } + + public SliderState scrollState() { + return SliderState.forScrollBar(() -> yScrollPos, e -> { + yScrollPos = e; + updateVisible(); + }, () -> MathHelper.clip(ySize() / contentHeight, 0, 1)); + } + + /** + * You can choose to attach a scroll bar to this element the same way you would a {@link GuiScrolling} + * But sometimes you just want to be able to mouse-wheel scroll without an actual scroll bar. + *

+ * This method will add a hidden scroll bar to enable mouse wheel scrolling and middle-click dragging without the need for an actual scroll bar. + * The scroll bar will be an invisible zero width element on the right side of this list. + */ + public GuiList addHiddenScrollBar() { + if (hiddenBar != null) removeChild(hiddenBar); + hiddenBar = new GuiSlider(this, Axis.Y) + .setSliderState(scrollState()) + .setScrollableElement(this) + .constrain(TOP, match(get(TOP))) + .constrain(LEFT, relative(get(RIGHT), -5)) + .constrain(BOTTOM, match(get(BOTTOM))) + .constrain(RIGHT, match(get(RIGHT))); + return this; + } + + public GuiList removeHiddenScrollBar() { + if (hiddenBar != null) removeChild(hiddenBar); + return this; + } + + //=== Internal Logic ===// + + public double hiddenSize() { + return Math.max(contentHeight - ySize(), 0); + } + + @Override + public void tick(double mouseX, double mouseY) { + if (rebuild) { + rebuildElements(); + } + super.tick(mouseX, mouseY); + } + + public void rebuildElements() { + elementMap.values().forEach(this::removeChild); + elementMap.clear(); + + for (E item : listContent) { + GuiElement next = displayBuilder.apply(this, item); + next.constrain(LEFT, match(get(LEFT))); + next.constrain(RIGHT, match(get(RIGHT))); + removeChild(next); + elementMap.put(item, next); + } + rebuild = false; + updateVisible(); + } + + public Map> getElementMap() { + return elementMap; + } + + public void scrollTo(E scrollTo) { + if (rebuild) { + rebuild = false; + rebuildElements(); + } + + if (elementMap.containsKey(scrollTo)) { + scrollState().setPos(0); + double yMax = yMin(); + + for (E item : getList()) { + GuiElement e = elementMap.get(item); + if (e != null) { + yMax += e.ySize() + 1; + if (item.equals(scrollTo)) break; + } + } + + if (yMax > yMax()) { + double move = yMax - yMax(); + scrollState().setPos(move / hiddenSize()); + } + } + } + + private void updateVisible() { + visible.forEach(this::removeChild); + visible.clear(); + contentHeight = 0; + if (listContent.isEmpty()) return; + + for (GuiElement item : elementMap.values()) { + contentHeight += item.ySize() + itemSpacing; + } + contentHeight -= itemSpacing; + + double winTop = yMin(); + double winBottom = yMax(); + + double yPos = winTop + (yScrollPos * -hiddenSize()); + for (E item : listContent) { + GuiElement element = elementMap.get(item); + if (element == null) continue; + double top = yPos; + double bottom = yPos + element.ySize(); + + if ((top >= winTop && top <= winBottom) || (bottom >= winTop && bottom <= winBottom)) { + addChild(element); + visible.add(element); + element.constrain(TOP, literal(top)); + } + yPos = bottom + itemSpacing; + } + } + + @Override + public boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return super.blockMouseOver(element, mouseX, mouseY) || (element.isDescendantOf(this) && !isMouseOver()); + } + + @Override + public void render(GuiRender render, double mouseX, double mouseY, float partialTicks) { + if (enableScissor) render.pushScissorRect(getRectangle()); + super.render(render, mouseX, mouseY, partialTicks); + if (enableScissor) render.popScissor(); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java new file mode 100644 index 00000000..d95835e4 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java @@ -0,0 +1,401 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.gui.modular.lib.CursorHelper; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.literal; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This element can be used to create movable/resizable guis of gui elements. + * This is achieved via a "contentElement" to which all child elements should eb attached. + * Initially the bounds of the content element will match the parent {@link GuiManipulable} element. + * However, depending on which features are enabled, it is possible for the user to resize the + * content element by clicking and dragging the edges, or move the element by clicking and dragging + * a specified "dragArea". + *

+ * It should be noted that the constraints on the underlying {@link GuiManipulable} should be fairly rigid. + * Things like dynamic constraint changes will not translate through to the contentElement, + *

+ * If a UI resize occurs the content element's bounds will be reset to default. + * You can also trigger a manual reset by calling {@link #resetBounds()} + *

+ * Created by brandon3055 on 13/11/2023 + */ +public class GuiManipulable extends GuiElement implements ContentElement> { + private final GuiElement contentElement; + + private int dragXOffset = 0; + private int dragYOffset = 0; + private boolean isDragging = false; + private boolean dragPos = false; + private boolean dragTop = false; + private boolean dragLeft = false; + private boolean dragBottom = false; + private boolean dragRight = false; + private boolean enableCursors = false; + + //Made available for external position restraints + public int xMin = 0; + public int xMax = 0; + public int yMin = 0; + public int yMax = 0; + + protected Rectangle minSize = Rectangle.create(0, 0, 50, 50); + protected Rectangle maxSize = Rectangle.create(0, 0, 256, 256); + protected Runnable onMovedCallback = null; + protected Runnable onResizedCallback = null; + protected PositionRestraint positionRestraint = draggable -> { + if (xMin < 0) { + int move = -xMin; + xMin += move; + xMax += move; + } else if (xMax > scaledScreenWidth()) { + int move = xMax - scaledScreenWidth(); + xMin -= move; + xMax -= move; + } + if (yMin < 0) { + int move = -yMin; + yMin += move; + yMax += move; + } else if (yMax > scaledScreenHeight()) { + int move = yMax - scaledScreenHeight(); + yMin -= move; + yMax -= move; + } + }; + + private GuiElement moveHandle; + private GuiElement leftHandle; + private GuiElement rightHandle; + private GuiElement topHandle; + private GuiElement bottomHandle; + + public GuiManipulable(@NotNull GuiParent parent) { + super(parent); + this.contentElement = new GuiElement<>(this) + .constrain(LEFT, Constraint.dynamic(() -> (double) xMin)) + .constrain(RIGHT, Constraint.dynamic(() -> (double) xMax)) + .constrain(TOP, Constraint.dynamic(() -> (double) yMin)) + .constrain(BOTTOM, Constraint.dynamic(() -> (double) yMax)); + moveHandle = new GuiRectangle(contentElement); + leftHandle = new GuiRectangle(contentElement); + rightHandle = new GuiRectangle(contentElement); + topHandle = new GuiRectangle(contentElement); + bottomHandle = new GuiRectangle(contentElement); + } + + public GuiManipulable resetBounds() { + xMin = (int)xMin(); + xMax = (int)xMax(); + yMin = (int)yMin(); + yMax = (int)yMax(); + return this; + } + + @Override + public GuiManipulable constrain(GeoParam param, @Nullable Constraint constraint) { + return super.constrain(param, constraint).resetBounds(); //TODO, This will break if strict constraints are enabled... + } + + @Override + public void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + super.onScreenInit(mc, font, screenWidth, screenHeight); + resetBounds(); + } + + @Override + public GuiElement getContentElement() { + return contentElement; + } + + public GuiManipulable addResizeHandles(int handleSize, boolean includeTopHandle) { + if (includeTopHandle) addTopHandle(handleSize); + addLeftHandle(handleSize); + addRightHandle(handleSize); + addBottomHandle(handleSize); + return this; + } + + public GuiManipulable addTopHandle(int handleSize) { + this.topHandle + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(HEIGHT, literal(handleSize)); + return this; + } + + public GuiManipulable addBottomHandle(int handleSize) { + this.bottomHandle + .constrain(BOTTOM, match(contentElement.get(BOTTOM))) + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(HEIGHT, literal(handleSize)); + return this; + } + + public GuiManipulable addLeftHandle(int handleSize) { + this.leftHandle + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(BOTTOM, match(contentElement.get(BOTTOM))) + .constrain(WIDTH, literal(handleSize)); + return this; + } + + public GuiManipulable addRightHandle(int handleSize) { + this.rightHandle + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(BOTTOM, match(contentElement.get(BOTTOM))) + .constrain(WIDTH, literal(handleSize)); + return this; + } + + public GuiManipulable addMoveHandle(int handleSize) { + this.moveHandle + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(HEIGHT, literal(handleSize)); + return this; + } + + /** + * You can use this to retrieve the current move handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getMoveHandle() { + return moveHandle; + } + + /** + * You can use this to retrieve the current left resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getLeftHandle() { + return leftHandle; + } + + /** + * You can use this to retrieve the current right resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getRightHandle() { + return rightHandle; + } + + /** + * You can use this to retrieve the current top resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getTopHandle() { + return topHandle; + } + + /** + * You can use this to retrieve the current bottom resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getBottomHandle() { + return bottomHandle; + } + + /** + * Enables rendering of custom mouse cursors when hovering over a draggable handle. + */ + public GuiManipulable enableCursors(boolean enableCursors) { + this.enableCursors = enableCursors; + return this; + } + + public GuiManipulable setOnMovedCallback(Runnable onMovedCallback) { + this.onMovedCallback = onMovedCallback; + return this; + } + + public GuiManipulable setOnResizedCallback(Runnable onResizedCallback) { + this.onResizedCallback = onResizedCallback; + return this; + } + + public GuiManipulable setPositionRestraint(PositionRestraint positionRestraint) { + this.positionRestraint = positionRestraint; + return this; + } + + public void setMinSize(Rectangle minSize) { + this.minSize = minSize; + } + + public void setMaxSize(Rectangle maxSize) { + this.maxSize = maxSize; + } + + public Rectangle getMinSize() { + return minSize; + } + + public Rectangle getMaxSize() { + return maxSize; + } + + + @Override + public void tick(double mouseX, double mouseY) { + if (enableCursors) { + boolean posFlag = moveHandle != null && moveHandle.isMouseOver(); + boolean topFlag = topHandle != null && topHandle.isMouseOver(); + boolean leftFlag = leftHandle != null && leftHandle.isMouseOver(); + boolean bottomFlag = bottomHandle != null && bottomHandle.isMouseOver(); + boolean rightFlag = rightHandle != null && rightHandle.isMouseOver(); + boolean any = posFlag || topFlag || leftFlag || bottomFlag || rightFlag; + + if (any) { + if (posFlag) { + getModularGui().setCursor(CursorHelper.DRAG); + } else if ((topFlag && leftFlag) || (bottomFlag && rightFlag)) { + getModularGui().setCursor(CursorHelper.RESIZE_TLBR); + } else if ((topFlag && rightFlag) || (bottomFlag && leftFlag)) { + getModularGui().setCursor(CursorHelper.RESIZE_TRBL); + } else if (topFlag || bottomFlag) { + getModularGui().setCursor(CursorHelper.RESIZE_V); + } else { + getModularGui().setCursor(CursorHelper.RESIZE_H); + } + } + } + + super.tick(mouseX, mouseY); + } + + public void startDragging() { + double mouseX = getModularGui().computeMouseX(); + double mouseY = getModularGui().computeMouseY(); + dragXOffset = (int) (mouseX - xMin); + dragYOffset = (int) (mouseY - yMin); + isDragging = true; + dragPos = true; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (super.mouseClicked(mouseX, mouseY, button)) return true; + + boolean posFlag = moveHandle != null && moveHandle.isMouseOver(); + boolean topFlag = topHandle != null && topHandle.isMouseOver(); + boolean leftFlag = leftHandle != null && leftHandle.isMouseOver(); + boolean bottomFlag = bottomHandle != null && bottomHandle.isMouseOver(); + boolean rightFlag = rightHandle != null && rightHandle.isMouseOver(); + + if (posFlag || topFlag || leftFlag || bottomFlag || rightFlag) { + dragXOffset = (int) (mouseX - xMin); + dragYOffset = (int) (mouseY - yMin); + isDragging = true; + if (posFlag) { + dragPos = true; + } else { + dragTop = topFlag; + dragLeft = leftFlag; + dragBottom = bottomFlag; + dragRight = rightFlag; + } + return true; + } + + return false; + } + + @Override + public void mouseMoved(double mouseX, double mouseY) { + if (isDragging) { + int xMove = (int) (mouseX - dragXOffset) - xMin; + int yMove = (int) (mouseY - dragYOffset) - yMin; + if (dragPos) { + Rectangle previous = Rectangle.create(xMin, yMin, xMax - xMin, yMax - yMin); + xMin += xMove; + xMax += xMove; + yMin += yMove; + yMax += yMove; + validatePosition(); + onMoved(); + } else { + Rectangle min = getMinSize(); + Rectangle max = getMaxSize(); + if (dragTop) { + yMin += yMove; + if (yMax - yMin < min.height()) yMin = yMax - (int) min.height(); + if (yMax - yMin > max.height()) yMin = yMax - (int) max.height(); + if (yMin < 0) yMin = 0; + } + if (dragLeft) { + xMin += xMove; + if (xMax - xMin < min.width()) xMin = xMax - (int) min.width(); + if (xMax - xMin > max.width()) xMin = xMax - (int) max.width(); + if (xMin < 0) xMin = 0; + } + if (dragBottom) { + yMax = yMin + (dragYOffset + yMove); + if (yMax - yMin < min.height()) yMax = yMin + (int) min.height(); + if (yMax - yMin > max.height()) yMax = yMin + (int) max.height(); + if (yMax > scaledScreenHeight()) yMax = scaledScreenHeight(); + } + if (dragRight) { + xMax = xMin + (dragXOffset + xMove); + if (xMax - xMin < min.width()) xMax = xMin + (int) min.width(); + if (xMax - xMin > max.width()) xMax = xMin + (int) max.width(); + if (xMax > scaledScreenWidth()) xMax = scaledScreenWidth(); + } + validatePosition(); + onResized(); + } + } + super.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + if (isDragging) { + validatePosition(); + } + isDragging = dragPos = dragTop = dragLeft = dragBottom = dragRight = false; + return super.mouseReleased(mouseX, mouseY, button, consumed); + } + + protected void validatePosition() { + double x = xMin; + double y = yMin; + positionRestraint.restrainPosition(this); + if ((x != xMin || y != yMin) && onMovedCallback != null) { + onMovedCallback.run(); + } + } + + protected void onMoved() { + if (onMovedCallback != null) { + onMovedCallback.run(); + } + } + + protected void onResized() { + if (onResizedCallback != null) { + onResizedCallback.run(); + } + } + + public interface PositionRestraint { + void restrainPosition(GuiManipulable draggable); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java new file mode 100644 index 00000000..3e56ce61 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java @@ -0,0 +1,115 @@ +package codechicken.lib.gui.modular.elements; + + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.Axis; +import codechicken.lib.gui.modular.lib.geometry.Direction; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.sprite.Material; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * This can be used to create a simple progress indicator like those used in machines like furnaces. + *

+ * The background texture (if one is used) and the animated texture must be the same shape and size, + * They must be designed so that the animated texture can be rendered directly on top of the background texture with no offset. + * The animated texture should not have any empty space on ether end as the entire width of the texture is used in the animation. + *

+ * Texture must be designed for left to right animation, + *

+ * Created by brandon3055 on 04/09/2023 + */ +public class GuiProgressIcon extends GuiElement implements BackgroundRender { + + private Material background = null; + private Material animated; + private Supplier progress = () -> 0D; + private Direction direction = Direction.RIGHT; + + public GuiProgressIcon(@NotNull GuiParent parent, Material animated) { + super(parent); + this.animated = animated; + } + + public GuiProgressIcon(@NotNull GuiParent parent, Material background, Material animated) { + super(parent); + this.background = background; + this.animated = animated; + } + + public GuiProgressIcon(@NotNull GuiParent parent) { + super(parent); + } + + /** + * Set the direction this progress icon is pointing, Default is RIGHT + */ + public GuiProgressIcon setDirection(Direction direction) { + this.direction = direction; + return this; + } + + /** + * Sets the background texture, aka the "empty" texture. + */ + public GuiProgressIcon setBackground(@Nullable Material background) { + this.background = background; + return this; + } + + /** + * Sets the texture that will be animated. + */ + public GuiProgressIcon setAnimated(Material animated) { + this.animated = animated; + return this; + } + + /** + * Set the current progress to a fixed value. + * + * @see #setProgress(Supplier) + */ + public GuiProgressIcon setProgress(double progress) { + return setProgress(() -> progress); + } + + /** + * Attach a supplier that returns the current progress value for this progress icon (0 to 1) + */ + public GuiProgressIcon setProgress(Supplier progress) { + this.progress = progress; + return this; + } + + public double getProgress() { + return progress.get(); + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + render.pose().pushPose(); + + double width = direction.getAxis() == Axis.X ? xSize() : ySize(); + double height = direction.getAxis() == Axis.X ? ySize() : xSize(); + + render.pose().translate(xMin() + (xSize() / 2), yMin() + (ySize() / 2), 0); + render.pose().mulPose(com.mojang.math.Axis.ZP.rotationDegrees((float) Direction.RIGHT.rotationTo(direction))); + + double halfWidth = width / 2; + double halfHeight = height / 2; + if (background != null) { + render.tex(background, -halfWidth, -halfHeight, halfWidth, halfHeight, 0xFFFFFFFF); + } + + if (animated == null) return; + float progress = (float) getProgress(); + render.partialSprite(animated.renderType(GuiRender::texColType), -halfWidth, -halfHeight, -halfWidth + (width* progress), -halfHeight + height, animated.sprite(), 0F, 0F, progress, 1F, 0xFFFFFFFF); + + render.pose().popPose(); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java new file mode 100644 index 00000000..0d034702 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java @@ -0,0 +1,165 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +/** + * Used to draw a simple rectangle on the screen. + * Can specify separate (or no) border colours and fill colours. + * Can also render using the "shadedRectangle" render type. + *

+ * Created by brandon3055 on 28/08/2023 + */ +public class GuiRectangle extends GuiElement implements BackgroundRender { + private Supplier fill = null; + private Supplier border = null; + + private Supplier borderWidth = () -> 1D; + + private Supplier shadeTopLeft; + private Supplier shadeBottomRight; + private Supplier shadeCorners; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiRectangle(@NotNull GuiParent parent) { + super(parent); + } + + /** + * Creates a rectangle that mimics the appearance of a vanilla inventory slot. + * Uses shadedRect to create the 3D "inset" look. + */ + public static GuiRectangle vanillaSlot(@NotNull GuiParent parent) { + return new GuiRectangle(parent).shadedRect(0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); + } + + /** + * Creates a rectangle that mimics the appearance of a vanilla inventory slot, except inverted + * Uses shadedRect to create the 3D "popped out" appearance + */ + public static GuiRectangle invertedSlot(@NotNull GuiParent parent) { + return new GuiRectangle(parent).shadedRect(0xFFffffff, 0xFF373737, 0xFF8b8b8b, 0xFF8b8b8b); + } + + /** + * Creates a rectangle similar in appearance to a vanilla button, but with no texture and no black border. + */ + public static GuiRectangle planeButton(@NotNull GuiParent parent) { + return new GuiRectangle(parent).shadedRect(0xFFaaaaaa, 0xFF545454, 0xFF6f6f6f); + } + + public static GuiRectangle toolTipBackground(@NotNull GuiParent parent) { + return toolTipBackground(parent, 0xF0100010, 0x505000FF, 0x5028007f); + } + + public static GuiRectangle toolTipBackground(@NotNull GuiParent parent, int backgroundColour, int borderColourTop, int borderColourBottom) { + return toolTipBackground(parent, backgroundColour, backgroundColour, borderColourTop, borderColourBottom); + } + + public static GuiRectangle toolTipBackground(@NotNull GuiParent parent, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom) { + return new GuiRectangle(parent) { + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + render.toolTipBackground(xMin(), yMin(), xSize(), ySize(), backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false); + } + }; + } + + public GuiRectangle border(int border) { + return border(() -> border); + } + + public GuiRectangle border(Supplier border) { + this.border = border; + return this; + } + + public GuiRectangle fill(int fill) { + return fill(() -> fill); + } + + public GuiRectangle fill(Supplier fill) { + this.fill = fill; + return this; + } + + public GuiRectangle rectangle(int fill, int border) { + return rectangle(() -> fill, () -> border); + } + + public GuiRectangle rectangle(Supplier fill, Supplier border) { + this.fill = fill; + this.border = border; + return this; + } + + public GuiRectangle shadedRect(int topLeft, int bottomRight, int fill) { + return shadedRect(() -> topLeft, () -> bottomRight, () -> fill); + } + + public GuiRectangle shadedRect(Supplier topLeft, Supplier bottomRight, Supplier fill) { + return shadedRect(topLeft, bottomRight, () -> GuiRender.midColour(topLeft.get(), bottomRight.get()), fill); + } + + public GuiRectangle shadedRect(int topLeft, int bottomRight, int cornerMix, int fill) { + return shadedRect(() -> topLeft, () -> bottomRight, () -> cornerMix, () -> fill); + } + + public GuiRectangle shadedRect(Supplier topLeft, Supplier bottomRight, Supplier cornerMix, Supplier fill) { + this.fill = fill; + this.shadeTopLeft = topLeft; + this.shadeBottomRight = bottomRight; + this.shadeCorners = cornerMix; + return this; + } + + public GuiRectangle setShadeTopLeft(Supplier shadeTopLeft) { + this.shadeTopLeft = shadeTopLeft; + return this; + } + + public GuiRectangle setShadeBottomRight(Supplier shadeBottomRight) { + this.shadeBottomRight = shadeBottomRight; + return this; + } + + public GuiRectangle setShadeCorners(Supplier shadeCorners) { + this.shadeCorners = shadeCorners; + return this; + } + + public GuiRectangle setShadeCornersAuto() { + this.shadeCorners = () -> GuiRender.midColour(shadeTopLeft.get(), shadeBottomRight.get()); + return this; + } + + public GuiRectangle borderWidth(double borderWidth) { + return borderWidth(() -> borderWidth); + } + + public GuiRectangle borderWidth(Supplier borderWidth) { + this.borderWidth = borderWidth; + return this; + } + + public double getBorderWidth() { + return borderWidth.get(); + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + if (shadeTopLeft != null && shadeBottomRight != null && shadeCorners != null) { + render.shadedRect(getRectangle(), getBorderWidth(), shadeTopLeft.get(), shadeBottomRight.get(), shadeCorners.get(), fill == null ? 0 : fill.get()); + } else if (border != null) { + render.borderRect(getRectangle(), getBorderWidth(), fill == null ? 0 : fill.get(), border.get()); + } else if (fill != null) { + render.rect(getRectangle(), fill.get()); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java new file mode 100644 index 00000000..c0c5f9e0 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java @@ -0,0 +1,219 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.SliderState; +import codechicken.lib.gui.modular.lib.geometry.Axis; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.math.MathHelper; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.relative; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * So the logic behind this element is as follows. + * This element contains a base "Content Element" that holds all the scrollable content. + * The content element's position is controlled by the {@link GuiScrolling} + * But its {@link GeoParam#WIDTH} and {@link GeoParam#HEIGHT} constraints can be set by the user, + * Or they can be set to dynamically adjust to the child elements added to it. + *

+ * The bounds of the {@link GuiScrolling} represent the "view window" + * When scrolling up/down, left/right the Content Element is effectively just moving around behind the view window + * and everything outside the view window is scissored off. + * Any events that occur outside the view window are not propagated to scroll element. + * Calls to {@link #isMouseOver()} from an area of an element that is outside the view window will return false. + *

+ * Elements that are completely outside the view window will not be rendered at all for efficiency. + *

+ * Created by brandon3055 on 01/09/2023 + */ +public class GuiScrolling extends GuiElement implements ContentElement> { + + /** + * This is made available primarily for debugging purposes where it can be useful to see what's going on behind the scenes. + */ + public boolean enableScissor = true; + private GuiElement contentElement; + private double xScrollPos = 0; + private double yScrollPos = 0; + private double contentWidth = 0; + private double contentHeight = 0; + private boolean setup = false; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiScrolling(@NotNull GuiParent parent) { + super(parent); + installContainerElement(new ContentElement(this)); + } + + //=== Scroll element setup ===// + + /** + * Retrieves the content element that holds all the scrolling elements. + * You must add all of your scrolling content to this element. + * Scrolling content must also be constrained relative to this element. + *

+ * The {@link GeoParam#TOP} and {@link GeoParam#LEFT} constraints for this element are set by the {@link GuiScrolling} and must not be overridden. + * These are used to control the 'scrolling' of the element. + *

+ * By default, the {@link GeoParam#WIDTH} and {@link GeoParam#HEIGHT} (and therefor also BOTTOM, RIGHT) are dynamically constrained to match the outer bounds of the scrolling elements. + * So attempting to constrain the content to any of these dynamic parameters would result in a stack overflow. + * You can however override the WIDTH and HEIGHT constraints if you wish. + * This can be useful if you wish to create something like a fixed width scrolling list where the width of each scrolling element is bound to the width of the list. + *

+ * The most important thing to note, Especially when manually constraining the WIDTH and HEIGHT of the content element, + * All scrolling elements must be withing the bounds of the content element. Anything outside the content element's bounds will not be visible. + * + * @return The content element. + */ + @Override + public GuiElement getContentElement() { + return contentElement; + } + + /** + * This allows you to install a custom container element. + * The elements constraints will automatically be set by this method. + *

+ * After calling this method you may override the container element WIDTH and HEIGHT constraints as described in the documentation for {@link #getContentElement()} + * But you must not touch the TOP or LEFT constraints. + *

+ * Important thing to note, By default the container element is preinstalled before any children can be added, meaning any children added to the {@link GuiScrolling} + * will render on top of the scrolling content. + * As this method allows you to set a new child as the container element, any children added before the new content element, will render under the content element. + * + * @param element The new container element. + */ + public void installContainerElement(GuiElement element) { + if (element.getParent() != this) throw new IllegalStateException("Content element must be a child of the GuiScrollingBase it is being installed in"); + if (contentElement != null) removeChild(contentElement); + setup = true; + contentElement = element; + contentElement.setRenderCull(getRectangle()); + contentElement.constrain(TOP, Constraint.relative(get(TOP), () -> yScrollPos * -hiddenSize(Axis.Y))); + contentElement.constrain(LEFT, Constraint.relative(get(LEFT), () -> xScrollPos * -hiddenSize(Axis.X))); + contentElement.constrain(WIDTH, Constraint.dynamic(() -> contentElement.getChildBounds().xMax() - contentElement.xMin())); + contentElement.constrain(HEIGHT, Constraint.dynamic(() -> contentElement.getChildBounds().yMax() - contentElement.yMin())); + setup = false; + } + + /** + * @return a {@link SliderState} that can be used to get or control the scroll position of the specified axis. + */ + public SliderState scrollState(Axis axis) { + return switch (axis) { + case X -> SliderState.forScrollBar(() -> xScrollPos, e -> xScrollPos = e, () -> MathHelper.clip(xSize() / contentElement.xSize(), 0, 1)); + case Y -> SliderState.forScrollBar(() -> yScrollPos, e -> yScrollPos = e, () -> MathHelper.clip(ySize() / contentElement.ySize(), 0, 1)); + }; + } + + //=== Internal logic ===// + + /** + * @return the total content size / length for the given axis + */ + public double totalSize(Axis axis) { + return switch (axis) { + case X -> contentWidth; + case Y -> contentHeight; + }; + } + + /** + * @return the hidden content size / length for the given axis (How much of the content is outside the view area) + */ + public double hiddenSize(Axis axis) { + return switch (axis) { + case X -> Math.max(contentWidth - xSize(), 0); + case Y -> Math.max(contentHeight - ySize(), 0); + }; + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + //These can not be generated dynamically, Doing so would result in a calculation loop, aka a stack overflow. + contentWidth = contentElement.xSize(); + contentHeight = contentElement.ySize(); + } + + @Override + public boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return super.blockMouseOver(element, mouseX, mouseY) || (element.isDescendantOf(contentElement) && !this.isMouseOver()); + } + + //=== Rendering ===// + + @Override + protected boolean renderChild(GuiElement child, GuiRender render, double mouseX, double mouseY, float partialTicks) { + boolean scissor = child == contentElement && enableScissor; + if (scissor) render.pushScissorRect(getRectangle()); + boolean ret = super.renderChild(child, render, mouseX, mouseY, partialTicks); + if (scissor) render.popScissor(); + return ret; + } + + private class ContentElement extends GuiElement { + /** + * @param parent parent {@link GuiParent}. + */ + public ContentElement(@NotNull GuiParent parent) { + super(parent); + } + + @Override + public ContentElement constrain(GeoParam param, @Nullable Constraint constraint) { + if (!setup && (param == TOP || param == LEFT)) throw new IllegalStateException("Can not override TOP or LEFT constraints on content element, These are used to control the scrolling behavior!"); + return super.constrain(param, constraint); + } + } + + public static ScrollWindow simpleScrollWindow(@NotNull GuiParent parent, boolean verticalScrollBar, boolean horizontalScrollBar) { + GuiElement container = new GuiElement<>(parent); + GuiRectangle background = GuiRectangle.vanillaSlot(container) + .constrain(TOP, match(container.get(TOP))) + .constrain(LEFT, match(container.get(LEFT))) + .constrain(BOTTOM, relative(container.get(BOTTOM), horizontalScrollBar ? -10 : 0)) + .constrain(RIGHT, relative(container.get(RIGHT), verticalScrollBar ? -10 : 0)); + + GuiScrolling scroll = new GuiScrolling(background); + Constraints.bind(scroll, background, 1); + + GuiSlider.ScrollBar verticalBar = null; + if (verticalScrollBar) { + verticalBar = GuiSlider.vanillaScrollBar(container, Axis.Y); + verticalBar.container() + .constrain(TOP, match(container.get(TOP))) + .constrain(BOTTOM, relative(container.get(BOTTOM), horizontalScrollBar ? -10 : 0)) + .constrain(RIGHT, match(container.get(RIGHT))) + .constrain(WIDTH, Constraint.literal(9)); + verticalBar.slider() + .setSliderState(scroll.scrollState(Axis.Y)) + .setScrollableElement(scroll); + } + GuiSlider.ScrollBar horizontalBar = null; + if (horizontalScrollBar) { + horizontalBar = GuiSlider.vanillaScrollBar(container, Axis.X); + horizontalBar.container() + .constrain(BOTTOM, match(container.get(BOTTOM))) + .constrain(LEFT, match(container.get(LEFT))) + .constrain(RIGHT, relative(container.get(RIGHT), verticalScrollBar ? -10 : 0)) + .constrain(HEIGHT, Constraint.literal(9)); + horizontalBar.slider() + .setSliderState(scroll.scrollState(Axis.X)) + .setScrollableElement(scroll); + } + return new ScrollWindow(container, scroll, verticalBar, horizontalBar); + } + + public record ScrollWindow(GuiElement container, GuiScrolling scrolling, @Nullable GuiSlider.ScrollBar verticalBar, @Nullable GuiSlider.ScrollBar horizontalBar) { + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java new file mode 100644 index 00000000..2157ccf8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java @@ -0,0 +1,266 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.geometry.*; +import codechicken.lib.math.MathHelper; +import org.jetbrains.annotations.NotNull; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This can be used as the base for anything that requires the linear movement of an element between two position. + * e.g. Scroll bars, Slide controls and slide indicators. + *

+ * Implementation is simple, Simply install a "Slide Element", this will be the moving element, + * The movement of this element is confined to the bounds og the {@link GuiSlider} + *

+ * The position of the slider is managed via the installed {@link SliderState} + *

+ * Created by brandon3055 on 02/09/2023 + */ +public class GuiSlider extends GuiElement { + private final Axis axis; + private SliderState state = SliderState.create(0.1); + private GuiElement slider; + private double outOfBoundsDist = 50; + private GuiElement scrollableElement; + + private int dragButton = GuiButton.LEFT_CLICK; + private int scrollDragButton = GuiButton.MIDDLE_CLICK; + private boolean middleClickScroll = false; + /** + * This should theoretically never be needed, But just in case... + */ + public boolean invertDragScroll = false; + + private boolean dragging = false; + private double slideStartPos = 0; + private Position clickPos = Position.create(0, 0); + private boolean scrollableDragging = false; + + /** + * Creates a basic gui slider that moves along the specified axis. + * This includes a default slider element the width of which is bound to the GuiSlider, + * And the length of which is controlled by {@link SliderState#sliderRatio()} + */ + public GuiSlider(@NotNull GuiParent parent, Axis axis) { + super(parent); + this.axis = axis; + installSlider(new GuiElement<>(this)); + bindSliderLength(); + bindSliderWidth(); + } + + public GuiSlider(@NotNull GuiParent parent, Axis axis, GuiElement slider) { + super(parent); + this.axis = axis; + installSlider(slider); + } + + /** + * Vanilla does not really seem to have a standard for its scroll bars, + * But this is something that should at least fit in to a typical vanilla gui. + */ + public static ScrollBar vanillaScrollBar(GuiElement parent, Axis axis) { + GuiRectangle background = GuiRectangle.vanillaSlot(parent); + + GuiSlider slider = new GuiSlider(background, axis); + Constraints.bind(slider, background, 1); + + slider.installSlider(GuiRectangle.planeButton(slider)) + .bindSliderLength() + .bindSliderWidth(); + + GuiRectangle sliderHighlight = new GuiRectangle(slider.getSlider()) + .fill(0x5000b6FF) + .setEnabled(() -> slider.getSlider().isMouseOver()); + + Constraints.bind(sliderHighlight, slider.getSlider()); + + return new ScrollBar(background, slider, sliderHighlight); + } + + /** + * Set the slider state used by this slider element. + * The slider state is used to get and set the slider position. + * It also controls scroll speed. + */ + public GuiSlider setSliderState(SliderState state) { + this.state = state; + return this; + } + + /** + * For use cases where this slider is controlling something like a scroll element. + * This enables scrolling when the cursor is over the scrollable element. + * It can also enable scrolling via middle-click + drag. + */ + public GuiSlider setScrollableElement(GuiElement scrollableElement) { + return setScrollableElement(scrollableElement, true); + } + + /** + * For use cases where this slider is controlling something like a scroll element. + * This enables scrolling when the cursor is over the scrollable element. + * It can also enable scrolling via middle-click + drag. + */ + public GuiSlider setScrollableElement(GuiElement scrollableElement, boolean middleClickScroll) { + this.scrollableElement = scrollableElement; + this.middleClickScroll = middleClickScroll; + return this; + } + + /** + * Install an element to be used as the sliding element. + * The sliders minimum position (meaning either LEFT or TOP) on the moving axis will be constrained the {@link GuiSlider} + * Attempting to override this constraint after installing the slider element will break the slider. + *

+ * The size constraints, and position constraint for the non-moving axis need to be set by the implementor. + * + * @see #bindSliderLength() + * @see #bindSliderWidth() + */ + public GuiSlider installSlider(GuiElement slider) { + if (slider.getParent() != this) throw new IllegalStateException("slider element must be a child of the GuiSlider it is being installed in"); + if (this.slider != null) removeChild(this.slider); + this.slider = slider; + switch (axis) { + case X -> slider.constrain(LEFT, Constraint.relative(get(LEFT), () -> (getValue(WIDTH) - slider.getValue(WIDTH)) * state.getPos())); + case Y -> slider.constrain(TOP, Constraint.relative(get(TOP), () -> (getValue(HEIGHT) - slider.getValue(HEIGHT)) * state.getPos())); + } + return this; + } + + /** + * Sets up constraints to automatically control the slider element length. + * The slider element length will be controlled by {@link SliderState#sliderRatio()} + * This is used for things like gui scroll bars where the bar length changes based on the ratio of content in view. + */ + public GuiSlider bindSliderLength() { + switch (axis) {//Ensure we don't accidentally over-constrain + case X -> slider.constrain(RIGHT, null).constrain(WIDTH, Constraint.dynamic(() -> getValue(WIDTH) * state.sliderRatio())); + case Y -> slider.constrain(BOTTOM, null).constrain(HEIGHT, Constraint.dynamic(() -> getValue(HEIGHT) * state.sliderRatio())); + } + return this; + } + + /** + * Binds the sliders position and size on the non-moving axis to the width and pos of the {@link GuiSlider} + */ + public GuiSlider bindSliderWidth() { + switch (axis) {//Ensure we don't accidentally over-constrain + case X -> slider.constrain(HEIGHT, null).constrain(TOP, Constraint.match(get(TOP))).constrain(BOTTOM, Constraint.match(get(BOTTOM))); + case Y -> slider.constrain(WIDTH, null).constrain(LEFT, Constraint.match(get(LEFT))).constrain(RIGHT, Constraint.match(get(RIGHT))); + } + return this; + } + + /** + * @return the installed slider element. + */ + public GuiElement getSlider() { + return slider; + } + + /** + * @return True if the slider is currently being dragged by the user. + */ + public boolean isDragging() { + return dragging; + } + + /** + * Set the out-of-bounds distance, + * If the cursor is dragged more than this distance from the slider bounds on the no-moving axis, + * the slider will snap back to its original position until the cursor moves back into bounds. + * Default is 50, -1 will disable the snap-back functionality. + */ + public GuiSlider setOutOfBoundsDist(double outOfBoundsDist) { + this.outOfBoundsDist = outOfBoundsDist; + return this; + } + + /** + * @param dragButton The mouse button used to drag this slider (Default {@link GuiButton#LEFT_CLICK}) + */ + public GuiSlider setDragButton(int dragButton) { + this.dragButton = dragButton; + return this; + } + + /** + * @param scrollDragButton The button used to scroll by clicking and dragging the defined scrollableElement (Default {@link GuiButton#MIDDLE_CLICK}) + * @see #setScrollableElement(GuiElement, boolean) + */ + public GuiSlider setScrollDragButton(int scrollDragButton) { + this.scrollDragButton = scrollDragButton; + return this; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + dragging = false; + clickPos = Position.create(mouseX, mouseY); + slideStartPos = state.getPos(); + if (button == dragButton && isMouseOver()) { + if (!slider.isMouseOver()) { + clickPos = Position.create(slider.xCenter(), slider.yCenter()); + handleDrag(mouseX, mouseY); + } + dragging = true; + return true; + } + if (button == scrollDragButton && scrollableElement != null && scrollableElement.isMouseOver()) { + scrollableDragging = true; + } + return false; + } + + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + dragging = scrollableDragging = false; + return super.mouseReleased(mouseX, mouseY, button, consumed); + } + + @Override + public void mouseMoved(double mouseX, double mouseY) { + if (dragging || (scrollableDragging && scrollableElement != null)) { + handleDrag(mouseX, mouseY); + } + super.mouseMoved(mouseX, mouseY); + } + + private void handleDrag(double mouseX, double mouseY) { + Position mousePos = Position.create(mouseX, mouseY); + Rectangle rect = dragging || scrollableElement == null ? getRectangle() : scrollableElement.getRectangle(); + + if (dragging && outOfBoundsDist >= -1 && rect.distance(axis.opposite(), mousePos) > outOfBoundsDist) { + state.setPos(slideStartPos); + return; + } + + double travel = rect.size(axis) - slider.getRectangle().size(axis); + if (travel <= 0) return; + double clickPos = this.clickPos.get(axis); + double currentPos = mousePos.get(axis); + double movement = (currentPos - clickPos) / travel; + + if (scrollableDragging) { + movement *= invertDragScroll ? state.sliderRatio() : -state.sliderRatio(); + } + + state.setPos(MathHelper.clip(slideStartPos + movement, 0, 1)); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + if (isMouseOver() || (scrollableElement != null && scrollableElement.isMouseOver())) { + if (!state.canScroll(axis)) return false; + state.setPos(MathHelper.clip(state.getPos() + (state.scrollSpeed() * -scroll), 0, 1)); + return true; + } + return false; + } + + public record ScrollBar(GuiRectangle container, GuiSlider slider, GuiRectangle highlight) {} +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java new file mode 100644 index 00000000..9ce861eb --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -0,0 +1,312 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; +import codechicken.lib.gui.modular.lib.container.SlotGroup; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import codechicken.lib.gui.modular.sprite.Material; +import net.minecraft.world.inventory.Slot; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.relative; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; +import static net.minecraft.world.inventory.InventoryMenu.BLOCK_ATLAS; + +/** + * This element is used to manage and render a grid of inventory slots in a GUI. + * The width and height of this element are automatically constrained based on the slot configuration. + * However, you can override those constraints, The slot grid will always render in the center of the element nomater the element size. + *

+ * This can be used to render all slots in a {@link SlotGroup} or a sub-set of slots within a group. + *

+ * Created by brandon3055 on 08/09/2023 + */ +public class GuiSlots extends GuiElement implements BackgroundRender { + public static final Material[] ARMOR_SLOTS = new Material[]{Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_helmet"), Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_chestplate"), Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_leggings"), Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_boots")}; + public static final Material OFF_HAND_SLOT = Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_shield"); + + private final int firstSlot; + private final int slotCount; + private final int columns; + private final SlotGroup slots; + private final ContainerScreenAccess screenAccess; + + private Material slotTexture = CCGuiTextures.getUncached("widgets/slot"); + private Function slotIcons = slot -> null; + private Function highlightColour = slot -> 0x80ffffff; + private int xSlotSpacing = 0; + private int ySlotSpacing = 0; + + /** + * @param slots The slot group containing the slots that this element will manage. + * @param gridColumns The width of the inventory grid (Typically 9 for standard player or chest inventories) + */ + public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int gridColumns) { + this(parent, screenAccess, slots, 0, slots.size(), gridColumns); + } + + /** + * @param slots The slot group containing the slots that this element will manage. + * @param firstSlot Index of the fist slot within the slot group. + * @param slotCount The number of slots that this element will manage. + * @param gridColumns The width of the inventory grid (Typically 9 for standard player or chest inventories) + */ + public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int firstSlot, int slotCount, int gridColumns) { + super(parent); + this.screenAccess = screenAccess; + this.slots = slots; + this.firstSlot = firstSlot; + this.slotCount = slotCount; + this.columns = gridColumns; + if (firstSlot + slotCount > slots.size()) { + throw new IllegalStateException("Specified slot range is out of bounds, Last slot in group is at index " + (slots.size() - 1) + " Specified range is from index " + firstSlot + " to " + (firstSlot + slotCount - 1)); + } + int columns = Math.min(gridColumns, slots.size()); + this.constrain(WIDTH, Constraint.dynamic(() -> (double) (columns * 18) + ((columns - 1) * xSlotSpacing))); + int rows = Math.max(1, slots.size() / gridColumns); + this.constrain(GeoParam.HEIGHT, Constraint.dynamic(() -> (double) (rows * 18) + ((rows - 1) * ySlotSpacing))); + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + getModularGui().setSlotHandler(slot, this); + } + + updateSlots(parent.getModularGui().getRoot()); + } + + //=== Construction Helpers ===// + + public static GuiSlots singleSlot(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots) { + return singleSlot(parent, screenAccess, slots, 0); + } + + public static GuiSlots singleSlot(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int index) { + return new GuiSlots(parent, screenAccess, slots, index, 1, 1); + } + + public static Player player(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots) { + return player(parent, screenAccess, mainSlots, hotBarSlots, 3); + } + + public static Player player(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, int hotBarSpacing) { + int width = 18 * 9; + int height = 18 * 4 + hotBarSpacing; + GuiElement container = new GuiElement<>(parent) + .setZStacking(false) + .constrain(WIDTH, Constraint.literal(width)) + .constrain(HEIGHT, Constraint.literal(height)); + + GuiSlots main = new GuiSlots(container, screenAccess, mainSlots, 9) + .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) + .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); + + GuiSlots bar = new GuiSlots(container, screenAccess, hotBarSlots, 9) + .constrain(TOP, relative(main.get(BOTTOM), hotBarSpacing)) + .constrain(LEFT, match(main.get(LEFT))); + return new Player(container, main, bar); + } + + public static PlayerWithArmor playerWithArmor(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots) { + return playerWithArmor(parent, screenAccess, mainSlots, hotBarSlots, armorSlots, 3, true); + } + + public static PlayerWithArmor playerWithArmor(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, int groupSpacing, boolean slotIcons) { + int width = 18 * 10 + groupSpacing; + int height = 18 * 4 + groupSpacing; + GuiElement container = new GuiElement<>(parent) + .setZStacking(false) + .constrain(WIDTH, Constraint.literal(width)) + .constrain(HEIGHT, Constraint.literal(height)); + + GuiSlots armor = new GuiSlots(container, screenAccess, armorSlots, 1) + .setYSlotSpacing(groupSpacing / 3) + .setEmptyIcon(index -> slotIcons ? ARMOR_SLOTS[index] : null) + .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) + .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); + + GuiSlots main = new GuiSlots(container, screenAccess, mainSlots, 9) + .constrain(TOP, match(armor.get(TOP))) + .constrain(LEFT, relative(armor.get(RIGHT), groupSpacing)); + + GuiSlots bar = new GuiSlots(container, screenAccess, hotBarSlots, 9) + .constrain(TOP, relative(main.get(BOTTOM), groupSpacing)) + .constrain(LEFT, match(main.get(LEFT))); + + return new PlayerWithArmor(container, main, bar, armor); + } + + public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots) { + return playerAllSlots(parent, screenAccess, mainSlots, hotBarSlots, armorSlots, offhandSlots, 3, true); + } + + public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots, int groupSpacing, boolean slotIcons) { + int width = 18 * 11 + groupSpacing * 2; + int height = 18 * 4 + groupSpacing; + GuiElement container = new GuiElement<>(parent) + .setZStacking(false) + .constrain(WIDTH, Constraint.literal(width)) + .constrain(HEIGHT, Constraint.literal(height)); + + GuiSlots armor = new GuiSlots(container, screenAccess, armorSlots, 1) + .setYSlotSpacing(groupSpacing / 3) + .setEmptyIcon(index -> slotIcons ? ARMOR_SLOTS[index] : null) + .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) + .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); + + GuiSlots main = new GuiSlots(container, screenAccess, mainSlots, 9) + .constrain(TOP, match(armor.get(TOP))) + .constrain(LEFT, relative(armor.get(RIGHT), groupSpacing)); + + GuiSlots bar = new GuiSlots(container, screenAccess, hotBarSlots, 9) + .constrain(TOP, relative(main.get(BOTTOM), groupSpacing)) + .constrain(LEFT, match(main.get(LEFT))); + + GuiSlots offHand = new GuiSlots(container, screenAccess, offhandSlots, 1) + .setEmptyIcon(index -> slotIcons ? OFF_HAND_SLOT : null) + .constrain(TOP, match(bar.get(TOP))) + .constrain(LEFT, relative(bar.get(RIGHT), groupSpacing)); + + return new PlayerAll(container, main, bar, armor, offHand); + } + + //=== Slots Setup ===// + + /** + * Allows you to use a custom slot texture, The default is the standard vanilla slot. + */ + public GuiSlots setSlotTexture(Material slotTexture) { + this.slotTexture = slotTexture; + return this; + } + + /** + * Sets a custom slot highlight colour (The highlight you get when your cursor is over a slot.) + */ + public GuiSlots setHighlightColour(int highlightColour) { + return setHighlightColour(slot -> highlightColour); + } + + /** + * Allows you to set per-slot highlight colours, The integer passed to the function is the + * index of the slot within the {@link SlotGroup} + */ + public GuiSlots setHighlightColour(Function highlightColour) { + this.highlightColour = highlightColour; + return this; + } + + /** + * Applies a single empty slot icon to all slots. + * Recommended texture size is 16x16 + */ + public GuiSlots setEmptyIcon(Material texture) { + return setEmptyIcon(index -> texture); + } + + /** + * Allows you to provide a texture to be rendered in each slot when the slot is empty. + * Recommended texture size is 16x16 + * + * @param slotIcons A function that is given the slot index within the {@link SlotGroup}, and should return a material or null. + */ + public GuiSlots setEmptyIcon(Function slotIcons) { + this.slotIcons = slotIcons; + return this; + } + + public GuiSlots setXSlotSpacing(int xSlotSpacing) { + this.xSlotSpacing = xSlotSpacing; + return this; + } + + public GuiSlots setYSlotSpacing(int ySlotSpacing) { + this.ySlotSpacing = ySlotSpacing; + return this; + } + + public GuiSlots setSlotSpacing(int xSlotSpacing, int ySlotSpacing) { + this.xSlotSpacing = xSlotSpacing; + this.ySlotSpacing = ySlotSpacing; + return this; + } + + //=== Internal Methods ===// + + @Override + public double getBackgroundDepth() { + return 33; + } + + private void updateSlots(GuiElement root) { + int columns = Math.min(this.columns, slots.size()); + int rows = Math.max(1, slots.size() / columns); + double width = (columns * 18) + (columns - 1) * xSlotSpacing; + double height = (rows * 18) + (rows - 1) * ySlotSpacing; + int top = (int) (yCenter() - (height / 2) - root.yMin()); + int left = (int) (xCenter() - (width / 2) - root.xMin()); + + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + int x = index % columns; + int y = index / columns; + slot.x = left + (x * 18) + 1 + (x * xSlotSpacing); + slot.y = top + (y * 18) + 1 + (y * ySlotSpacing); + } + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + GuiElement root = getModularGui().getRoot(); + updateSlots(root); + + Slot highlightSlot = null; + render.pose().pushPose(); + + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + render.texRect(slotTexture, slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); + } + + render.pose().translate(0, 0, 0.4); + + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + if (!slot.isActive()) continue; + if (!slot.hasItem()) { + Material icon = slotIcons.apply(index + firstSlot); + if (icon != null) { + render.texRect(icon, slot.x + root.xMin(), slot.y + root.yMin(), 16, 16); + } + } + + screenAccess.renderSlot(render, slot); + if (GuiRender.isInRect(slot.x + root.xMin(), slot.y + root.yMin(), 16, 16, mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY)) { + highlightSlot = slot; + } + } + + if (highlightSlot != null) { + render.pose().translate(0, 0, getBackgroundDepth() - 0.8); + render.rect(highlightSlot.x + root.xMin(), highlightSlot.y + root.yMin(), 16, 16, highlightColour.apply(slots.indexOf(highlightSlot))); + } + + render.pose().popPose(); + } + + public record Player(GuiElement container, GuiSlots main, GuiSlots hotBar) {} + + public record PlayerWithArmor(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor) {} + + public record PlayerAll(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor, GuiSlots offHand) {} +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java new file mode 100644 index 00000000..2776c2d5 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java @@ -0,0 +1,268 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ForegroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.Align; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Position; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import net.minecraft.client.gui.Font; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FormattedText; +import net.minecraft.util.FormattedCharSequence; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Align.MAX; +import static codechicken.lib.gui.modular.lib.geometry.Align.MIN; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.dynamic; + +/** + * Created by brandon3055 on 31/08/2023 + */ +public class GuiText extends GuiElement implements ForegroundRender { + private Supplier text; + private Supplier shadow = () -> true; + private Supplier textColour = () -> 0xFFFFFFFF; + private Supplier rotation = null; + private Position rotatePoint = Position.create(() -> xSize() / 2, () -> ySize() / 2); + private boolean trim = false; + private boolean wrap = false; + private boolean scroll = true; + private Align alignment = Align.CENTER; + //TODO, Arbitrary rotation is fun, But may want to switch to Axis, with option for "reverse" + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiText(@NotNull GuiParent parent) { + this(parent, () -> null); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiText(@NotNull GuiParent parent, @Nullable Component text) { + this(parent, () -> text); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiText(@NotNull GuiParent parent, @NotNull Supplier<@Nullable Component> text) { + super(parent); + this.text = text; + } + + /** + * Apply a dynamic height constraint that sets the height based on text height (accounting for wrapping) + */ + public GuiText autoHeight() { + constrain(GeoParam.HEIGHT, dynamic(() -> wrap ? (double) font().wordWrapHeight(getText(), (int) xSize()) : font().lineHeight)); + return this; + } + + public GuiText setTextSupplier(@NotNull Supplier<@Nullable Component> textSupplier) { + this.text = textSupplier; + return this; + } + + public GuiText setText(@Nullable Component text) { + this.text = () -> text; + return this; + } + + public GuiText setText(@NotNull String text) { + this.text = () -> Component.literal(text); + return this; + } + + public GuiText setTranslatable(@NotNull String translationKey) { + this.text = () -> Component.translatable(translationKey); + return this; + } + + @Nullable + public Component getText() { + return text.get(); + } + + public GuiText setAlignment(Align alignment) { + this.alignment = alignment; + return this; + } + + public Align getAlignment() { + return alignment; + } + + /** + * If set to true the text will be trimmed if it is too long to fit within the bounds on the element. + * Default disabled. + * Setting this to true will automatically disable wrap and scroll ether are enabled. + */ + public GuiText setTrim(boolean trim) { + this.trim = trim; + if (trim) wrap = scroll = false; + return this; + } + + public boolean getTrim() { + return trim; + } + + /** + * Set to true the text will be wrapped (rendered as multiple lines of text) if it is too long to fit within the size of the element. + * Default disabled. + * Setting this to true will automatically disable trim and scroll ether are enabled. + */ + public GuiText setWrap(boolean wrap) { + this.wrap = wrap; + if (wrap) trim = scroll = false; + return this; + } + + public boolean getWrap() { + return wrap; + } + + /** + * Set to true the text scroll using the same logic as vanillas widgets if the text is too long to fit within the elements bounds + * Default enabled. + * Setting this to true will automatically disable trim and wrap ether are enabled. + */ + public GuiText setScroll(boolean scroll) { + this.scroll = scroll; + if (scroll) trim = wrap = false; + return this; + } + + public boolean getScroll() { + return scroll; + } + + public GuiText setShadow(@NotNull Supplier shadow) { + this.shadow = shadow; + return this; + } + + public GuiText setShadow(boolean shadow) { + this.shadow = () -> shadow; + return this; + } + + public boolean getShadow() { + return shadow.get(); + } + + public GuiText setTextColour(Supplier textColour) { + this.textColour = textColour; + return this; + } + + public GuiText setTextColour(int textColour) { + this.textColour = () -> textColour; + return this; + } + + public int getTextColour() { + return textColour.get(); + } + + /** + * Set rotation angle in degrees + * //TODO, Does not work when text scroll is used + */ + public GuiText setRotation(double rotation) { + return setRotation(() -> rotation); + } + + /** + * Dynamic rotation control, Set to null to disable rotation. + * Rotation angle is in degrees + * //TODO, Does not work when text scroll is used + */ + public GuiText setRotation(@Nullable Supplier rotation) { + this.rotation = rotation; + return this; + } + + /** + * Sets the point around which the text rotates relative to the top left of the element. + * Default rotation point is a dynamic point set to the dead center of the element. + */ + public GuiText setRotatePoint(Position rotatePoint) { + this.rotatePoint = rotatePoint; + return this; + } + + @Override + public double getForegroundDepth() { + return 0.035; + } + + @Override + public void renderForeground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + Component component = getText(); + if (component == null) return; + Font font = render.font(); + + int textHeight = font.lineHeight; + int textWidth = font.width(component); + boolean tooLong = textWidth > xSize(); + double yPos = (yMin() + ySize() / 2 - textHeight / 2D) + 1; //Adding 1 here makes the text look 'visually' centered, Text height includes the height of the optional underline. + + PoseStack stack = render.pose(); + if (rotation != null) { + stack.pushPose(); + stack.translate(xMin() + rotatePoint.x(), yMin() + rotatePoint.y(), 0); + stack.mulPose(Axis.ZP.rotationDegrees(rotation.get().floatValue())); + stack.translate(-xMin() - rotatePoint.x(), -yMin() - rotatePoint.y(), 0); + } + + //Draw Trimmed + if (tooLong && getTrim()) { + Component tail = Component.literal("...").setStyle(getText().getStyle()); + FormattedText head = font.getSplitter().headByWidth(component, (int) xSize() - font.width(tail), getText().getStyle()); + FormattedCharSequence formatted = Language.getInstance().getVisualOrder(FormattedText.composite(head, tail)); + textWidth = font.width(formatted); + + double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; + render.drawString(formatted, xPos, yPos, getTextColour(), getShadow()); + } + //Draw Wrapped + else if (tooLong && wrap) { + textHeight = font.wordWrapHeight(component, (int) xSize()); + List list = font.split(component, (int) xSize()); + + yPos = yMin() + ySize() / 2 - textHeight / 2D; + for (FormattedCharSequence line : list) { + int lineWidth = font.width(line); + double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - lineWidth : xMin() + xSize() / 2 - lineWidth / 2D; + render.drawString(line, xPos, yPos, getTextColour(), getShadow()); + yPos += font.lineHeight; + } + } + //Draw Scrolling + else if (tooLong && scroll) { + render.pushScissorRect(getRectangle()); + render.drawScrollingString(component, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); + render.popScissor(); + } + //Draw + else { + double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; + render.drawString(component, xPos, yPos, getTextColour(), getShadow()); + } + + if (rotation != null) { + stack.popPose(); + } + } +} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java new file mode 100644 index 00000000..680b918c --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java @@ -0,0 +1,660 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.TextState; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.SharedConstants; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.RenderStateShard; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.Mth; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.glfw.GLFW; + +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Predicate; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * TODO, Re write this, Its currently mostly pulled from the TextField in Gui v2 + *

+ * Created by brandon3055 on 03/09/2023 + */ +public class GuiTextField extends GuiElement implements BackgroundRender { + private static final RenderType HIGHLIGHT_TYPE = RenderType.create("text_field_highlight", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() + .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionColorShader)) + .setColorLogicState(RenderStateShard.OR_REVERSE_COLOR_LOGIC) + .createCompositeState(false)); + + private int tick; + private int cursorPos; + private int maxLength = 32; + private int displayPos; + private int highlightPos; + private boolean focused; + private boolean shiftPressed; + + private Supplier isEditable = () -> true; + private Supplier isFocusable = () -> true; + private Supplier canLoseFocus = () -> true; + + private Runnable onEditComplete = null; + private Runnable onEnterPressed = null; + + private TextState textState = TextState.simpleState(""); + private Supplier shadow = () -> true; + private Supplier textColor = () -> 0xe0e0e0; + + private Supplier suggestion = null; + private Supplier suggestionColour = () -> 0x7f7f80; + + private Predicate filter = Objects::nonNull; + private BiFunction formatter = (string, pos) -> FormattedCharSequence.forward(string, Style.EMPTY); + + public GuiTextField(@NotNull GuiParent parent) { + super(parent); + } + + /** + * Creates a simple text box with a simple bordered background. + * Using colours 0xFF000000, 0xFFFFFFFF, 0xE0E0E0 will get you a text box identical to the one in a command block + */ + public static TextField create(GuiElement parent, int backgroundColour, int borderColour, int textColour) { + GuiRectangle background = new GuiRectangle(parent) + .rectangle(backgroundColour, borderColour); + + GuiTextField textField = new GuiTextField(background) + .setTextColor(textColour) + .constrain(TOP, Constraint.relative(background.get(TOP), 1)) + .constrain(BOTTOM, Constraint.relative(background.get(BOTTOM), -1)) + .constrain(LEFT, Constraint.relative(background.get(LEFT), 4)) + .constrain(RIGHT, Constraint.relative(background.get(RIGHT), -4)); + + return new TextField(background, textField); + } + + //=== Text field setup ===// + + /** + * Called when the user clicks outside the text box, or when they press enter + */ + public GuiTextField setOnEditComplete(Runnable onEditComplete) { + this.onEditComplete = onEditComplete; + return this; + } + + /** + * Called when the user presses enter key (Including numpad enter) with the text box ion focus + */ + public GuiTextField setEnterPressed(Runnable onEnterPressed) { + this.onEnterPressed = onEnterPressed; + return this; + } + + /** + * The {@link TextState} is an accessor for the current text value. + * It simply contains string getter and setter methods. + * You can use this to link the text field to some external value. + */ + public GuiTextField setTextState(TextState textState) { + this.textState = textState; + return this; + } + + public TextState getTextState() { + return textState; + } + + public GuiTextField setTextColor(Supplier textColor) { + this.textColor = textColor; + return this; + } + + public GuiTextField setTextColor(int textColor) { + return setTextColor(() -> textColor); + } + + /** + * Should the text be rendered with a shadow? + */ + public GuiTextField setShadow(Supplier shadow) { + this.shadow = shadow; + return this; + } + + /** + * Should the text be rendered with a shadow? + */ + public GuiTextField setShadow(boolean shadow) { + return setShadow(() -> shadow); + } + + /** + * Set the "suggestion" text that is displayed when the text field is empty. + */ + public GuiTextField setSuggestion(Component suggestion) { + return setSuggestion(suggestion == null ? null : () -> suggestion); + } + + /** + * Set the "suggestion" text that is displayed when the text field is empty. + */ + public GuiTextField setSuggestion(@Nullable Supplier suggestion) { + this.suggestion = suggestion; + return this; + } + + /** + * Set the colour of the suggestion text. + */ + public void setSuggestionColour(Supplier suggestionColour) { + this.suggestionColour = suggestionColour; + } + + /** + * Allows you to apply a fielder to this text field. + * Whenever this field's value is updated, If the new value does not pass this filter + * It will not be applied. + */ + public GuiTextField setFilter(Predicate filter) { + this.filter = filter; + return this; + } + + /** + * Formats the current text value for display to the user. + * The integer is the current display start position within the current field value. + */ + public GuiTextField setFormatter(BiFunction formatter) { + this.formatter = formatter; + return this; + } + + /** + * If set to false, it will not be possible for the text field to lose focus via normal means. + * Focus can still be set via {@link #setFocus(boolean)} + */ + public GuiTextField setCanLoseFocus(boolean canLoseFocus) { + return setCanLoseFocus(() -> canLoseFocus); + } + + /** + * If set to false, it will not be possible for the text field to lose focus via normal means. + * Focus can still be set via {@link #setFocus(boolean)} + */ + public GuiTextField setCanLoseFocus(Supplier canLoseFocus) { + this.canLoseFocus = canLoseFocus; + return this; + } + + /** + * If false, It will not be possible to focus this element by clicking on it. + */ + public GuiTextField setFocusable(boolean focusable) { + return setFocusable(() -> focusable); + } + + /** + * If false, It will not be possible to focus this element by clicking on it. + */ + public GuiTextField setFocusable(Supplier focusable) { + this.isFocusable = focusable; + return this; + } + + /** + * If false, It will not be possible for the user to edit the value of this text field. + */ + public GuiTextField setEditable(boolean editable) { + return setEditable(() -> editable); + } + + /** + * If false, It will not be possible for the user to edit the value of this text field. + */ + public GuiTextField setEditable(Supplier editable) { + this.isEditable = editable; + return this; + } + + /** + * Sets the maximum allowed text length + */ + public GuiTextField setMaxLength(int newWidth) { + String value = getValue(); + maxLength = newWidth; + if (value.length() > newWidth) { + textState.setText(value.substring(0, newWidth)); + } + return this; + } + + private int getMaxLength() { + return maxLength; + } + + //=== Text field logic ===// + + /** + * Note, Initial value should be set after element is constrained, + * If element width is zero when set, nothing will render until the field is updated. + * TODO, I need to fix this. Element size should be able to change dynamically without things breaking. + */ + public GuiTextField setValue(String newValue) { + if (this.filter.test(newValue)) { + if (newValue.length() > maxLength) { + textState.setText(newValue.substring(0, maxLength)); + } else { + textState.setText(newValue); + } + moveCursorToEnd(); + setHighlightPos(cursorPos); + } + return this; + } + + public String getValue() { + return textState.getText(); + } + + public String getHighlighted() { + int i = Math.min(cursorPos, highlightPos); + int j = Math.max(cursorPos, highlightPos); + return getValue().substring(i, j); + } + + public void insertText(String text) { + String value = getValue(); + int selectStart = Math.min(cursorPos, highlightPos); + int selectEnd = Math.max(cursorPos, highlightPos); + int freeSpace = maxLength - value.length() - (selectStart - selectEnd); + String toInsert = SharedConstants.filterText(text); + int insertLen = toInsert.length(); + if (freeSpace < insertLen) { + toInsert = toInsert.substring(0, freeSpace); + insertLen = freeSpace; + } + + String newValue = (new StringBuilder(value)).replace(selectStart, selectEnd, toInsert).toString(); + if (filter.test(newValue)) { + textState.setText(newValue); + setCursorPosition(selectStart + insertLen); + setHighlightPos(cursorPos); + } + } + + private void deleteText(int i) { + if (Screen.hasControlDown()) { + deleteWords(i); + } else { + deleteChars(i); + } + } + + public void deleteWords(int i) { + if (!getValue().isEmpty()) { + if (highlightPos != cursorPos) { + insertText(""); + } else { + deleteChars(getWordPosition(i) - cursorPos); + } + } + } + + public void deleteChars(int i1) { + String value = getValue(); + if (!value.isEmpty()) { + if (highlightPos != cursorPos) { + insertText(""); + } else { + int i = getCursorPos(i1); + int j = Math.min(i, cursorPos); + int k = Math.max(i, cursorPos); + if (j != k) { + String s = (new StringBuilder(value)).delete(j, k).toString(); + if (filter.test(s)) { + textState.setText(s); + moveCursorTo(j); + } + } + } + } + } + + public int getWordPosition(int i) { + return getWordPosition(i, getCursorPosition()); + } + + private int getWordPosition(int i, int i1) { + return getWordPosition(i, i1, true); + } + + private int getWordPosition(int i1, int i2, boolean b) { + String value = getValue(); + int i = i2; + boolean flag = i1 < 0; + int j = Math.abs(i1); + + for (int k = 0; k < j; ++k) { + if (!flag) { + int l = value.length(); + i = value.indexOf(32, i); + if (i == -1) { + i = l; + } else { + while (b && i < l && value.charAt(i) == ' ') ++i; + } + } else { + while (b && i > 0 && value.charAt(i - 1) == ' ') --i; + while (i > 0 && value.charAt(i - 1) != ' ') --i; + } + } + + return i; + } + + public void moveCursor(int pos) { + moveCursorTo(getCursorPos(pos)); + } + + private int getCursorPos(int i) { + return Util.offsetByCodepoints(getValue(), cursorPos, i); + } + + public void moveCursorTo(int pos, boolean notify) { + setCursorPosition(pos); + if (!shiftPressed) { + setHighlightPos(cursorPos); + } + } + + public void moveCursorTo(int pos) { + moveCursorTo(pos, true); + } + + public void setCursorPosition(int pos) { + cursorPos = Mth.clamp(pos, 0, getValue().length()); + } + + public void moveCursorToStart() { + moveCursorTo(0); + } + + public void moveCursorToEnd(boolean notify) { + moveCursorTo(getValue().length(), notify); + } + + public void moveCursorToEnd() { + moveCursorToEnd(true); + } + + public boolean isEditable() { + return isEditable.get(); + } + + public void setFocus(boolean focused) { + if (this.focused && !focused && onEditComplete != null) { + onEditComplete.run(); + } + this.focused = focused; + } + + public boolean isFocused() { + return focused; + } + + public int getCursorPosition() { + return cursorPos; + } + + public void setHighlightPos(int newPos) { + String value = getValue(); + int length = value.length(); + highlightPos = Mth.clamp(newPos, 0, length); + + if (displayPos > length) { + displayPos = length; + } + + int width = (int) xSize(); + String visibleText = font().plainSubstrByWidth(value.substring(displayPos), width); + int endPos = displayPos + visibleText.length(); + if (highlightPos == displayPos) { + displayPos -= font().plainSubstrByWidth(value, width, true).length(); + } + + if (highlightPos > endPos) { + displayPos += highlightPos - endPos; + } else if (highlightPos <= displayPos) { + displayPos -= displayPos - highlightPos; + } + + displayPos = Mth.clamp(displayPos, 0, length); + } + + //=== Input Handling ===// + + @Override + public boolean keyPressed(int key, int scancode, int modifiers) { + if (!canConsumeInput()) { + return false; + } else { + shiftPressed = Screen.hasShiftDown(); + if (Screen.isSelectAll(key)) { + moveCursorToEnd(); + setHighlightPos(0); + return true; + } else if (Screen.isCopy(key)) { + Minecraft.getInstance().keyboardHandler.setClipboard(getHighlighted()); + return true; + } else if (Screen.isPaste(key)) { + if (isEditable()) { + insertText(Minecraft.getInstance().keyboardHandler.getClipboard()); + } + + return true; + } else if (Screen.isCut(key)) { + Minecraft.getInstance().keyboardHandler.setClipboard(getHighlighted()); + if (isEditable()) { + insertText(""); + } + + return true; + } else { + switch (key) { + case InputConstants.KEY_BACKSPACE: + if (isEditable()) { + shiftPressed = false; + deleteText(-1); + shiftPressed = Screen.hasShiftDown(); + } + + return true; + case InputConstants.KEY_NUMPADENTER: + case InputConstants.KEY_RETURN: { + if (onEditComplete != null) { + onEditComplete.run(); + } + if (onEnterPressed != null) { + onEnterPressed.run(); + } + } + case InputConstants.KEY_INSERT: + case InputConstants.KEY_DOWN: + case InputConstants.KEY_UP: + case InputConstants.KEY_PAGEUP: + case InputConstants.KEY_PAGEDOWN: + default: + //Consume key presses when we are typing so we dont do something dumb like close the screen when you type e + return key != GLFW.GLFW_KEY_ESCAPE; + case InputConstants.KEY_DELETE: + if (isEditable()) { + shiftPressed = false; + deleteText(1); + shiftPressed = Screen.hasShiftDown(); + } + return true; + case InputConstants.KEY_RIGHT: + if (Screen.hasControlDown()) { + moveCursorTo(getWordPosition(1)); + } else { + moveCursor(1); + } + return true; + case InputConstants.KEY_LEFT: + if (Screen.hasControlDown()) { + moveCursorTo(getWordPosition(-1)); + } else { + moveCursor(-1); + } + return true; + case InputConstants.KEY_HOME: + moveCursorToStart(); + return true; + case InputConstants.KEY_END: + moveCursorToEnd(); + return true; + } + } + } + } + + public boolean canConsumeInput() { + return isFocused() && isEditable() && isEnabled(); + } + + @Override + public boolean keyReleased(int key, int scancode, int modifiers, boolean consumed) { + this.shiftPressed = Screen.hasShiftDown(); + return super.keyReleased(key, scancode, modifiers, consumed); + } + + @Override + public boolean charTyped(char charTyped, int charCode) { + if (!canConsumeInput()) { + return false; + } else if (SharedConstants.isAllowedChatCharacter(charTyped)) { + if (isEditable()) { + insertText(Character.toString(charTyped)); + } + return true; + } else { + return false; + } + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + consumed = super.mouseClicked(mouseX, mouseY, button, consumed); + + boolean mouseOver = isMouseOver(); + if (isFocused() && !mouseOver) { + setFocus(isFocusable.get() && !canLoseFocus.get()); + } + + if (consumed) return true; + + if (canLoseFocus.get()) { + setFocus(mouseOver && isFocusable.get()); + } else { + setFocus(isFocusable.get()); + } + + if (isFocused() && mouseOver && button == 0) { + int i = (int) (Mth.floor(mouseX) - xMin()); + String s = font().plainSubstrByWidth(getValue().substring(displayPos), (int) xSize()); + moveCursorTo(font().plainSubstrByWidth(s, i).length() + displayPos); + return true; + } else { + return false; + } + } + + //=== Rendering ===// + + @Override + public double getBackgroundDepth() { + return 0.04; + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + String value = getValue(); + int colour = textColor.get(); + + int textStart = cursorPos - displayPos; + int highlightStart = highlightPos - displayPos; + String displayText = font().plainSubstrByWidth(value.substring(displayPos), (int) xSize()); + boolean flag = textStart >= 0 && textStart <= displayText.length(); + boolean cursorBlink = isFocused() && tick / 6 % 2 == 0 && flag; + double drawX = xMin(); + double drawY = yMin() + ((ySize() - 8) / 2); + int drawEnd = (int) drawX; + + if (highlightStart > displayText.length()) { + highlightStart = displayText.length(); + } + + if (!displayText.isEmpty()) { + String drawString = flag ? displayText.substring(0, textStart) : displayText; + drawEnd = render.drawString(formatter.apply(drawString, displayPos), drawX, drawY, colour, shadow.get()); + } + + boolean flag2 = cursorPos < value.length() || value.length() >= getMaxLength(); + int k1 = drawEnd; + + if (!flag) { + k1 = (int) (textStart > 0 ? drawX + xSize() : drawX); + } else if (flag2) { + k1 = drawEnd - 1; + --drawEnd; + } + + if (!displayText.isEmpty() && flag && textStart < displayText.length()) { + render.drawString(formatter.apply(displayText.substring(textStart), cursorPos), drawEnd, drawY, colour, shadow.get()); + } + + if (suggestion != null && value.isEmpty()) { + render.drawString(suggestion.get(), (float) (k1 - 1), (float) drawY, suggestionColour.get(), shadow.get()); + } + + if (cursorBlink) { + if (flag2) { + render.fill(k1, drawY - 1, k1 + 1, drawY + 1 + 9, -3092272); + } else { + render.drawString("_", (float) k1, (float) drawY, colour, shadow.get()); + } + } + + if (highlightStart != textStart) { + int l1 = (int) (drawX + font().width(displayText.substring(0, highlightStart))); + render.pose().translate(0, 0, 0.035); + render.fill(HIGHLIGHT_TYPE, k1, drawY - 1, l1 - 1, drawY + 1 + 9, 0xFF0000FF); + render.pose().translate(0, 0, -0.035); + } + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + tick++; + } + + public record TextField(GuiRectangle container, GuiTextField field) {} +} + diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java new file mode 100644 index 00000000..865b935c --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java @@ -0,0 +1,173 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ForegroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.Align; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.gui.Font; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Align.MAX; +import static codechicken.lib.gui.modular.lib.geometry.Align.MIN; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.dynamic; + +/** + * Created by brandon3055 on 10/10/2023 + */ +public class GuiTextList extends GuiElement implements ForegroundRender { + private Supplier> text; + private Supplier shadow = () -> true; + private Supplier textColour = () -> 0xFFFFFFFF; + private boolean scroll = true; + private Align horizontalAlign = Align.CENTER; + private Align verticalAlign = Align.TOP; + private int lineSpacing = 0; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiTextList(@NotNull GuiParent parent) { + this(parent, () -> null); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiTextList(@NotNull GuiParent parent, List text) { + this(parent, () -> text); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiTextList(@NotNull GuiParent parent, @NotNull Supplier> text) { + super(parent); + this.text = text; + } + + /** + * Apply a dynamic height constraint that sets the height based on text height (accounting for wrapping) + */ + public GuiTextList autoHeight() { + constrain(GeoParam.HEIGHT, dynamic(() -> (double) ((font().lineHeight + lineSpacing) * getText().size()) - 1)); + return this; + } + + public GuiTextList setTextSupplier(@NotNull Supplier> textSupplier) { + this.text = textSupplier; + return this; + } + + public GuiTextList setText(List text) { + this.text = () -> text; + return this; + } + + public List getText() { + return text.get(); + } + + public GuiTextList setHorizontalAlign(Align horizontalAlign) { + this.horizontalAlign = horizontalAlign; + return this; + } + + public GuiTextList setVerticalAlign(Align verticalAlign) { + this.verticalAlign = verticalAlign; + return this; + } + + public Align getHorizontalAlign() { + return horizontalAlign; + } + + public Align getVerticalAlign() { + return verticalAlign; + } + + public GuiTextList setLineSpacing(int lineSpacing) { + this.lineSpacing = lineSpacing; + return this; + } + + public int getLineSpacing() { + return lineSpacing; + } + + /** + * Set to true the text scroll using the same logic as vanillas widgets if the text is too long to fit within the elements bounds + * Default enabled. + * Setting this to true will automatically disable trim and wrap ether are enabled. + */ + public GuiTextList setScroll(boolean scroll) { + this.scroll = scroll; + return this; + } + + public boolean getScroll() { + return scroll; + } + + public GuiTextList setShadow(@NotNull Supplier shadow) { + this.shadow = shadow; + return this; + } + + public GuiTextList setShadow(boolean shadow) { + this.shadow = () -> shadow; + return this; + } + + public boolean getShadow() { + return shadow.get(); + } + + public GuiTextList setTextColour(Supplier textColour) { + this.textColour = textColour; + return this; + } + + public GuiTextList setTextColour(int textColour) { + this.textColour = () -> textColour; + return this; + } + + public int getTextColour() { + return textColour.get(); + } + + @Override + public double getForegroundDepth() { + return 0.035; + } + + @Override + public void renderForeground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + List list = getText(); + if (list.isEmpty()) return; + Font font = render.font(); + + double height = (list.size() * (font.lineHeight + lineSpacing)) - lineSpacing; + double yPos = verticalAlign == MIN ? yMin() : verticalAlign == MAX ? yMax() - height : (yCenter() - (height / 2)) + 1; + for (Component line : list) { + int textWidth = font.width(line); + boolean tooLong = textWidth > xSize(); + + if (tooLong && scroll) { + render.pushScissorRect(getRectangle()); + render.drawScrollingString(line, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); + render.popScissor(); + } else { + double xPos = horizontalAlign == MIN ? xMin() : horizontalAlign == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; + render.drawString(line, xPos, yPos, getTextColour(), getShadow()); + } + + yPos += font.lineHeight + lineSpacing; + } + } +} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java new file mode 100644 index 00000000..da5c0577 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java @@ -0,0 +1,110 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.GuiRender; +import codechicken.lib.gui.modular.lib.geometry.Borders; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.sprite.Material; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 28/08/2023 + */ +public class GuiTexture extends GuiElement implements BackgroundRender { + private Supplier getMaterial; + private Supplier colour = () -> 0xFFFFFFFF; + private Borders dynamicBorders = null; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiTexture(@NotNull GuiParent parent) { + super(parent); + } + + public GuiTexture(@NotNull GuiParent parent, Supplier supplier) { + super(parent); + setMaterial(supplier); + } + + public GuiTexture(@NotNull GuiParent parent, Material material) { + super(parent); + setMaterial(material); + } + + public GuiTexture setMaterial(Supplier supplier) { + this.getMaterial = supplier; + return this; + } + + public GuiTexture setMaterial(Material material) { + this.getMaterial = () -> material; + return this; + } + + @Nullable + public Material getMaterial() { + return getMaterial == null ? null : getMaterial.get(); + } + + /** + * Enables dynamic texture resizing though the use of cutting and tiling. + * Only works with textures that can be cut up and tiled without issues, e.g. background textures or button textures. + * This method uses the standard border with of 5 pixels on all sides. + */ + public GuiTexture dynamicTexture() { + return dynamicTexture(5); + } + + /** + * Enables dynamic texture resizing though the use of cutting and tiling. + * Only works with textures that can be cut up and tiled without issues, e.g. background textures or button textures. + * The border parameters indicate the width of border around the texture that must be maintained during the cutting and tiling process. + * For standardisation purposes the border width should be >= 5 + */ + public GuiTexture dynamicTexture(int textureBorders) { + return dynamicTexture(Borders.create(textureBorders)); + } + + /** + * Enables dynamic texture resizing though the use of cutting and tiling. + * Only works with textures that can be cut up and tiled without issues, e.g. background textures or button textures. + * The border parameters indicate the width of border around the texture that must be maintained during the cutting and tiling process. + * For standardisation purposes the border width should be >= 5 + */ + public GuiTexture dynamicTexture(Borders textureBorders) { + dynamicBorders = textureBorders; + return this; + } + + /** + * Allows you to set an argb colour. + * This colour will be applied when rendering the texture. + */ + public GuiTexture setColour(int colourARGB) { + return setColour(() -> colourARGB); + } + + /** + * Allows you to set an argb colour provider. + * This colour will be applied when rendering the texture. + */ + public GuiTexture setColour(Supplier colour) { + this.colour = colour; + return this; + } + + @Override + public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + Material material = getMaterial(); + if (material == null) return; + if (dynamicBorders != null) { + render.dynamicTex(material, getRectangle(), dynamicBorders, colour.get()); + } else { + render.texRect(material, getRectangle(), colour.get()); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java b/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java new file mode 100644 index 00000000..0291e8af --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java @@ -0,0 +1,34 @@ +package codechicken.lib.gui.modular.lib; + +import com.mojang.blaze3d.vertex.PoseStack; + +/** + * Allows a Gui Elements to render content behind child elements. + * This is the default render mode for the majority of elements. + *

+ * Created by brandon3055 on 07/08/2023 + */ +public interface BackgroundRender { + + /** + * Specifies the z depth of the background content. + * After {@link #renderBackground(GuiRender, double, double, float)} is called, the PoseStack will be translated by this amount in the z direction + * before any assigned child elements are rendered. + * Recommended minimum depth is 0.01 or 0.035 if this element renders text. (text shadows are rendered with a 0.03 offset) + * + * @return the z height of the background content. + */ + default double getBackgroundDepth() { + return 0.01; + } + + /** + * Used to render content behind this elements child elements. + * When rendering element content, always use the {@link PoseStack} available via the provided {@link GuiRender} + * Where applicable, always use push/pop to ensure the stack is returned to its original state after your rendering is complete. + * + * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + */ + void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks); + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ColourState.java b/src/main/java/codechicken/lib/gui/modular/lib/ColourState.java new file mode 100644 index 00000000..850e0f14 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ColourState.java @@ -0,0 +1,72 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.colour.Colour; +import codechicken.lib.colour.ColourARGB; + +import java.util.Locale; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 19/11/2023 + */ +public interface ColourState { + + int get(); + + default ColourARGB getColour() { + return new ColourARGB(get()); + } + + void set(int colour); + + default void set(Colour colour) { + set(colour.argb()); + } + + default String getHexColour() { + return Integer.toHexString(get()).toUpperCase(Locale.ROOT); + } + + default void setHexColour(String hexColour) { + try { + set(Integer.parseUnsignedInt(hexColour, 16)); + } catch (Throwable e) { + set(0); + } + } + + static ColourState create() { + return create(null); + } + + static ColourState create(Consumer listener) { + return new ColourState() { + int colour = 0; + @Override + public int get() { + return colour; + } + + @Override + public void set(int colour) { + this.colour = colour; + if (listener != null) listener.accept(colour); + } + }; + } + + static ColourState create(Supplier getter, Consumer setter) { + return new ColourState() { + @Override + public int get() { + return getter.get(); + } + + @Override + public void set(int colour) { + setter.accept(colour); + } + }; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java new file mode 100644 index 00000000..1cb4de5b --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java @@ -0,0 +1,209 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.lib.geometry.Borders; +import codechicken.lib.gui.modular.lib.geometry.ConstrainedGeometry; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This class contains a bunch of static helper methods that can be used to quickly apply common constraints. + * The plan is to keep adding common constraints to this class as they pop up. + *

+ * Created by brandon3055 on 07/09/2023 + */ +public interface DynamicTextures { + + void makeTextures(Function textures); + + default String dynamicTexture(Function textures, ResourceLocation dynamicInput, ResourceLocation outputLocation, int width, int height, int border) { + return textures.apply(new DynamicTexture(dynamicInput, outputLocation, width, height, border, border, border, border)); + } + + default String dynamicTexture(Function textures, ResourceLocation dynamicInput, ResourceLocation outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + return textures.apply(new DynamicTexture(dynamicInput, outputLocation, width, height, topBorder, leftBorder, bottomBorder, rightBorder)); + } + + record DynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + public String guiTexturePath() { + return outputLocation.getPath().replace("textures/gui/", "").replace(".gui", ""); + } + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java new file mode 100644 index 00000000..d4edcbe1 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java @@ -0,0 +1,272 @@ +package codechicken.lib.gui.modular.lib; + +import com.google.common.collect.Lists; +import codechicken.lib.gui.modular.elements.GuiElement; + +import java.util.List; + +/** + * This class defines the default implementation for all Screen events. + * Input events in Modular GUI v2 work similar to v2, events are passed to all elements recursively in a top-down order, + * and if any element 'consumes' the event, it will not be passed any further down the chain. + * However, this approach had issues in v2, because there are certain situations where an element needs to receive an event even if it has been consumed. + * To deal with that we now have two methods for each event, the main handler method that will always get called, and uses a 'consumed' flag to track whether the event has been consumed, + * as well as a simpler convenience method that will only get called if the event has not already been canceled, and does not require you to call super. + *

+ * Created by brandon3055 on 09/08/2023 + */ +public interface ElementEvents { + + /** + * @return An unmodifiable list of all assigned child elements assigned to this parent. The list should be sorted in the order they were added. + */ + List> getChildren(); + + //=== Mouse Events ==// + + /** + * Called whenever the cursor position changes. + * Vanillas mouseDragged is not passed through because it is redundant. + * All mouse drag functionality can be archived using available events. + * + * @param mouseX new mouse X position + * @param mouseY new mouse Y position + */ + default void mouseMoved(double mouseX, double mouseY) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + child.mouseMoved(mouseX, mouseY); + } + } + } + + /** + * Override this method to implement handling for the mouseClicked event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseClicked(double, double, int, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param button Mouse Button + * @return true to consume event. + */ + default boolean mouseClicked(double mouseX, double mouseY, int button) { + return false; + } + + /** + * Root handler for mouseClick event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of mouseClick handling should be implemented via {@link #mouseClicked(double, double, int)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param button Mouse Button + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.mouseClicked(mouseX, mouseY, button, consumed); + } + } + return consumed || mouseClicked(mouseX, mouseY, button) || blockMouseEvents(); + } + + /** + * Override this method to implement handling for the mouseReleased event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseReleased(double, double, int, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param button Mouse Button + * @return true to consume event. + */ + default boolean mouseReleased(double mouseX, double mouseY, int button) { + return false; + } + + /** + * Root handler for mouseReleased event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of mouseReleased handling should be implemented via {@link #mouseReleased(double, double, int)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param button Mouse Button + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.mouseReleased(mouseX, mouseY, button, consumed); + } + } + return consumed || mouseReleased(mouseX, mouseY, button) || blockMouseEvents(); + } + + /** + * Override this method to implement handling for the mouseScrolled event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseScrolled(double, double, double, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scroll Scroll direction and amount + * @return true to consume event. + */ + default boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + return false; + } + + /** + * Root handler for mouseScrolled event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of mouseScrolled handling should be implemented via {@link #mouseScrolled(double, double, double)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scroll Scroll direction and amount + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean mouseScrolled(double mouseX, double mouseY, double scroll, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.mouseScrolled(mouseX, mouseY, scroll, consumed); + } + } + return consumed || mouseScrolled(mouseX, mouseY, scroll) || blockMouseEvents(); + } + + /** + * @return True to prevent mouse events from being passed to elements bellow this element. + */ + default boolean blockMouseEvents() { + return false; + } + + //=== Keyboard Events ==// + + /** + * Override this method to implement handling for the keyPressed event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyPressed(int, int, int, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param key the keyboard key that was pressed. + * @param scancode the system-specific scancode of the key + * @param modifiers bitfield describing which modifier keys were held down. + * @return true to consume event. + */ + default boolean keyPressed(int key, int scancode, int modifiers) { + return false; + } + + /** + * Root handler for keyPressed event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of keyPressed handling should be implemented via {@link #keyPressed(int, int, int)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param key the keyboard key that was pressed. + * @param scancode the system-specific scancode of the key + * @param modifiers bitfield describing which modifier keys were held down. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean keyPressed(int key, int scancode, int modifiers, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.keyPressed(key, scancode, modifiers, consumed); + } + } + return consumed || keyPressed(key, scancode, modifiers); + } + + /** + * Override this method to implement handling for the keyReleased event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyReleased(int, int, int, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param key the keyboard key that was released. + * @param scancode the system-specific scancode of the key + * @param modifiers bitfield describing which modifier keys were held down. + * @return true to consume event. + */ + default boolean keyReleased(int key, int scancode, int modifiers) { + return false; + } + + /** + * Root handler for keyReleased event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of keyReleased handling should be implemented via {@link #keyReleased(int, int, int)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param key the keyboard key that was released. + * @param scancode the system-specific scancode of the key + * @param modifiers bitfield describing which modifier keys were held down. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean keyReleased(int key, int scancode, int modifiers, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.keyReleased(key, scancode, modifiers, consumed); + } + } + return consumed || keyReleased(key, scancode, modifiers); + } + + /** + * Override this method to implement handling for the charTyped event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #charTyped(char, int, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param character The character typed. + * @param modifiers bitfield describing which modifier keys were held down. + * @return true to consume event. + */ + default boolean charTyped(char character, int modifiers) { + return false; + } + + /** + * Root handler for charTyped event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of charTyped handling should be implemented via {@link #charTyped(char, int)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param character The character typed. + * @param modifiers bitfield describing which modifier keys were held down. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean charTyped(char character, int modifiers, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.charTyped(character, modifiers, consumed); + } + } + return consumed || charTyped(character, modifiers); + } + +} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java b/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java new file mode 100644 index 00000000..76dfcfb3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java @@ -0,0 +1,32 @@ +package codechicken.lib.gui.modular.lib; + +import com.mojang.blaze3d.vertex.PoseStack; + +/** + * Allows a Gui Elements to render content in front of child elements. + * Note: Most elements should use {@link BackgroundRender} to render their content. + *

+ * Created by brandon3055 on 07/08/2023 + */ +public interface ForegroundRender { + + /** + * Specifies the z depth of the foreground content. + * Used when calculating the total depth of this gui element. + * Recommended minimum depth is 0.01 or 0.035 if this element renders text. (text shadows are rendered with a 0.03 offset) + * + * @return the z height of the background content. + */ + default double getForegroundDepth() { + return 0.01; + } + + /** + * Used to render content in front of this elements child elements. + * When rendering element content, always use the {@link PoseStack} available via the provided {@link GuiRender} + * Where applicable, always use push/pop to ensure the stack is returned to its original state after your rendering is complete. + * + * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + */ + void renderForeground(GuiRender render, double mouseX, double mouseY, float partialTicks); +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiProvider.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiProvider.java new file mode 100644 index 00000000..32dbcbb5 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/GuiProvider.java @@ -0,0 +1,42 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; + +/** + * This interface is used to build modular gui Screens. + * For modular gui container screens use {@link ContainerGuiProvider} + * + * Created by brandon3055 on 19/08/2023 + */ +public interface GuiProvider { + + /** + * Override this to defile a custom root gui element. + * Useful if you want to use something like a background texture or a manipulable element as the root element. + * + * @param gui The modular GUI. + * @return the root gui element. + */ + default GuiElement createRootElement(ModularGui gui) { + return new GuiElement<>(gui); + } + + /** + * Use this method to build the modular gui. + *

+ * Initialize the gui root element with {@link ModularGui#initStandardGui(int, int)}, {@link ModularGui#initFullscreenGui()} + * This applies bindings to fix the size and position of the root element, you can also do this manually for custom configurations. + *

+ * Build your gui by adding and configuring your desired gui elements. + * Elements must be added to the root gui element which is obtainable via gui.getRoot() + *

+ * Note: gui elements are added on construction, meaning you do not need to use element.addChild. + * Instead, just construct the elements, and pass in the root element (or any other initialized element) as the parent. + * + * @param gui The modular gui instance. + */ + void buildGui(ModularGui gui); + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java new file mode 100644 index 00000000..a91b7bd8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java @@ -0,0 +1,1728 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.lib.geometry.Borders; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import codechicken.lib.gui.modular.sprite.Material; +import com.mojang.blaze3d.platform.Lighting; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.CrashReport; +import net.minecraft.CrashReportCategory; +import net.minecraft.ReportedException; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner; +import net.minecraft.client.gui.screens.inventory.tooltip.DefaultTooltipPositioner; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderStateShard; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FormattedText; +import net.minecraft.network.chat.HoverEvent; +import net.minecraft.network.chat.Style; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.inventory.tooltip.TooltipComponent; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraftforge.client.ForgeHooksClient; +import net.minecraftforge.client.event.RenderTooltipEvent; +import net.minecraftforge.common.MinecraftForge; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.joml.Vector2ic; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * This class primarily based on GuiHelper from BrandonsCore + * But its implementation is heavily inspired by the new GuiGraphics system in 1.20+ + *

+ * The purpose of this class is to provide most of the basic rendering functions required to render various GUI geometry. + * This includes things like simple rectangles, textures, strings, etc. + *

+ * Created by brandon3055 on 29/06/2023 + */ +public class GuiRender { + public static final RenderType SOLID = RenderType.gui(); + + //Used for things like events that require the vanilla GuiGraphics + private final RenderWrapper renderWrapper; + + private final Minecraft mc; + private final PoseStack pose; + private final ScissorHandler scissorHandler = new ScissorHandler(); + private final MultiBufferSource.BufferSource buffers; + private boolean batchDraw; + private Font fontOverride; + + public GuiRender(Minecraft mc, PoseStack poseStack, MultiBufferSource.BufferSource buffers) { + this.mc = mc; + this.pose = poseStack; + this.buffers = buffers; + this.renderWrapper = new RenderWrapper(this); + } + + public GuiRender(Minecraft mc, MultiBufferSource.BufferSource buffers) { + this(mc, new PoseStack(), buffers); + } + + public static GuiRender convert(GuiGraphics graphics) { + return new GuiRender(Minecraft.getInstance(), graphics.pose(), graphics.bufferSource()); + } + + public PoseStack pose() { + return pose; + } + + public MultiBufferSource.BufferSource buffers() { + return buffers; + } + + public Minecraft mc() { + return mc; + } + + public Font font() { + return fontOverride == null ? mc().font : fontOverride; + } + + public int guiWidth() { + return mc().getWindow().getGuiScaledWidth(); + } + + public int guiHeight() { + return mc().getWindow().getGuiScaledHeight(); + } + + /** + * Allows you to override the font renderer used for all text rendering. + * Be sure to set the override back to null when you are finished using your custom font! + * + * @param font The font to use, or null to disable override. + */ + public void overrideFont(@Nullable Font font) { + this.fontOverride = font; + } + + /** + * Allow similar render calls to be batched together into a single draw for better render efficiency. + * All render calls in batch must use the same render type. + * + * @param batch callback in which the rendering should be implemented. + */ + public void batchDraw(Runnable batch) { + flush(); + batchDraw = true; + batch.run(); + batchDraw = false; + flush(); + } + + private void flushIfUnBatched() { + if (!batchDraw) flush(); + } + + private void flushIfBatched() { + if (batchDraw) flush(); + } + + public void flush() { + RenderSystem.disableDepthTest(); + buffers.endBatch(); + RenderSystem.enableDepthTest(); + } + + /** + * Only use this as a last resort! It may explode... Have fun! + * + * @return A Vanilla GuiGraphics instance that wraps this {@link GuiRender} + */ + @Deprecated + public RenderWrapper guiGraphicsWrapper() { + return renderWrapper; + } + + //=== Un-Textured geometry ===// + + /** + * Fill rectangle with solid colour + */ + public void rect(Rectangle rectangle, int colour) { + this.rect(SOLID, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), colour); + } + + /** + * Fill rectangle with solid colour + */ + public void rect(RenderType type, Rectangle rectangle, int colour) { + this.rect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), colour); + } + + /** + * Fill rectangle with solid colour + */ + public void rect(double x, double y, double width, double height, int colour) { + this.fill(SOLID, x, y, x + width, y + height, colour); + } + + /** + * Fill rectangle with solid colour + */ + public void rect(RenderType type, double x, double y, double width, double height, int colour) { + this.fill(type, x, y, x + width, y + height, colour); + } + + /** + * Fill area with solid colour + */ + public void fill(double xMin, double yMin, double xMax, double yMax, int colour) { + this.fill(SOLID, xMin, yMin, xMax, yMax, colour); + } + + /** + * Fill area with solid colour + */ + public void fill(RenderType type, double xMin, double yMin, double xMax, double yMax, int colour) { + if (xMax < xMin) { + double min = xMax; + xMax = xMin; + xMin = min; + } + if (yMax < yMin) { + double min = yMax; + yMax = yMin; + yMin = min; + } + + Matrix4f mat = pose.last().pose(); + VertexConsumer buffer = buffers.getBuffer(type); + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(colour).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(colour).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(colour).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(colour).endVertex(); //L-B + flushIfUnBatched(); + } + + /** + * Fill area with colour gradient from top to bottom + */ + public void gradientFillV(double xMin, double yMin, double xMax, double yMax, int topColour, int bottomColour) { + this.gradientFillV(SOLID, xMin, yMin, xMax, yMax, topColour, bottomColour); + } + + /** + * Fill area with colour gradient from top to bottom + */ + public void gradientFillV(RenderType type, double xMin, double yMin, double xMax, double yMax, int topColour, int bottomColour) { + VertexConsumer buffer = buffers().getBuffer(type); + float sA = a(topColour) / 255.0F; + float sR = r(topColour) / 255.0F; + float sG = g(topColour) / 255.0F; + float sB = b(topColour) / 255.0F; + float eA = a(bottomColour) / 255.0F; + float eR = r(bottomColour) / 255.0F; + float eG = g(bottomColour) / 255.0F; + float eB = b(bottomColour) / 255.0F; + Matrix4f mat = pose.last().pose(); + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(sR, sG, sB, sA).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(sR, sG, sB, sA).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //L-B + this.flushIfUnBatched(); + } + + /** + * Fill area with colour gradient from left to right + */ + public void gradientFillH(double xMin, double yMin, double xMax, double yMax, int leftColour, int rightColour) { + this.gradientFillH(SOLID, xMin, yMin, xMax, yMax, leftColour, rightColour); + } + + /** + * Fill area with colour gradient from left to right + */ + public void gradientFillH(RenderType type, double xMin, double yMin, double xMax, double yMax, int leftColour, int rightColour) { + VertexConsumer buffer = buffers().getBuffer(type); + float sA = a(leftColour) / 255.0F; + float sR = r(leftColour) / 255.0F; + float sG = g(leftColour) / 255.0F; + float sB = b(leftColour) / 255.0F; + float eA = a(rightColour) / 255.0F; + float eR = r(rightColour) / 255.0F; + float eG = g(rightColour) / 255.0F; + float eB = b(rightColour) / 255.0F; + Matrix4f mat = pose.last().pose(); + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(eR, eG, eB, eA).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(sR, sG, sB, sA).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(sR, sG, sB, sA).endVertex(); //L-B + this.flushIfUnBatched(); + } + + /** + * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. + */ + public void borderRect(Rectangle rectangle, double borderWidth, int fillColour, int borderColour) { + borderFill(rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, fillColour, borderColour); + } + + /** + * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. + */ + public void borderRect(double x, double y, double width, double height, double borderWidth, int fillColour, int borderColour) { + borderFill(x, y, x + width, y + height, borderWidth, fillColour, borderColour); + } + + /** + * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. + */ + public void borderRect(RenderType type, Rectangle rectangle, double borderWidth, int fillColour, int borderColour) { + borderFill(type, rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, fillColour, borderColour); + } + + /** + * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. + */ + public void borderRect(RenderType type, double x, double y, double width, double height, double borderWidth, int fillColour, int borderColour) { + borderFill(type, x, y, x + width, y + height, borderWidth, fillColour, borderColour); + } + + /** + * Draw a border of specified with, fill internal area with solid colour. + */ + public void borderFill(double xMin, double yMin, double xMax, double yMax, double borderWidth, int fillColour, int borderColour) { + borderFill(SOLID, xMin, yMin, xMax, yMax, borderWidth, fillColour, borderColour); + } + + /** + * Draw a border of specified with, fill internal area with solid colour. + */ + public void borderFill(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int fillColour, int borderColour) { + if (batchDraw) { //Draw batched for efficiency, unless already doing a batch draw. + borderFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, fillColour, borderColour); + } else { + batchDraw(() -> borderFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, fillColour, borderColour)); + } + } + + private void borderFillInternal(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int fillColour, int borderColour) { + fill(type, xMin, yMin, xMax, yMin + borderWidth, borderColour); //Top + fill(type, xMin, yMin + borderWidth, xMin + borderWidth, yMax - borderWidth, borderColour); //Left + fill(type, xMin, yMax - borderWidth, xMax, yMax, borderColour); //Bottom + fill(type, xMax - borderWidth, yMin + borderWidth, xMax, yMax - borderWidth, borderColour); //Right + if (fillColour != 0) //No point rendering fill if there is no fill colour + fill(type, xMin + borderWidth, yMin + borderWidth, xMax - borderWidth, yMax - borderWidth, fillColour); //Fill + } + + /** + * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedRect(Rectangle rectangle, double borderWidth, int topLeftColour, int bottomRightColour, int fillColour) { + shadedFill(SOLID, rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, topLeftColour, bottomRightColour, midColour(topLeftColour, bottomRightColour), fillColour); + } + + /** + * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedRect(double x, double y, double width, double height, double borderWidth, int topLeftColour, int bottomRightColour, int fillColour) { + shadedFill(SOLID, x, y, x + width, y + height, borderWidth, topLeftColour, bottomRightColour, midColour(topLeftColour, bottomRightColour), fillColour); + } + + /** + * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedRect(Rectangle rectangle, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { + shadedFill(SOLID, rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); + } + + /** + * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedRect(double x, double y, double width, double height, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { + shadedFill(SOLID, x, y, x + width, y + height, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); + } + + /** + * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedRect(RenderType type, double x, double y, double width, double height, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { + shadedFill(type, x, y, x + width, y + height, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); + } + + /** + * Can be used to create the illusion of an inset / outset area. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedFill(double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int fillColour) { + shadedFill(SOLID, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, midColour(topLeftColour, bottomRightColour), fillColour); + } + + /** + * Can be used to create the illusion of an inset / outset area. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedFill(double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { + shadedFill(SOLID, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); + } + + /** + * Can be used to create the illusion of an inset / outset area. This is identical to the way inventory slots are rendered except in code rather than via a texture. + * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot + * This can also be used to render things like buttons that appear to actually "push in" when you press them. + */ + public void shadedFill(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { + if (batchDraw) { //Draw batched for efficiency, unless already doing a batch draw. + shadedFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); + } else { + batchDraw(() -> shadedFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour)); + } + } + + public void shadedFillInternal(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { + fill(type, xMin, yMin, xMax - borderWidth, yMin + borderWidth, topLeftColour); //Top + fill(type, xMin, yMin + borderWidth, xMin + borderWidth, yMax - borderWidth, topLeftColour); //Left + fill(type, xMin + borderWidth, yMax - borderWidth, xMax, yMax, bottomRightColour); //Bottom + fill(type, xMax - borderWidth, yMin + borderWidth, xMax, yMax - borderWidth, bottomRightColour); //Right + fill(type, xMax - borderWidth, yMin, xMax, yMin + borderWidth, cornerMixColour); //Top Right Corner + fill(type, xMin, yMax - borderWidth, xMin + borderWidth, yMax, cornerMixColour); //Bottom Left Corner + + if (fillColour != 0) //No point rendering fill if there is no fill colour + fill(type, xMin + borderWidth, yMin + borderWidth, xMax - borderWidth, yMax - borderWidth, fillColour); //Fill + } + + //=== Generic Backgrounds ===// + + /** + * Draws a rectangle / background with a style matching vanilla tool tips. + */ + public void toolTipBackground(double x, double y, double width, double height) { + toolTipBackground(x, y, width, height, 0xF0100010, 0x505000FF, 0x5028007f); + } + + /** + * Draws a rectangle / background with a style matching vanilla tool tips. + * Vanilla Default Colours: 0xF0100010, 0x505000FF, 0x5028007f + */ + public void toolTipBackground(double x, double y, double width, double height, int backgroundColour, int borderColourTop, int borderColourBottom) { + toolTipBackground(x, y, width, height, backgroundColour, backgroundColour, borderColourTop, borderColourBottom, false); + } + + /** + * Draws a rectangle / background with a style matching vanilla tool tips. + * Vanilla Default Colours: 0xF0100010, 0xF0100010, 0x505000FF, 0x5028007f + */ + public void toolTipBackground(double x, double y, double width, double height, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom, boolean empty) { + if (batchDraw) { //Draw batched for efficiency, unless already doing a batch draw. + toolTipBackgroundInternal(x, y, x + width, y + height, backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false); + } else { + batchDraw(() -> toolTipBackgroundInternal(x, y, x + width, y + height, backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false)); + } + } + + private void toolTipBackgroundInternal(double xMin, double yMin, double xMax, double yMax, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom, boolean empty) { + fill(xMin + 1, yMin, xMax - 1, yMin + 1, backgroundColourTop); // Top + fill(xMin + 1, yMax - 1, xMax - 1, yMax, backgroundColourBottom); // Bottom + gradientFillV(xMin, yMin + 1, xMin + 1, yMax - 1, backgroundColourTop, backgroundColourBottom); // Left + gradientFillV(xMax - 1, yMin + 1, xMax, yMax - 1, backgroundColourTop, backgroundColourBottom); // Right + if (!empty) { + gradientFillV(xMin + 1, yMin + 1, xMax - 1, yMax - 1, backgroundColourTop, backgroundColourBottom); // Fill + } + gradientFillV(xMin + 1, yMin + 1, xMin + 2, yMax - 1, borderColourTop, borderColourBottom); // Left Accent + gradientFillV(xMax - 2, yMin + 1, xMax - 1, yMax - 1, borderColourTop, borderColourBottom); // Right Accent + fill(xMin + 2, yMin + 1, xMax - 2, yMin + 2, borderColourTop); // Top Accent + fill(xMin + 2, yMax - 2, xMax - 2, yMax - 1, borderColourBottom); // Bottom Accent + } + + //=== Textured geometry ===// + + //Sprite plus RenderType + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void spriteRect(RenderType type, Rectangle rectangle, TextureAtlasSprite sprite) { + spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), sprite, 1F, 1F, 1F, 1F); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void spriteRect(RenderType type, Rectangle rectangle, TextureAtlasSprite sprite, int argb) { + spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), sprite, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void spriteRect(RenderType type, Rectangle rectangle, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { + spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), sprite, red, green, blue, alpha); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void spriteRect(RenderType type, double x, double y, double width, double height, TextureAtlasSprite sprite) { + spriteRect(type, x, y, width, height, sprite, 1F, 1F, 1F, 1F); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void spriteRect(RenderType type, double x, double y, double width, double height, TextureAtlasSprite sprite, int argb) { + spriteRect(type, x, y, width, height, sprite, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void spriteRect(RenderType type, double x, double y, double width, double height, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { + sprite(type, x, y, x + width, y + height, sprite, red, green, blue, alpha); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite) { + sprite(type, xMin, yMin, xMax, yMax, sprite, 1F, 1F, 1F, 1F); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int argb) { + sprite(type, xMin, yMin, xMax, yMax, sprite, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { + VertexConsumer buffer = buffers().getBuffer(type); + Matrix4f mat = pose.last().pose(); + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV1()).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV0()).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV0()).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV1()).endVertex(); //L-B + flushIfUnBatched(); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void spriteRect(RenderType type, Rectangle rectangle, int rotation, TextureAtlasSprite sprite) { + spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, sprite, 1F, 1F, 1F, 1F); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void spriteRect(RenderType type, Rectangle rectangle, int rotation, TextureAtlasSprite sprite, int argb) { + spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, sprite, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void spriteRect(RenderType type, Rectangle rectangle, int rotation, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { + spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, sprite, red, green, blue, alpha); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void spriteRect(RenderType type, double x, double y, double width, double height, int rotation, TextureAtlasSprite sprite) { + spriteRect(type, x, y, width, height, rotation, sprite, 1F, 1F, 1F, 1F); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void spriteRect(RenderType type, double x, double y, double width, double height, int rotation, TextureAtlasSprite sprite, int argb) { + spriteRect(type, x, y, width, height, rotation, sprite, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void spriteRect(RenderType type, double x, double y, double width, double height, int rotation, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { + sprite(type, x, y, x + width, y + height, rotation, sprite, red, green, blue, alpha); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite) { + sprite(type, xMin, yMin, xMax, yMax, rotation, sprite, 1F, 1F, 1F, 1F); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, int argb) { + sprite(type, xMin, yMin, xMax, yMax, rotation, sprite, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { + float[] u = {sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0()}; + float[] v = {sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0()}; + VertexConsumer buffer = buffers().getBuffer(type); + Matrix4f mat = pose.last().pose(); + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).endVertex(); //L-B + flushIfUnBatched(); + } + + //Partial Sprite + + //TODO figure out if there is a way to make this work. +// /** +// * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX +// * Texture will be resized / reshaped as appropriate to fit the defined area. +// *

+// * This is similar to {@link #partialSprite(RenderType, double, double, double, double, TextureAtlasSprite, float, float, float, float, int)} +// * Except the input uv values are in texture coordinates. So to draw a full 16x16 sprite with this you would supply 0, 0, 16, 16 +// * +// * @param rotation Rotates sprite clockwise in 90 degree steps. +// */ +// public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, int texXMin, int texYMin, int texXMax, int texYMax, int argb) { +// float width = sprite.contents().width(); +// float height = sprite.contents().height(); +// partialSprite(type, xMin, yMin, xMax, yMax, rotation, sprite, texXMin / width, texYMin / height, texXMax / width, texYMax / height, argb); +// } +// + +// /** +// * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX +// * Texture will be resized / reshaped as appropriate to fit the defined area. +// * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] +// * +// * @param rotation Rotates sprite clockwise in 90 degree steps. +// */ +// public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, int argb) { +// partialSprite(type, xMin, yMin, xMax, yMax, rotation, sprite, uMin, vMin, uMax, vMax, r(argb), g(argb), b(argb), a(argb)); +// } +// +// /** +// * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX +// * Texture will be resized / reshaped as appropriate to fit the defined area. +// * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] +// * +// * @param rotation Rotates sprite clockwise in 90 degree steps. +// */ +// public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, float left, float top, float right, float bottom, float red, float green, float blue, float alpha) { +// VertexConsumer buffer = buffers().getBuffer(type); +// Matrix4f mat = pose.last().pose(); +// rotation = Math.floorMod(rotation, 4); +// +// float[] sub = {left, top, right, bottom}; +// left = sub[rotation % 4]; +// top = sub[(rotation + 1) % 4]; +// right = sub[(rotation + 2) % 4]; +// bottom = sub[(rotation + 3) % 4]; +// +// float ul = sprite.getU1() - sprite.getU0(); +// float vl = sprite.getV1() - sprite.getV0(); +// float u0 = sprite.getU0() + (left * ul); +// float v0 = sprite.getV0() + (top * vl); +// float u1 = sprite.getU0() + (right * ul); +// float v1 = sprite.getV0() + (bottom * vl); +// float[] u = {u0, u1, u1, u0}; +// float[] v = {v1, v1, v0, v0}; +// buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B +// buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).endVertex(); //R-T +// buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).endVertex(); //L-T +// buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).endVertex(); //L-B +// flushIfUnBatched(); +// } + + /** + * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + *

+ * This is similar to {@link #partialSprite(RenderType, double, double, double, double, TextureAtlasSprite, float, float, float, float, int)} + * Except the input uv values are in texture coordinates. So to draw a full 16x16 sprite with this you would supply 0, 0, 16, 16 + */ + public void partialSpriteTex(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, double texXMin, double texYMin, double texXMax, double texYMax, int argb) { + partialSpriteTex(type, xMin, yMin, xMax, yMax, sprite, texXMin, texYMin, texXMax, texYMax, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + *

+ * This is similar to {@link #partialSprite(RenderType, double, double, double, double, TextureAtlasSprite, float, float, float, float, int)} + * Except the input uv values are in texture coordinates. So to draw a full 16x16 sprite with this you would supply 0, 0, 16, 16 + */ + public void partialSpriteTex(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, double texXMin, double texYMin, double texXMax, double texYMax, float red, float green, float blue, float alpha) { + int width = sprite.contents().width(); + int height = sprite.contents().height(); + partialSprite(type, xMin, yMin, xMax, yMax, sprite, (float) texXMin / width, (float) texYMin / height, (float) texXMax / width, (float) texYMax / height, red, green, blue, alpha); + } + + /** + * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] + */ + public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, int argb) { + partialSprite(type, xMin, yMin, xMax, yMax, sprite, uMin, vMin, uMax, vMax, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX + * Texture will be resized / reshaped as appropriate to fit the defined area. + * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] + */ + public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, float red, float green, float blue, float alpha) { + VertexConsumer buffer = buffers().getBuffer(type); + Matrix4f mat = pose.last().pose(); + float u0 = sprite.getU0(); + float v0 = sprite.getV0(); + float u1 = sprite.getU1(); + float v1 = sprite.getV1(); + float ul = u1 - u0; + float vl = v1 - v0; + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u0 + (uMax * ul), v0 + (vMax * vl)).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u0 + (uMax * ul), v0 + (vMin * vl)).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u0 + (uMin * ul), v0 + (vMin * vl)).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u0 + (uMin * ul), v0 + (vMax * vl)).endVertex(); //L-B + flushIfUnBatched(); + } + + /** + * Draw a sprite tiled to fit the specified area. + * Sprite is drawn from the top-left so sprite will be tiled right and down. + */ + public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int argb) { + tileSprite(type, xMin, yMin, xMax, yMax, sprite, sprite.contents().width(), sprite.contents().height(), argb); + } + + /** + * Draw a sprite tiled to fit the specified area. + * Sprite is drawn from the top-left so sprite will be tiled right and down. + * + * @param textureWidth Set base width of the sprite texture in pixels + * @param textureHeight Set base height of the sprite texture in pixels + */ + public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int textureWidth, int textureHeight, int argb) { + tileSprite(type, xMin, yMin, xMax, yMax, sprite, textureWidth, textureHeight, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draw a sprite tiled to fit the specified area. + * Sprite is drawn from the top-left so sprite will be tiled right and down. + */ + public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { + tileSprite(type, xMin, yMin, xMax, yMax, sprite, sprite.contents().width(), sprite.contents().height(), red, green, blue, alpha); + } + + /** + * Draw a sprite tiled to fit the specified area. + * Sprite is drawn from the top-left so sprite will be tiled right and down. + * + * @param textureWidth Set base width of the sprite texture in pixels + * @param textureHeight Set base height of the sprite texture in pixels + */ + public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int textureWidth, int textureHeight, float red, float green, float blue, float alpha) { + double width = xMax - xMin; + double height = yMax - yMin; + if (width <= textureWidth && height <= textureHeight) { + partialSprite(type, xMin, yMin, xMax, yMax, sprite, 0F, 0F, (float) width / textureWidth, (float) height / textureHeight, red, green, blue, alpha); + } else { + Runnable draw = () -> { + double xPos = xMin; + do { + double sectionWidth = Math.min(textureWidth, xMax - xPos); + double uWidth = sectionWidth / textureWidth; + double yPos = yMin; + do { + double sectionHeight = Math.min(textureHeight, yMax - yPos); + double vWidth = sectionHeight / textureHeight; + partialSprite(type, xPos, yPos, xPos + sectionWidth, yPos + sectionHeight, sprite, 0, 0, (float) uWidth, (float) vWidth, red, green, blue, alpha); + yPos += textureHeight; + } while (yPos < yMax); + xPos += textureWidth; + } while (xPos < xMax); + }; + if (batchDraw) { + draw.run(); + } else { + batchDraw(draw); + } + } + } + + //Material + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void texRect(Material material, Rectangle rectangle) { + texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), 1F, 1F, 1F, 1F); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void texRect(Material material, Rectangle rectangle, int argb) { + texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void texRect(Material material, Rectangle rectangle, float red, float green, float blue, float alpha) { + texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), red, green, blue, alpha); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void texRect(Material material, double x, double y, double width, double height) { + texRect(material, x, y, width, height, 1F, 1F, 1F, 1F); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void texRect(Material material, double x, double y, double width, double height, int argb) { + texRect(material, x, y, width, height, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void texRect(Material material, double x, double y, double width, double height, float red, float green, float blue, float alpha) { + tex(material, x, y, x + width, y + height, red, green, blue, alpha); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void tex(Material material, double xMin, double yMin, double xMax, double yMax) { + tex(material, xMin, yMin, xMax, yMax, 1F, 1F, 1F, 1F); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void tex(Material material, double xMin, double yMin, double xMax, double yMax, int argb) { + tex(material, xMin, yMin, xMax, yMax, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + */ + public void tex(Material material, double xMin, double yMin, double xMax, double yMax, float red, float green, float blue, float alpha) { + TextureAtlasSprite sprite = material.sprite(); + VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); + Matrix4f mat = pose.last().pose(); + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV1()).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV0()).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV0()).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV1()).endVertex(); //L-B + flushIfUnBatched(); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void texRect(Material material, int rotation, Rectangle rectangle) { + texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, 1F, 1F, 1F, 1F); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void texRect(Material material, int rotation, Rectangle rectangle, int argb) { + texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void texRect(Material material, int rotation, Rectangle rectangle, float red, float green, float blue, float alpha) { + texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, red, green, blue, alpha); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void texRect(Material material, int rotation, double x, double y, double width, double height) { + texRect(material, x, y, width, height, rotation, 1F, 1F, 1F, 1F); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void texRect(Material material, int rotation, double x, double y, double width, double height, int argb) { + texRect(material, x, y, width, height, rotation, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void texRect(Material material, double x, double y, double width, double height, int rotation, float red, float green, float blue, float alpha) { + tex(material, x, y, x + width, y + height, rotation, red, green, blue, alpha); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void tex(Material material, int rotation, double xMin, double yMin, double xMax, double yMax) { + tex(material, xMin, yMin, xMax, yMax, rotation, 1F, 1F, 1F, 1F); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void tex(Material material, double xMin, double yMin, double xMax, double yMax, int rotation, int argb) { + tex(material, xMin, yMin, xMax, yMax, rotation, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * Draws a texture sprite derived from the provided material. + * Texture will be resized / reshaped as appropriate to fit the defined area. + * + * @param rotation Rotates sprite clockwise in 90 degree steps. + */ + public void tex(Material material, double xMin, double yMin, double xMax, double yMax, int rotation, float red, float green, float blue, float alpha) { + TextureAtlasSprite sprite = material.sprite(); + VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); + float[] u = {sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0()}; + float[] v = {sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0()}; + Matrix4f mat = pose.last().pose(); + buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B + buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).endVertex(); //R-T + buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).endVertex(); //L-T + buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).endVertex(); //L-B + flushIfUnBatched(); + } + + //Slice and stitch + + /** + * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. + * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. + * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. + */ + public void dynamicTex(Material material, Rectangle rectangle, Borders borders, int argb) { + dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), (int) borders.top(), (int) borders.left(), (int) borders.bottom(), (int) borders.right(), argb); + } + + /** + * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. + * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. + * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. + */ + public void dynamicTex(Material material, Rectangle rectangle, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int argb) { + dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), topBorder, leftBorder, bottomBorder, rightBorder, argb); + } + + /** + * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. + * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. + * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. + */ + public void dynamicTex(Material material, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int argb) { + dynamicTex(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, r(argb), g(argb), b(argb), a(argb)); + } + + /** + * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. + * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. + * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. + */ + public void dynamicTex(Material material, Rectangle rectangle, Borders borders) { + dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), (int) borders.top(), (int) borders.left(), (int) borders.bottom(), (int) borders.right()); + } + + /** + * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. + * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. + * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. + */ + public void dynamicTex(Material material, Rectangle rectangle, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), topBorder, leftBorder, bottomBorder, rightBorder); + } + + /** + * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. + * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. + * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. + */ + public void dynamicTex(Material material, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + dynamicTex(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, 1F, 1F, 1F, 1F); + } + + /** + * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. + * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. + * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. + */ + public void dynamicTex(Material material, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder, float red, float green, float blue, float alpha) { + if (batchDraw) {//Draw batched for efficiency, unless already doing a batch draw. + dynamicTexInternal(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, red, green, blue, alpha); + } else { + batchDraw(() -> dynamicTexInternal(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, red, green, blue, alpha)); + } + } + + //Todo, This method can probably be made a lot more efficient. + private void dynamicTexInternal(Material material, int xPos, int yPos, int xSize, int ySize, int topBorder, int leftBorder, int bottomBorder, int rightBorder, float red, float green, float blue, float alpha) { + TextureAtlasSprite sprite = material.sprite(); + VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); + Matrix4f mat = pose.last().pose(); + SpriteContents contents = sprite.contents(); + int texWidth = contents.width(); + int texHeight = contents.height(); + int trimWidth = texWidth - leftBorder - rightBorder; + int trimHeight = texHeight - topBorder - bottomBorder; + if (xSize <= texWidth) trimWidth = Math.min(trimWidth, xSize - rightBorder); + if (xSize <= 0 || ySize <= 0 || trimWidth <= 0 || trimHeight <= 0) return; + + for (int x = 0; x < xSize; ) { + int rWidth = Math.min(xSize - x, trimWidth); + int trimU = 0; + if (x != 0) { + if (x + leftBorder + trimWidth <= xSize) { + trimU = leftBorder; + } else { + trimU = (texWidth - (xSize - x)); + } + } + + //Top & Bottom trim + bufferDynamic(buffer, mat, sprite, xPos + x, yPos, trimU, 0, rWidth, topBorder, red, green, blue, alpha); + bufferDynamic(buffer, mat, sprite, xPos + x, yPos + ySize - bottomBorder, trimU, texHeight - bottomBorder, rWidth, bottomBorder, red, green, blue, alpha); + + rWidth = Math.min(xSize - x - leftBorder - rightBorder, trimWidth); + for (int y = 0; y < ySize; ) { + int rHeight = Math.min(ySize - y - topBorder - bottomBorder, trimHeight); + int trimV; + if (y + (texHeight - topBorder - bottomBorder) <= ySize) { + trimV = topBorder; + } else { + trimV = texHeight - (ySize - y); + } + + //Left & Right trim + if (x == 0 && y + topBorder < ySize - bottomBorder) { + bufferDynamic(buffer, mat, sprite, xPos, yPos + y + topBorder, 0, trimV, leftBorder, rHeight, red, green, blue, alpha); + bufferDynamic(buffer, mat, sprite, xPos + xSize - rightBorder, yPos + y + topBorder, trimU + texWidth - rightBorder, trimV, rightBorder, rHeight, red, green, blue, alpha); + } + + //Core + if (y + topBorder < ySize - bottomBorder && x + leftBorder < xSize - rightBorder) { + bufferDynamic(buffer, mat, sprite, xPos + x + leftBorder, yPos + y + topBorder, leftBorder, topBorder, rWidth, rHeight, red, green, blue, alpha); + } + y += trimHeight; + } + x += trimWidth; + } + } + + private void bufferDynamic(VertexConsumer builder, Matrix4f mat, TextureAtlasSprite tex, int x, int y, double textureX, double textureY, int width, int height, float red, float green, float blue, float alpha) { + int w = tex.contents().width(); + int h = tex.contents().height(); + //@formatter:off + builder.vertex(mat, x, y + height, 0).color(red, green, blue, alpha).uv(tex.getU((textureX / w) * 16D), tex.getV(((textureY + height) / h) * 16)).endVertex(); + builder.vertex(mat, x + width, y + height, 0).color(red, green, blue, alpha).uv(tex.getU(((textureX + width) / w) * 16), tex.getV(((textureY + height) / h) * 16)).endVertex(); + builder.vertex(mat, x + width, y, 0).color(red, green, blue, alpha).uv(tex.getU(((textureX + width) / w) * 16), tex.getV(((textureY) / h) * 16)).endVertex(); + builder.vertex(mat, x, y, 0).color(red, green, blue, alpha).uv(tex.getU((textureX / w) * 16), tex.getV(((textureY) / h) * 16)).endVertex(); + //@formatter:on + } + + //=== Strings ===// + + /** + * Draw string with shadow. + */ + public int drawString(@Nullable String message, double x, double y, int colour) { + return drawString(message, x, y, colour, true); + } + + public int drawString(@Nullable String message, double x, double y, int colour, boolean shadow) { + if (message == null) return 0; + int i = font().drawInBatch(message, (float) x, (float) y, colour, shadow, pose.last().pose(), buffers, Font.DisplayMode.NORMAL, 0, 15728880, font().isBidirectional()); + this.flushIfUnBatched(); + return i; + } + + /** + * Draw string with shadow. + */ + public int drawString(FormattedCharSequence message, double x, double y, int colour) { + return drawString(message, x, y, colour, true); + } + + public int drawString(FormattedCharSequence message, double x, double y, int colour, boolean shadow) { + int i = font().drawInBatch(message, (float) x, (float) y, colour, shadow, pose.last().pose(), buffers, Font.DisplayMode.NORMAL, 0, 15728880); + this.flushIfUnBatched(); + return i; + } + + /** + * Draw string with shadow. + */ + public int drawString(Component message, double x, double y, int colour) { + return drawString(message, x, y, colour, true); + } + + public int drawString(Component message, double x, double y, int colour, boolean shadow) { + return drawString(message.getVisualOrderText(), x, y, colour, shadow); + } + + /** + * Draw wrapped string with shadow. + */ + public void drawWordWrap(FormattedText message, double x, double y, int width, int colour) { + drawWordWrap(message, x, y, width, colour, false); + } + + public void drawWordWrap(FormattedText message, double x, double y, int width, int colour, boolean shadow) { + drawWordWrap(message, x, y, width, colour, shadow, font().lineHeight); + } + + public void drawWordWrap(FormattedText message, double x, double y, int width, int colour, boolean shadow, double spacing) { + for (FormattedCharSequence formattedcharsequence : font().split(message, width)) { + drawString(formattedcharsequence, x, y, colour, shadow); + y += spacing; + } + } + + /** + * Draw centered string with shadow. (centered on x position) + */ + public void drawCenteredString(String message, double x, double y, int colour) { + drawCenteredString(message, x, y, colour, true); + } + + public void drawCenteredString(String message, double x, double y, int colour, boolean shadow) { + drawString(message, x - font().width(message) / 2D, y, colour, shadow); + } + + /** + * Draw centered string with shadow. (centered on x position) + */ + public void drawCenteredString(Component message, double x, double y, int colour) { + drawCenteredString(message, x, y, colour, true); + } + + public void drawCenteredString(Component message, double x, double y, int colour, boolean shadow) { + FormattedCharSequence formattedcharsequence = message.getVisualOrderText(); + drawString(formattedcharsequence, x - font().width(formattedcharsequence) / 2D, y, colour, shadow); + } + + /** + * Draw centered string with shadow. (centered on x position) + */ + public void drawCenteredString(FormattedCharSequence message, double x, double y, int colour) { + drawCenteredString(message, x, y, colour, true); + } + + public void drawCenteredString(FormattedCharSequence message, double x, double y, int colour, boolean shadow) { + drawString(message, x - font().width(message) / 2D, y, colour, shadow); + } + + /** + * If text is to long ti fit between x and xMaz, the text will scroll from left to right. + * Otherwise, will render centered. + * This is mostly copied from {@link AbstractWidget#renderScrollingString(GuiGraphics, Font, Component, int, int, int, int, int)} + */ + @SuppressWarnings ("JavadocReference") + public void drawScrollingString(Component component, double x, double y, double xMax, int colour, boolean shadow) { + drawScrollingString(component, x, y, xMax, colour, shadow, true); + } + + /** + * If text is to long ti fit between x and xMaz, the text will scroll from left to right. + * Otherwise, will render centered. + * This is mostly copied from {@link net.minecraft.client.gui.components.AbstractWidget#renderScrollingString(GuiGraphics, Font, Component, int, int, int, int, int)} + */ + @SuppressWarnings ("JavadocReference") + public void drawScrollingString(Component component, double x, double y, double xMax, int colour, boolean shadow, boolean doScissor) { + int textWidth = font().width(component); + double width = xMax - x; + if (textWidth > width) { + double outside = textWidth - width; + double anim = (double) Util.getMillis() / 1000.0; + double e = Math.max(outside * 0.5, 3.0); + double f = Math.sin(1.5707963267948966 * Math.cos(6.283185307179586 * anim / e)) / 2.0 + 0.5; + double offset = Mth.lerp(f, 0.0, outside); + if (doScissor) pushScissor(x, y - 1, xMax, y + font().lineHeight + 1); + drawString(component, x - offset, y, colour, shadow); + if (doScissor) popScissor(); + } else { + drawCenteredString(component, (x + xMax) / 2, y, colour, shadow); + } + } + + //=== Tool Tips ===// + + private ItemStack tooltipStack = ItemStack.EMPTY; + + public void renderTooltip(ItemStack stack, double mouseX, double mouseY) { + renderTooltip(stack, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); + } + + public void renderTooltip(ItemStack stack, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + this.tooltipStack = stack; + this.toolTipWithImage(Screen.getTooltipFromItem(this.mc(), stack), stack.getTooltipImage(), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom); + this.tooltipStack = ItemStack.EMPTY; + } + + public void toolTipWithImage(List tooltips, Optional tooltipImage, ItemStack stack, double mouseX, double mouseY) { + toolTipWithImage(tooltips, tooltipImage, stack, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); + } + + public void toolTipWithImage(List tooltips, Optional tooltipImage, ItemStack stack, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + this.tooltipStack = stack; + this.toolTipWithImage(tooltips, tooltipImage, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom); + this.tooltipStack = ItemStack.EMPTY; + } + + public void toolTipWithImage(List tooltip, Optional tooltipImage, double mouseX, double mouseY) { + toolTipWithImage(tooltip, tooltipImage, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); + } + + public void toolTipWithImage(List tooltip, Optional tooltipImage, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, tooltip, tooltipImage, (int) mouseX, guiWidth(), guiHeight(), font()); + this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); + } + + public void renderTooltip(Component message, double mouseX, double mouseY) { + renderTooltip(message, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); + } + + public void renderTooltip(Component message, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + this.renderTooltip(List.of(message.getVisualOrderText()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom); + } + + public void componentTooltip(List tooltips, double mouseX, double mouseY) { + componentTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); + } + + public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); + this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); + } + + public void componentTooltip(List tooltips, double mouseX, double mouseY, ItemStack stack) { + componentTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f, stack); + } + + public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ItemStack stack) { + this.tooltipStack = stack; + List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); + this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); + this.tooltipStack = ItemStack.EMPTY; + } + + public void renderTooltip(List tooltips, double mouseX, double mouseY) { + renderTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); + } + + public void renderTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + this.renderTooltipInternal(tooltips.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); + } + + public void renderTooltip(List tooltips, ClientTooltipPositioner positioner, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { + this.renderTooltipInternal(tooltips.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, positioner); + } + + private void renderTooltipInternal(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ClientTooltipPositioner positioner) { + if (!tooltips.isEmpty()) { + RenderTooltipEvent.Pre event = ForgeHooksClient.onRenderTooltipPre(tooltipStack, guiGraphicsWrapper(), (int) mouseX, (int) mouseY, guiWidth(), guiHeight(), tooltips, font(), positioner); + if (event.isCanceled()) return; + + + int width = 0; + int height = tooltips.size() == 1 ? -2 : 0; + for (ClientTooltipComponent line : tooltips) { + width = Math.max(width, line.getWidth(event.getFont())); + height += line.getHeight(); + } + + Vector2ic position = positioner.positionTooltip(guiWidth(), guiHeight(), event.getX(), event.getY(), width, height); + int xPos = position.x(); + int yPos = Math.max(position.y(), 3); //Default positioner allows negative y-pos for some reason... + + RenderTooltipEvent.Color colorEvent = new RenderTooltipEvent.Color(tooltipStack, guiGraphicsWrapper(), (int) mouseX, (int) mouseY, font(), backgroundTop, borderTop, borderBottom, tooltips); + colorEvent.setBackgroundEnd(backgroundBottom); + MinecraftForge.EVENT_BUS.post(colorEvent); + + toolTipBackground(xPos - 3, yPos - 3, width + 6, height + 6, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd(), false); + int linePos = yPos; + + for (int i = 0; i < tooltips.size(); ++i) { + ClientTooltipComponent component = tooltips.get(i); + component.renderText(event.getFont(), xPos, linePos, pose.last().pose(), buffers); + linePos += component.getHeight() + (i == 0 ? 2 : 0); + } + + linePos = yPos; + + for (int i = 0; i < tooltips.size(); ++i) { + ClientTooltipComponent component = tooltips.get(i); + component.renderImage(event.getFont(), xPos, linePos, renderWrapper); + linePos += component.getHeight() + (i == 0 ? 2 : 0); + } + } + } + + public void renderComponentHoverEffect(@Nullable Style style, int mouseX, int mouseY) { + if (style != null && style.getHoverEvent() != null) { + HoverEvent event = style.getHoverEvent(); + HoverEvent.ItemStackInfo stackInfo = event.getValue(HoverEvent.Action.SHOW_ITEM); + if (stackInfo != null) { + renderTooltip(stackInfo.getItemStack(), mouseX, mouseY); + } else { + HoverEvent.EntityTooltipInfo tooltipInfo = event.getValue(HoverEvent.Action.SHOW_ENTITY); + if (tooltipInfo != null) { + if (mc().options.advancedItemTooltips) { + componentTooltip(tooltipInfo.getTooltipLines(), mouseX, mouseY); + } + } else { + Component component = event.getValue(HoverEvent.Action.SHOW_TEXT); + if (component != null) { + renderTooltip(font().split(component, Math.max(this.guiWidth() / 2, 200)), mouseX, mouseY); + } + } + } + } + } + + //=== ItemStacks ===// + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is 32, This must be accounted for when setting the z depth in an element using this render method. + */ + public void renderItem(ItemStack stack, double x, double y) { + renderItem(stack, x, y, 16); + } + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. + */ + public void renderItem(ItemStack stack, double x, double y, double size) { + this.renderItem(mc().player, mc().level, stack, x, y, size, 0); + } + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. + */ + public void renderItem(ItemStack stack, double x, double y, double size, int modelRand) { + this.renderItem(mc().player, mc().level, stack, x, y, size, modelRand); + } + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is 32, This must be accounted for when setting the z depth in an element using this render method. + */ + public void renderFakeItem(ItemStack stack, double x, double y) { + renderFakeItem(stack, x, y, 16); + } + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. + */ + public void renderFakeItem(ItemStack stack, double x, double y, double size) { + this.renderItem(null, mc().level, stack, x, y, size, 0); + } + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is 32, This must be accounted for when setting the z depth in an element using this render method. + */ + public void renderItem(LivingEntity entity, ItemStack stack, double x, double y, int modelRand) { + renderItem(entity, stack, x, y, 16, modelRand); + } + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. + */ + public void renderItem(LivingEntity entity, ItemStack stack, double x, double y, double size, int modelRand) { + this.renderItem(entity, entity.level(), stack, x, y, size, modelRand); + } + + /** + * Renders an item stack on the screen. + * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. + * + * @param size Width and height of the stack in pixels (Standard default is 16) + * @param modelRand A somewhat random value used in model gathering, Not very important, Can just use 0 or x/y position. + */ + public void renderItem(@Nullable LivingEntity entity, @Nullable Level level, ItemStack stack, double x, double y, double size, int modelRand) { + if (!stack.isEmpty()) { + BakedModel bakedmodel = mc().getItemRenderer().getModel(stack, level, entity, modelRand); + pose.pushPose(); + pose.translate(x + (size / 2D), y + (size / 2D), size); + try { + pose.mulPoseMatrix((new Matrix4f()).scaling(1.0F, -1.0F, 1.0F)); + pose.scale((float) size, (float) size, (float) size); + boolean flag = !bakedmodel.usesBlockLight(); + if (flag) Lighting.setupForFlatItems(); + mc().getItemRenderer().render(stack, ItemDisplayContext.GUI, false, pose, buffers, 0xf000f0, OverlayTexture.NO_OVERLAY, bakedmodel); + this.flush(); + if (flag) Lighting.setupFor3DItems(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item"); + CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered"); + crashreportcategory.setDetail("Item Type", () -> String.valueOf(stack.getItem())); + crashreportcategory.setDetail("Item Stack", () -> String.valueOf(stack.getItem())); + crashreportcategory.setDetail("Item Damage", () -> String.valueOf(stack.getDamageValue())); + crashreportcategory.setDetail("Item NBT", () -> String.valueOf(stack.getTag())); + crashreportcategory.setDetail("Item Foil", () -> String.valueOf(stack.hasFoil())); + throw new ReportedException(crashreport); + } + pose.popPose(); + } + } + + /** + * Draw item decorations (Count, Damage, Cool-down) + * This should be rendered at the same position and size as the item. + * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. + * Z depth requirements are the same as the renderItem method. + */ + public void renderItemDecorations(ItemStack stack, double x, double y) { + renderItemDecorations(stack, x, y, 16); + } + + /** + * Draw item decorations (Count, Damage, Cool-down) + * This should be rendered at the same position and size as the item. + * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. + * Z depth requirements are the same as the renderItem method. + */ + public void renderItemDecorations(ItemStack stack, double x, double y, double size) { + this.renderItemDecorations(stack, x, y, size, null); + } + + /** + * Draw item decorations (Count, Damage, Cool-down) + * This should be rendered at the same position and size as the item. + * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. + * Z depth requirements are the same as the renderItem method. + */ + public void renderItemDecorations(ItemStack stack, double x, double y, @Nullable String text) { + renderItemDecorations(stack, x, y, 16, text); + } + + /** + * Draw item decorations (Count, Damage, Cool-down) + * This should be rendered at the same position and size as the item. + * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. + * Z depth requirements are the same as the renderItem method. + */ + public void renderItemDecorations(ItemStack stack, double x, double y, double size, @Nullable String text) { + if (!stack.isEmpty()) { + pose.pushPose(); + float scale = (float) size / 16F; + pose.translate(x, y, (size * 2) - 0.1); + pose.scale(scale, scale, 1F); + pose.translate(-x, -y, 0); + + if (stack.getCount() != 1 || text != null) { + String s = text == null ? String.valueOf(stack.getCount()) : text; + drawString(s, x + 19 - 2 - font().width(s), y + 6 + 3, 0xffffff, true); + } + + if (stack.isBarVisible()) { + int l = stack.getBarWidth(); + int i = stack.getBarColor(); + double j = x + 2; + double k = y + 13; + pose.translate(0.0F, 0.0F, 0.04); + fill(j, k, j + 13, k + 2, 0xff000000); + pose.translate(0.0F, 0.0F, 0.02); + fill(j, k, j + l, k + 1, i | 0xff000000); + } + + LocalPlayer localplayer = mc().player; + float f = localplayer == null ? 0.0F : localplayer.getCooldowns().getCooldownPercent(stack.getItem(), mc().getFrameTime()); + if (f > 0.0F) { + double i1 = y + Mth.floor(16.0F * (1.0F - f)); + double j1 = i1 + Mth.ceil(16.0F * f); + pose.translate(0.0F, 0.0F, 0.02); + fill(x, i1, x + 16, j1, Integer.MAX_VALUE); + } + + pose.popPose(); + if (size == 16) { + net.minecraftforge.client.ItemDecoratorHandler.of(stack).render(guiGraphicsWrapper(), font(), stack, (int) x, (int) y); + } + } + } + + + //=== Entity? ===// + + + //=== Render Utils ===// + + public void pushScissorRect(Rectangle rectangle) { + pushScissorRect(rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height()); + } + + public void pushScissorRect(double x, double y, double width, double height) { + flushIfBatched(); + scissorHandler.pushGuiScissor(x, y, width, height); + } + + public void pushScissor(double xMin, double yMin, double xMax, double yMax) { + flushIfBatched(); + scissorHandler.pushGuiScissor(xMin, yMin, xMax - xMin, yMax - yMin); + } + + public void popScissor() { + scissorHandler.popScissor(); + } + + /** + * Sets the render system shader colour, Effect will vary depending on what is being rendered. + * Ideally this should be avoided in favor of render calls that accept colour. + */ + public void setColor(float red, float green, float blue, float alpha) { + this.flushIfBatched(); + RenderSystem.setShaderColor(red, green, blue, alpha); + } + + //=== Static Utils ===// + + public static boolean isInRect(double minX, double minY, double width, double height, double testX, double testY) { + return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); + } + + public static boolean isInRect(int minX, int minY, int width, int height, double testX, double testY) { + return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); + } + + /** + * Mixes the two input colours by adding up the R, G, B and A values of each input. + */ + public static int mixColours(int colour1, int colour2) { + return mixColours(colour1, colour2, false); + } + + /** + * Mixes the two input colours by adding up the R, G, B and A values of each input. + * + * @param subtract If true, subtract colour2 from colour1, otherwise add colour2 to colour1. + */ + public static int mixColours(int colour1, int colour2, boolean subtract) { + int alpha1 = colour1 >> 24 & 255; + int alpha2 = colour2 >> 24 & 255; + int red1 = colour1 >> 16 & 255; + int red2 = colour2 >> 16 & 255; + int green1 = colour1 >> 8 & 255; + int green2 = colour2 >> 8 & 255; + int blue1 = colour1 & 255; + int blue2 = colour2 & 255; + + int alpha = Mth.clamp(alpha1 + (subtract ? -alpha2 : alpha2), 0, 255); + int red = Mth.clamp(red1 + (subtract ? -red2 : red2), 0, 255); + int green = Mth.clamp(green1 + (subtract ? -green2 : green2), 0, 255); + int blue = Mth.clamp(blue1 + (subtract ? -blue2 : blue2), 0, 255); + + return (alpha & 0xFF) << 24 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF; + } + + /** + * Returns a colour half-way between the two input colours. + * The R, G, B and A channels are extracted from each input, + * Then for each chanel, a midpoint is determined, + * And a new colour is constructed based on the midpoint of each channel. + */ + public static int midColour(int colour1, int colour2) { + int alpha1 = colour1 >> 24 & 255; + int alpha2 = colour2 >> 24 & 255; + int red1 = colour1 >> 16 & 255; + int red2 = colour2 >> 16 & 255; + int green1 = colour1 >> 8 & 255; + int green2 = colour2 >> 8 & 255; + int blue1 = colour1 & 255; + int blue2 = colour2 & 255; + return (alpha2 + (alpha1 - alpha2) / 2 & 0xFF) << 24 | (red2 + (red1 - red2) / 2 & 0xFF) << 16 | (green2 + (green1 - green2) / 2 & 0xFF) << 8 | blue2 + (blue1 - blue2) / 2 & 0xFF; + } + + private static float r(int argb) { + return (argb >> 16 & 255) / 255F; + } + + private static float g(int argb) { + return (argb >> 8 & 255) / 255F; + } + + private static float b(int argb) { + return (argb & 255) / 255F; + } + + private static float a(int argb) { + return (argb >>> 24) / 255F; + } + + //Render Type Builders + + public static RenderType texType(ResourceLocation location) { + return RenderType.create("tex_type", DefaultVertexFormat.POSITION_TEX, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() + .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionTexShader)) + .setTextureState(new RenderStateShard.TextureStateShard(location, false, false)) + .setTransparencyState(RenderStateShard.TRANSLUCENT_TRANSPARENCY) + .setCullState(RenderStateShard.NO_CULL) + .createCompositeState(false)); + } + + public static RenderType texColType(ResourceLocation location) { + return RenderType.create("tex_col_type", DefaultVertexFormat.POSITION_COLOR_TEX, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() + .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionColorTexShader)) + .setTextureState(new RenderStateShard.TextureStateShard(location, false, false)) + .setTransparencyState(RenderStateShard.TRANSLUCENT_TRANSPARENCY) + .setCullState(RenderStateShard.NO_CULL) + .createCompositeState(false)); + } + + /** + * This exists to allow thing like the Tooltip events to still function correctly, hopefully without exploding... + */ + public static class RenderWrapper extends GuiGraphics { + private final GuiRender wrapped; + + private RenderWrapper(GuiRender wrapped) { + super(wrapped.mc(), wrapped.pose(), wrapped.buffers()); + this.wrapped = wrapped; + } + + @Override + public void drawManaged(Runnable runnable) { + wrapped.batchDraw(runnable); + } + + @Override + public void flush() { + wrapped.flush(); + } + + @Override + public void flushIfManaged() { + wrapped.flushIfBatched(); + } + + @Override + public void flushIfUnmanaged() { + wrapped.flushIfUnBatched(); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java new file mode 100644 index 00000000..06952dec --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java @@ -0,0 +1,75 @@ +package codechicken.lib.gui.modular.lib; + +import com.google.common.collect.Queues; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Deque; + +/** + * Created by brandon3055 on 29/06/2023 + */ +public class ScissorHandler { + public static final Logger LOGGER = LogManager.getLogger(); + private final Deque stack = Queues.newArrayDeque(); + + public void pushGuiScissor(double x, double y, double width, double height) { + Window window = Minecraft.getInstance().getWindow(); + int windowHeight = window.getHeight(); + double scale = window.getGuiScale(); + double scX = x * scale; + double scY = (double) windowHeight - (y + height) * scale; + double scW = Math.max(width * scale, 0); + double scH = Math.max(height * scale, 0); + pushScissor((int) scX, (int) scY, (int) scW, (int) scH); + } + + public void pushScissor(int x, int y, int width, int height) { + int xMax = x + width; + int yMax = y + height; + stack.addLast(ScissorState.createState(x, y, xMax, yMax, stack.peekLast()).apply()); + } + + public void popScissor() { + if (stack.isEmpty()) { + LOGGER.error("Scissor stack underflow"); + } + stack.removeLast(); + ScissorState active = stack.peekLast(); + if (active != null) { + active.apply(); + } else { + RenderSystem.disableScissor(); + } + } + + private record ScissorState(int x, int y, int xMax, int yMax) { + + private ScissorState apply() { + RenderSystem.enableScissor(x, y, xMax - x, yMax - y); + return this; + } + + private static ScissorState createState(int newX, int newY, int newXMax, int newYMax, ScissorState prevState) { + if (prevState != null) { + int x = Math.max(prevState.x, newX); + int y = Math.max(prevState.y, newY); + int xMax = Math.min(prevState.xMax, newXMax); + int yMax = Math.min(prevState.yMax, newYMax); + Minecraft mc = Minecraft.getInstance(); + if (x < 0) x = 0; + if (y < 0) y = 0; + if (xMax > mc.getWindow().getScreenWidth()) xMax = mc.getWindow().getScreenWidth(); + if (yMax > mc.getWindow().getScreenHeight()) yMax = mc.getWindow().getScreenHeight(); + if (xMax < x) xMax = x; + if (yMax < y) yMax = y; + return new ScissorState(x, y, xMax, yMax); + } else { + return new ScissorState(newX, newY, newXMax, newYMax); + } + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java b/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java new file mode 100644 index 00000000..a9724798 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java @@ -0,0 +1,139 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.lib.geometry.Axis; +import net.minecraft.client.gui.screens.Screen; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * The primary interface for managing getting and setting the position of slider elements. + *

+ * Created by brandon3055 on 01/09/2023 + */ +public interface SliderState { + + /** + * @return the current position. (Between 0 and 1) + */ + double getPos(); + + /** + * Set the current slide position, + * When using this method, make sure the provided value can not go outside the valid range of 0 to 1. + * + * @param pos Set the current position (Between 0 and 1) + */ + void setPos(double pos); + + /** + * The slider ratio is computed by dividing the length of the slider element by the total length of the slider track. + * This is primarily for things like setting the size of scroll bar sliders, and calibrating scrolling via middle-click + drag. + * + * @return scroll ratio, viewable content size / total content size (Range 0 to 1) + */ + default double sliderRatio() { + return 0.1; + } + + /** + * For controlling a slider via mouse scroll wheel. + * You can return a negative value to invert the scroll direction. + * + * @return The amount added to the position per scroll increment. + */ + default double scrollSpeed() { + double ratio = sliderRatio(); + return ratio < 0.1 ? ratio * 0.1 : ratio * ratio; + } + + /** + * @param scrollAxis The moving axis of the slider element. + * @return true if the current scroll wheel event should affect this slider. + */ + default boolean canScroll(Axis scrollAxis) { + return true; + } + + /** + * Creates a basic slide state which stores its position internally. + * Useful for things like simple slide control elements. + */ + static SliderState create(double speed) { + return create(speed, null); + } + + /** + * Creates a basic slide state which stores its position internally. + * And allows you to attach a change listener. + * Useful for things like simple slide control elements. + */ + static SliderState create(double speed, @Nullable Consumer changeListener) { + return new SliderState() { + double pos = 0; + + @Override + public double getPos() { + return pos; + } + + @Override + public void setPos(double pos) { + this.pos = pos; + if (changeListener != null) { + changeListener.accept(pos); + } + } + + @Override + public double scrollSpeed() { + return speed; + } + }; + } + + static SliderState forScrollBar(Supplier getPos, Consumer setPos, Supplier getRatio) { + return new SliderState() { + @Override + public double getPos() { + return getPos.get(); + } + + @Override + public void setPos(double pos) { + setPos.accept(pos); + } + + @Override + public double sliderRatio() { + return getRatio.get(); + } + + @Override + public boolean canScroll(Axis scrollAxis) { + //Controls scrolling left and right when shift key is down. + return (scrollAxis == Axis.Y) != Screen.hasShiftDown(); + } + }; + } + + static SliderState forSlider(Supplier getPos, Consumer setPos, Supplier getSpeed) { + return new SliderState() { + @Override + public double getPos() { + return getPos.get(); + } + + @Override + public void setPos(double pos) { + setPos.accept(pos); + } + + @Override + public double scrollSpeed() { + return getSpeed.get(); + } + }; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/TextState.java b/src/main/java/codechicken/lib/gui/modular/lib/TextState.java new file mode 100644 index 00000000..f92af296 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/TextState.java @@ -0,0 +1,56 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.elements.GuiTextField; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * The primary interface for managing getting and setting the text in a {@link GuiTextField} + *

+ * Created by brandon3055 on 03/09/2023 + */ +public interface TextState { + + String getText(); + + void setText(String text); + + static TextState simpleState(String defaultValue) { + return simpleState(defaultValue, null); + } + + static TextState simpleState(String defaultValue, @Nullable Consumer changeListener) { + return new TextState() { + private String value = defaultValue; + + @Override + public String getText() { + return value; + } + + @Override + public void setText(String text) { + this.value = text; + if (changeListener != null) { + changeListener.accept(value); + } + } + }; + } + + static TextState create(Supplier getValue, Consumer setValue) { + return new TextState() { + @Override + public String getText() { + return getValue.get(); + } + + @Override + public void setText(String text) { + setValue.accept(text); + } + }; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java new file mode 100644 index 00000000..7bc1bb20 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java @@ -0,0 +1,105 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.elements.GuiElement; +import net.covers1624.quack.util.SneakyUtils; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 01/09/2023 + */ +public interface TooltipHandler> { + + Supplier> getTooltip(); + + /** + * Set a delay before element tooltip is displayed. + * Default delay is 10 ticks. + */ + T setTooltipDelay(int tooltipDelay); + + int getTooltipDelay(); + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param Tooltip A single tooltip text component supplier. + * @see #setTooltipDelay(int) + */ + default T setTooltipSingle(@Nullable Component Tooltip) { + return setTooltip(Tooltip == null ? null : () -> Collections.singletonList(Tooltip)); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param Tooltip A single tooltip text component supplier. + * @see #setTooltipDelay(int) + */ + default T setTooltip(Component... Tooltip) { + return setTooltip(Tooltip == null ? null : () -> List.of(Tooltip)); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip A single line tooltip component supplier. + * @see #setTooltipDelay(int) + */ + default T setTooltipSingle(@Nullable Supplier tooltip) { + return setTooltip(tooltip == null ? null : () -> Collections.singletonList(tooltip.get())); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip The tooltip lines. If null or empty, hover text will be disabled + * @see #setTooltipDelay(int) + */ + default T setTooltip(@Nullable List tooltip) { + return setTooltip(tooltip == null ? null : () -> tooltip); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip The tooltip lines. If null or the returned list is empty, hover text will be disabled + * @see #setTooltipDelay(int) + */ + T setTooltip(@Nullable Supplier> tooltip); + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip The tooltip lines. If null or the returned list is empty, hover text will be disabled + * @param tooltipDelay Delay before hover text is shown. + */ + default T setTooltip(@Nullable Supplier> tooltip, int tooltipDelay) { + setTooltip(tooltip); + setTooltipDelay(tooltipDelay); + return SneakyUtils.unsafeCast(this); + } + + /** + * The method responsible for rendering element tool tips. + * Called from {@link GuiElement#renderOverlay(GuiRender, double, double, float, boolean)} + */ + default boolean renderTooltip(GuiRender render, double mouseX, double mouseY) { + Supplier> supplier = getTooltip(); + if (supplier == null) return false; + List list = supplier.get(); + if (list.isEmpty()) return false; + render.componentTooltip(list, mouseX, mouseY); + return true; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerGuiProvider.java b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerGuiProvider.java new file mode 100644 index 00000000..92282ee8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerGuiProvider.java @@ -0,0 +1,33 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.ModularGuiContainer; +import codechicken.lib.gui.modular.lib.GuiProvider; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.world.inventory.AbstractContainerMenu; + +/** + * Created by brandon3055 on 08/09/2023 + */ +public abstract class ContainerGuiProvider implements GuiProvider { + + private ContainerScreenAccess screenAccess; + + public void setMenuAccess(ContainerScreenAccess screenAccess) { + this.screenAccess = screenAccess; + } + + @Override + public final void buildGui(ModularGui gui) { + buildGui(gui, screenAccess); + } + + /** + * This is the same as {@link GuiProvider#buildGui(ModularGui)} except you have access to the {@link MenuAccess} + * The given menu accessor should always be the parent screen unless your using some custom modular gui implementation. + * + * @param gui The modular gui instance. + * @param screenAccess The screen access (This will be a gui class that extends {@link ModularGuiContainer} + */ + public abstract void buildGui(ModularGui gui, ContainerScreenAccess screenAccess); +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java new file mode 100644 index 00000000..d8998dd2 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java @@ -0,0 +1,22 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.gui.modular.elements.GuiSlots; +import codechicken.lib.gui.modular.lib.GuiRender; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; + +/** + * Used by {@link ContainerGuiProvider} + * Provides access to the ContainerMenu as well as some essential functions. + *

+ * Created by brandon3055 on 08/09/2023 + */ +public interface ContainerScreenAccess extends MenuAccess { + + /** + * This is the modular gui friendly method used by elements such as {@link GuiSlots} to render inventory item stacks. + */ + void renderSlot(GuiRender render, Slot slot); + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java b/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java new file mode 100644 index 00000000..4b0cb9ec --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java @@ -0,0 +1,48 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.inventory.container.data.AbstractDataStore; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; + +import java.util.function.Supplier; + +/** + * This class provides a convenient way to synchronize server side data with a client side screen via the ContainerMenu + *

+ * Created by brandon3055 on 09/09/2023 + */ +public class DataSync { + public static final int PKT_SEND_CHANGES = 255; + private final ModularGuiContainerMenu containerMenu; + private final AbstractDataStore dataStore; + private final Supplier valueGetter; + + public DataSync(ModularGuiContainerMenu containerMenu, AbstractDataStore dataStore, Supplier valueGetter) { + this.containerMenu = containerMenu; + this.dataStore = dataStore; + this.valueGetter = valueGetter; + containerMenu.dataSyncs.add(this); + } + + public T get() { + return dataStore.get(); + } + + /** + * This should only ever be called server side! + */ + public void detectAndSend() { + if (dataStore.isSameValue(valueGetter.get())) { + return; + } + dataStore.set(valueGetter.get()); + containerMenu.sendPacketToClient(PKT_SEND_CHANGES, buf -> { + buf.writeByte((byte) containerMenu.dataSyncs.indexOf(this)); + dataStore.toBytes(buf); + }); + } + + public void handleSyncPacket(MCDataInput buf) { + dataStore.fromBytes(buf); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java b/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java new file mode 100644 index 00000000..1b6ff101 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java @@ -0,0 +1,119 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.gui.modular.elements.GuiSlots; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import codechicken.lib.inventory.container.modular.ModularSlot; +import net.minecraft.world.Container; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.EnchantmentHelper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * Used to configure slots a set of slots in a ContainerMenu. + * The SlotGroup can then be passed to ModularGui elements such as {@link GuiSlots} in order to give the gui control over slot positioning and rendering. + *

+ * Ideally you should use a separate SlotGroup for each 'group' of slots, Meaning the players main inventory and hot bar should be separate ranges. + * That said, if you have multiple slots spread out across something like a machine gui, You can add them all to one SlotGroup then + * pass each individual slot from that range to a {@link GuiSlots#singleSlot(GuiParent, ContainerScreenAccess, SlotGroup, int)} + *

+ * Created by brandon3055 on 08/09/2023 + */ +public class SlotGroup { + + public final int zone; + public final List quickMoveTo; + + private final ModularGuiContainerMenu containerMenu; + private final List slots = new ArrayList<>(); + + public SlotGroup(ModularGuiContainerMenu containerMenu, int zone, int... quickMoveTo) { + this.zone = zone; + this.containerMenu = containerMenu; + this.quickMoveTo = Arrays.stream(quickMoveTo).boxed().toList(); + } + + public ModularSlot addSlot(ModularSlot slot) { + slots.add(slot); + containerMenu.addSlot(slot); + containerMenu.mapSlot(slot, this); + return slot; + } + + /** + * Convenient method for adding multiple slots. + * + * @param slotCount The number of slots to be added. + * @param startIndex Slot starting index. + * @param makeSlot Builder used to create the slots, Input integer will start at startIndex and increment by one for each slot. + */ + public void addSlots(int slotCount, int startIndex, Function makeSlot) { + for (int index = startIndex; index < startIndex + slotCount; index++) { + addSlot(makeSlot.apply(index)); + } + } + + public void addAllSlots(Container container) { + addAllSlots(container, ModularSlot::new); + } + + public void addAllSlots(Container container, BiFunction makeSlot) { + for (int index = 0; index < container.getContainerSize(); index++) { + addSlot(makeSlot.apply(container, index)); + } + } + + public void addPlayerMain(Inventory inventory) { + addSlots(27, 9, index -> new ModularSlot(inventory, index)); + } + + public void addPlayerBar(Inventory inventory) { + addSlots(9, 0, index -> new ModularSlot(inventory, index)); + } + + public void addPlayerArmor(Inventory inventory) { + for (int i = 0; i < 4; ++i) { + EquipmentSlot slot = EquipmentSlot.byTypeAndIndex(EquipmentSlot.Type.ARMOR, 3 - i); + addSlot(new ModularSlot(inventory, 39 - i) + .onSet((oldStack, newStack) -> onEquipItem(inventory, slot, newStack, oldStack)) + .setStackLimit(stack -> 1) + .setValidator(stack -> slot == Mob.getEquipmentSlotForItem(stack)) + .setCanRemove((player, stack) -> stack.isEmpty() || player.isCreative() || !EnchantmentHelper.hasBindingCurse(stack)) + ); + } + } + + public void addPlayerOffhand(Inventory inventory) { + addSlot(new ModularSlot(inventory, 40).onSet((oldStack, newStack) -> onEquipItem(inventory, EquipmentSlot.OFFHAND, newStack, oldStack))); + } + + static void onEquipItem(Inventory inventory, EquipmentSlot slot, ItemStack newStack, ItemStack oldStack) { + inventory.player.onEquipItem(slot, oldStack, newStack); + } + + public int size() { + return slots.size(); + } + + public ModularSlot getSlot(int index) { + return slots.get(index); + } + + public int indexOf(Slot slot) { + return slots.indexOf(slot); + } + + public List slots() { + return Collections.unmodifiableList(slots); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Align.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Align.java new file mode 100644 index 00000000..c38b84b3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Align.java @@ -0,0 +1,14 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Created by brandon3055 on 31/08/2023 + */ +public enum Align { + MIN, + CENTER, + MAX; + public static Align LEFT = MIN; + public static Align RIGHT = MAX; + public static Align TOP = MIN; + public static Align BOTTOM = MAX; +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Axis.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Axis.java new file mode 100644 index 00000000..7f4ac8f2 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Axis.java @@ -0,0 +1,13 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Created by brandon3055 on 02/09/2023 + */ +public enum Axis { + X, + Y; + + public Axis opposite() { + return this == X ? Y : X; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/AxisConfig.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/AxisConfig.java new file mode 100644 index 00000000..5fbd204b --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/AxisConfig.java @@ -0,0 +1,96 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import org.apache.commons.lang3.function.TriFunction; +import org.jetbrains.annotations.Nullable; + +/** + * Denies how each of the three axis parameters are computed based on the available constraints. + * Note: If both min and max are defined, size is ignored. + */ +public enum AxisConfig { + //@formatter:off + // | Compute Axis Min | Compute Axis Max | Compute Axis Size | + /** + * If nothing is constrained. + * min=0, max=0, size=0 + * */ + NONE (0, (min, max, size) -> 0D, (min, max, size) -> 0D, (min, max, size) -> 0D), + /** + * If only Min is constrained. + * min=min, max=min, size=0 + * */ + MIN_ONLY (1, (min, max, size) -> min.get(), (min, max, size) -> min.get(), (min, max, size) -> 0D), + /** + * If only Max is constrained. + * min=max, max=max, size=0 + * */ + MAX_ONLY (1, (min, max, size) -> max.get(), (min, max, size) -> max.get(), (min, max, size) -> 0D), + /** + * If only Size is constrained. + * min=0, max=size, size=size + * */ + SIZE_ONLY (1, (min, max, size) -> 0D, (min, max, size) -> size.get(), (min, max, size) -> size.get()), + /** + * If Min and Size are constrained . + * min=min, max=min+size, size=size + * */ + MIN_SIZE (2, (min, max, size) -> min.get(), (min, max, size) -> min.get() + size.get(), (min, max, size) -> size.get()), + /** + * If Max and Size are constrained. + * min=max-size, max=max, size=size + * */ + MAX_SIZE (2, (min, max, size) -> max.get() - size.get(), (min, max, size) -> max.get(), (min, max, size) -> size.get()), + /** + * If Min and Max are constrained. + * min=min, max=max, size=max-min + * */ + MIN_MAX (2, (min, max, size) -> min.get(), (min, max, size) -> max.get(), (min, max, size) -> max.get() - min.get()), + /** + * If Min, Max and Size are constrained the Size is ignored. + * min=min, max=max, size=max-min + * */ + MIN_MAX_SIZE(3, (min, max, size) -> min.get(), (min, max, size) -> max.get(), (min, max, size) -> max.get() - min.get()); + //@formatter:on + + public final int constraints; + public final TriFunction min; + public final TriFunction max; + public final TriFunction size; + //[min][max][size] TODO, I Clean this up once i confirm everything works correctly. + private static final AxisConfig[][][] LOOKUP = new AxisConfig[][][]{ + { //Min = 0 + { //Max = 0 + NONE, //Size = 0 + SIZE_ONLY //Size = 1 + }, + { //Max = 1 + MAX_ONLY, //Size = 0 + MAX_SIZE //Size = 1 + } + }, + { //Min = 1 + { //Max = 0 + MIN_ONLY, //Size = 0 + MIN_SIZE //Size = 1 + }, + { //Max = 1 + MIN_MAX, //Size = 0 + MIN_MAX_SIZE//Size = 1 + } + } + }; + + AxisConfig(int constraints, + TriFunction min, + TriFunction max, + TriFunction size) { + this.constraints = constraints; + this.min = min; + this.max = max; + this.size = size; + } + + public static AxisConfig getConfigFor(@Nullable Constraint min, @Nullable Constraint max, @Nullable Constraint size) { + return LOOKUP[min != null ? 1 : 0][max != null ? 1 : 0][size != null ? 1 : 0]; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Borders.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Borders.java new file mode 100644 index 00000000..d9ef9ce7 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Borders.java @@ -0,0 +1,118 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import java.util.Objects; + +/** + * Created by brandon3055 on 28/08/2023 + */ +public final class Borders { + public double top; + public double left; + public double bottom; + public double right; + + public Borders(double top, double left, double bottom, double right) { + this.top = top; + this.left = left; + this.bottom = bottom; + this.right = right; + } + + public static Borders create(double borders) { + return create(borders, borders); + } + + public static Borders create(double leftRight, double topBottom) { + return create(topBottom, leftRight, topBottom, leftRight); + } + + public static Borders create(double top, double left, double bottom, double right) { + return new Borders(top, left, bottom, right); + } + + public double top() { + return top; + } + + public double left() { + return left; + } + + public double bottom() { + return bottom; + } + + public double right() { + return right; + } + + public Borders top(double top) { + this.top = top; + return this; + } + + public Borders left(double left) { + this.left = left; + return this; + } + + public Borders bottom(double bottom) { + this.bottom = bottom; + return this; + } + + public Borders right(double right) { + this.right = right; + return this; + } + + public Borders setTopBottom(double topBottom) { + return top(topBottom).bottom(topBottom); + } + + public Borders setLeftRight(double leftRight) { + return left(leftRight).setLeftRight(leftRight); + } + + public Borders setBorders(double borders) { + return setBorders(borders, borders); + } + + public Borders setBorders(double topBottom, double leftRight) { + return setBorders(topBottom, leftRight, topBottom, leftRight); + } + + public Borders setBorders(double top, double left, double bottom, double right) { + this.top = top; + this.left = left; + this.bottom = bottom; + this.right = right; + return this; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (Borders) obj; + return Double.doubleToLongBits(this.top) == Double.doubleToLongBits(that.top) && + Double.doubleToLongBits(this.left) == Double.doubleToLongBits(that.left) && + Double.doubleToLongBits(this.bottom) == Double.doubleToLongBits(that.bottom) && + Double.doubleToLongBits(this.right) == Double.doubleToLongBits(that.right); + } + + @Override + public int hashCode() { + return Objects.hash(top, left, bottom, right); + } + + @Override + public String toString() { + return "Borders[" + + "top=" + top + ", " + + "left=" + left + ", " + + "bottom=" + bottom + ", " + + "right=" + right + ']'; + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java new file mode 100644 index 00000000..b0c62353 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java @@ -0,0 +1,376 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import codechicken.lib.gui.modular.elements.GuiElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This is the base class used to define the size and position of a GuiElement. + *

+ * The geometry system is designed to be very user-friendly, yet very powerful, with the ability to do all sorts of fun and interesting things. + * But if all you want is the ability to set simple size and position values, then there is no need to read any further. + * Just use the basic setters setXPos, setYPos, setWidth, setHeight and everything should just work. + * If you want to dive deeper, read on. + *

+ * The geometry system is based around 6 core parameters: xMin, xMax, xSize, yMin, yMax and ySize. See: {@link GeoParam}
+ * These parameters are defined using 'Constraints' See: {@link Constraint}
+ * When properly constrained, it will be possible to request values for any of these 6 parameters.
+ * For each axis (x and y) there are 3 constraints: min, max and size.
+ * In order for an axis to be properly defined 2 of these constraints need to be set.
+ * e.g. (xMin and xSize) or (xMin and xMax) or (xMax and xSize)
+ * Using any of these combinations the position and size of an axis can be computed. + *

+ * Look at {@link AxisConfig} for details on the values that get returned when too few constraints are set.
+ * TLDR: We will always try to return "reasonable" default values. e.g. if only size is constrained, xMin will default + * to 0 and xMax will default to 0 + xSize.
+ * If all three constraints are set then the size constraint will be ignored.
+ * You can use {@link #strictMode(boolean)} to change this behavior. + *

+ * There are a number of different types of constraints that can be used, including completely custom constraints.
+ * Take a look at the {@link Constraint} class for a detailed list with explanations. + *

+ * Note: + * All position and size values in ModularGui use doubles. This is because floating point position and size values + * can be very useful at times. But they can also cause a lot of ugly visual artifacts when not used properly. + * So by default, all the builtin constraints will cast their outputs to an integer value. + * If you need floating point precision, you can enable it by calling .precise() on any of the builtin constraints. + *

+ * Created by brandon3055 on 29/06/2023 + */ +public abstract class ConstrainedGeometry> implements GuiParent { + + private Constraint xMin = null; + private Constraint xMax = null; + private Constraint xSize = null; + private AxisConfig xAxis = AxisConfig.NONE; + + private Constraint yMin = null; + private Constraint yMax = null; + private Constraint ySize = null; + private AxisConfig yAxis = AxisConfig.NONE; + + //Permanently bound immutable position and rectangle elements. + private final Position position = Position.create(this); + private final Rectangle rectangle = Rectangle.create(this); + private final Rectangle.Mutable childBounds = getRectangle().mutable(); + + private boolean strictMode = false; + + @NotNull + public abstract GuiParent getParent(); + + public GeoRef getParent(GeoParam param) { + return getParent().get(param); + } + + //=== Simple Setters ===// + + /** + * Simple method for setting the x position of this element. + *

+ * Constrains the left side of this element, to the left side of the parent element, + * with an offset that is calculated by subtracting parent's current x pos from the given x pos. + *

+ * In other words, if the parent element's position changes, this element will move with it. + * + * @param x The X position in screen space. + * @return This Element. + */ + public T setXPos(double x) { + GeoRef parentLeft = getParent(LEFT); + return constrain(LEFT, Constraint.relative(parentLeft, x - parentLeft.get())); + } + + /** + * Simple method for setting the y position of this element. + *

+ * Constrains the top side of this element, to the top side of the parent element, + * with an offset that is calculated by subtracting parent's current y pos from the given y pos. + *

+ * In other words, if the parent element's position changes, this element will move with it. + * + * @param y The Y position in screen space. + * @return This Element. + */ + public T setYPos(double y) { + GeoRef parentTop = getParent(LEFT); + return constrain(LEFT, Constraint.relative(parentTop, y - parentTop.get())); + } + + /** + * Convenience method for setting both x and y positions. + * + * @param x The X position in screen space. + * @param y The Y position in screen space. + * @return This Element. + * @see #setXPos(double) + * @see #setYPos(double) + */ + public T setPos(double x, double y) { + return setXPos(x).setYPos(y); + } + + /** + * Simple method for setting the width of this element. + * + * @param width The width to apply. + * @return This Element. + */ + public T setWidth(double width) { + return constrain(WIDTH, Constraint.literal(width)); + } + + /** + * Simple method for setting the height of this element. + * + * @param height The height to apply. + * @return This Element. + */ + public T setHeight(double height) { + return constrain(HEIGHT, Constraint.literal(height)); + } + + /** + * Convenience method for setting both width and height. + * + * @param width The width to apply. + * @param height The height to apply. + * @return This Element. + * @see #setWidth(double) + * @see #setHeight(double) + */ + public T setSize(double width, double height) { + return setWidth(width).setHeight(height); + } + + //=== Everything related to constraint based geometry ===// + + /** + * @return The position of the Left edge of this element. + */ + @Override + public double xMin() { + return xAxis.min.apply(xMin, xMax, xSize); + } + + /** + * @return The position of the Right edge of this element. + */ + @Override + public double xMax() { + return xAxis.max.apply(xMin, xMax, xSize); + } + + /** + * @return The Width of this element. + */ + @Override + public double xSize() { + return xAxis.size.apply(xMin, xMax, xSize); + } + + /** + * @return The position of the Top edge of this element. + */ + @Override + public double yMin() { + return yAxis.min.apply(yMin, yMax, ySize); + } + + /** + * @return The position of the Bottom edge of this element. + */ + @Override + public double yMax() { + return yAxis.max.apply(yMin, yMax, ySize); + } + + /** + * @return The Height of this element. + */ + @Override + public double ySize() { + return yAxis.size.apply(yMin, yMax, ySize); + } + + /** + * Returns a reference to the specified geometry parameter. + * This is primarily used when defining geometry constraints. + * But it can also be used as a simple {@link Supplier} + * that will return the current parameter value when requested. + *

+ * Note: The returned geometry reference will always be valid + * + * @param param The geometry parameter. + * @return A Geometry Reference + */ + @Override + public GeoRef get(GeoParam param) { + return new GeoRef(this, param); + } + + /** + * @param param The geometry parameter to be constrained. + * @param constraint The constraint to apply + * @return This Element. + */ + @SuppressWarnings ("unchecked") + public T constrain(GeoParam param, @Nullable Constraint constraint) { + if (constraint != null && constraint.axis() != null && constraint.axis() != param.axis) { + throw new IllegalStateException("Attempted to apply constraint for axis: " + constraint.axis() + ", to Parameter: " + param); + } + if (param.axis == Axis.X) { + constrainX(param, constraint); + } else if (param.axis == Axis.Y) { + constrainY(param, constraint); + } + return (T) this; + } + + /** + * Clear any configured constraints and reset this element to default unconstrained state. + * Convenient when reconfiguring an elements constraints or applying constraints to an element + * with an existing, unknown constraint configuration. + */ + @SuppressWarnings ("unchecked") + public T clearConstraints() { + xMin = xMax = xSize = yMin = yMax = ySize = null; + xAxis = yAxis = AxisConfig.NONE; + return (T) this; + } + + private void constrainX(GeoParam param, @Nullable Constraint constraint) { + if (param == GeoParam.LEFT) { + xMin = constraint; + } else if (param == GeoParam.RIGHT) { + xMax = constraint; + } else if (param == WIDTH) { + xSize = constraint; + } + xAxis = AxisConfig.getConfigFor(xMin, xMax, xSize); + validate(); + } + + private void constrainY(GeoParam param, @Nullable Constraint constraint) { + if (param == GeoParam.TOP) { + yMin = constraint; + } else if (param == GeoParam.BOTTOM) { + yMax = constraint; + } else if (param == GeoParam.HEIGHT) { + ySize = constraint; + } + yAxis = AxisConfig.getConfigFor(yMin, yMax, ySize); + validate(); + } + + /** + * Strict mode is intended to help catch potential mistakes when writing modular GUIs + *

+ * Enforces a strict requirement for each exist to have two and only two constraints. + * Any attempt to over-constrain an axis will throw an immediate fatal exception. + * If an axis is under-constrained then a fatal exception will be thrown when a value from the axis is queried. + *

+ * Strict mode applies to this element, and recursively to all children of this element. + * + * @param strictMode Enable strict mode. + * @return the geometry object. + */ + @SuppressWarnings ("unchecked") + public T strictMode(boolean strictMode) { + this.strictMode = strictMode; + //TODO Propagate to children (Will be handled in the base GuiElement) + return (T) this; + } + + //TODO This needs to be called from the parent element somewhere. Possibly on tick or render + //Ideally i would like to find a way to only call it once. we need to account for constraints being modified after initial element construction. + public void validate() { + if (strictMode) { + if (xAxis.constraints != 2) { + throw new IllegalStateException(String.format("X axis of element: %s is %s constrained!", getParent(), xAxis.constraints < 2 ? "under" : "over")); + } else if (yAxis.constraints != 2) { + throw new IllegalStateException(String.format("Y axis of element: %s is %s constrained!", getParent(), yAxis.constraints < 2 ? "under" : "over")); + } + } + } + + public void clearGeometryCache() { + if (xMin != null) xMin.markDirty(); + if (xMax != null) xMax.markDirty(); + if (xSize != null) xSize.markDirty(); + if (yMin != null) yMin.markDirty(); + if (yMax != null) yMax.markDirty(); + if (ySize != null) ySize.markDirty(); + getChildren().forEach(ConstrainedGeometry::clearGeometryCache); + } + + //=== Geometry Utilities ===// + + /** + * Returns a {@link Position} that is permanently bound to this element. + */ + public Position getPosition() { + return position; + } + + /** + * Returns a {@link Rectangle} that is permanently bound to this element. + */ + public Rectangle getRectangle() { + return rectangle; + } + + public double xCenter() { + return xMin() + (xSize() / 2); + } + + public double yCenter() { + return yMin() + (ySize() / 2); + } + + /** + * Returns a new {@link Rectangle} the bounds of which will enclose this element and all of its child + * elements recursively. + */ + public Rectangle.Mutable getEnclosingRect() { + return addBoundsToRect(getRectangle().mutable()); + } + + /** + * Expands the bounds of the given rectangle (if needed) so that they enclose this element. + * And all of its child elements recursively. + */ + public Rectangle.Mutable addBoundsToRect(Rectangle.Mutable enclosingRect) { + enclosingRect.combine(getRectangle()); + for (GuiElement element : getChildren()) { + if (element.isEnabled()) { + element.addBoundsToRect(enclosingRect); + } + } + return enclosingRect; + } + + /** + * @return a rectangle, the bounds of which enclose all enabled child elements. + * If there are no enabled child elements the returned rect will have the position of this element, with zero size. + */ + public Rectangle.Mutable getChildBounds() { + boolean set = false; + for (GuiElement element : getChildren()) { + if (element.isEnabled()) { + if (!set) { + childBounds.set(element.getRectangle()); + set = true; + } else { + element.addBoundsToRect(childBounds); + } + } + } + if (!set) childBounds.setPos(xMin(), yMin()).setSize(0, 0); + return childBounds; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java new file mode 100644 index 00000000..63d80344 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java @@ -0,0 +1,154 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * Constraints are used to define an elements position and shape by constraining the elements geometry parameters. {@link GeoParam} + * Constraints can be as simple as literal values representing an elements exact position and / or size in screen space, + * They can be relative coordinates, (Relative to another element's Geometry) + * Or they can be used to supply completely custom dynamic values. + *

+ * All the built-in constraints are implemented and documented in this class. + *

+ * Created by brandon3055 on 30/06/2023 + * + * @see ConstrainedGeometry + */ +public sealed interface Constraint permits ConstraintImpl { + + /** + * This method will return the current value of this constraint. + * This could be a fixed stored value, or a dynamically computed value + * depending on the type of constraint. + *

+ * All position and size values in ModularGui are doubles. + * However, by default, all the builtin constraints will cast their outputs to integer values. + * This avoids a lot of random visual artifacts that can occur when using floating point values in MC Screens. + *

+ * If you need floating-point precision, it can be enabled calling .precise() on any of the builtin constraints. + * + * @return The computed or stored value of this constraint. + */ + double get(); + + /** + * @return the axis this constraint applies to, Ether X, Y or null for undefined. + */ + @Nullable + Axis axis(); + + /** + * This is part of a late addition to improve performance. + * Rather than computing a constraint value every single time it is queried, which can be many, many times per render frame, + * We now cache the constraint value, and that cache is cleared at the start of each render frame. + */ + void markDirty(); + + /** + * This is the most basic constraint. It constrains a parameter to a single fixed value. + * + * @param value The fixed value that will be returned by this constraint. + */ + static ConstraintImpl.Literal literal(double value) { + return new ConstraintImpl.Literal(value); + } + + /** + * Constrains a parameter to the value provided by the given supplier. + * + * @param valueSupplier The dynamic value supplier. + */ + static ConstraintImpl.Dynamic dynamic(Supplier valueSupplier) { + return new ConstraintImpl.Dynamic(valueSupplier); + } + + /** + * Contains a parameter to the exact value of the given reference. + * This is effectively a relative constraint with no offset. + * + * @param relativeTo The relative geometry. + */ + static ConstraintImpl.Relative match(GeoRef relativeTo) { + return new ConstraintImpl.Relative(relativeTo, 0); + } + + /** + * Contains a parameter to the given reference plus the provided fixed offset. + * + * @param relativeTo The relative geometry. + * @param offset The offset to apply. + */ + static ConstraintImpl.Relative relative(GeoRef relativeTo, double offset) { + return new ConstraintImpl.Relative(relativeTo, offset); + } + + /** + * Contains a parameter to the given reference plus the provided dynamic offset. + * + * @param relativeTo The relative geometry. + * @param offset The dynamic offset to apply. + */ + static ConstraintImpl.RelativeDynamic relative(GeoRef relativeTo, Supplier offset) { + return new ConstraintImpl.RelativeDynamic(relativeTo, offset); + } + + /** + * Contains a parameter to a fixed position between the two provided references. + * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. + * To prevent this call .clamp() on the returned constraint. + * + * @param start The Start position. + * @param end The End position. + * @param position The position between start and end. (0=start to 1=end) + */ + static ConstraintImpl.Between between(GeoRef start, GeoRef end, double position) { + return new ConstraintImpl.Between(start, end, position); + } + + /** + * Contains a parameter to a dynamic position between the two provided references. + * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. + * To prevent this call .clamp() on the returned constraint. + * + * @param start The Start position. + * @param end The End position. + * @param position The dynamic position between start and end. (0=start to 1=end) + */ + static ConstraintImpl.BetweenDynamic between(GeoRef start, GeoRef end, Supplier position) { + return new ConstraintImpl.BetweenDynamic(start, end, position); + } + + /** + * Contains a parameter to the mid-point between the two provided references. + * + * @param start The Start position. + * @param end The End position. + */ + static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end) { + return new ConstraintImpl.MidPoint(start, end, 0); + } + + /** + * Contains a parameter to the mid-point between the two provided references with a fixed offset. + * + * @param start The Start position. + * @param end The End position. + * @param offset offset distance. + */ + static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end, double offset) { + return new ConstraintImpl.MidPoint(start, end, offset); + } + + /** + * Contains a parameter to the mid-point between the two provided references with a dynamic offset. + * + * @param start The Start position. + * @param end The End position. + * @param offset offset distance suppler. + */ + static ConstraintImpl.MidPointDynamic midPoint(GeoRef start, GeoRef end, Supplier offset) { + return new ConstraintImpl.MidPointDynamic(start, end, offset); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java new file mode 100644 index 00000000..646abe93 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java @@ -0,0 +1,294 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import net.minecraft.util.Mth; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 04/07/2023 + */ +public abstract non-sealed class ConstraintImpl> implements Constraint { + + protected boolean precise = false; + protected Axis axis = null; + private double value; + private boolean isDirty = true; + + /** + * @return True if precise mode is enabled. + * @see #precise() + */ + public boolean isPrecise() { + return precise; + } + + /** + * By default, all constraint values are cast to (int). + * This helps avoid a lot of visual artifacts that can occur when using floating point positions in MC Screens. + *

+ * Calling this enables precise mode, which allows floating point precision to be used. + * + * @return The Constraint. + */ + @SuppressWarnings("unchecked") + public T precise() { + this.precise = true; + return (T) this; + } + + @Override + public double get() { + if (isDirty) { + value = isPrecise() ? getImpl() : (int) getImpl(); + isDirty = false; + } + return value; + } + + @Override + public @Nullable Axis axis() { + return axis; + } + + @SuppressWarnings("unchecked") + public T setAxis(@Nullable Axis axis) { + this.axis = axis; + return (T) this; + } + + @Override + public void markDirty() { + isDirty = true; + } + + protected abstract double getImpl(); + + public static class Literal extends ConstraintImpl { + protected final double value; + + /** + * Returns the literal value supplied. + */ + public Literal(double value) { + this.value = value; + } + + @Override + protected double getImpl() { + return value; + } + } + + public static class Dynamic extends ConstraintImpl { + protected final Supplier value; + + /** + * Returns a dynamic value that will be retrieved from the provided supplier. + */ + public Dynamic(Supplier value) { + this.value = value; + } + + @Override + protected double getImpl() { + return value.get(); + } + } + + public static class Relative extends ConstraintImpl { + protected final GeoRef relTo; + protected final double offset; + + /** + * Returns the value of the provided reference plus the given offset. + */ + public Relative(GeoRef relTo, double offset) { + this.setAxis(relTo.parameter.axis); + this.relTo = relTo; + this.offset = offset; + } + + @Override + protected double getImpl() { + return relTo.get() + getOffset(); + } + + public double getOffset() { + return offset; + } + } + + public static class RelativeDynamic extends ConstraintImpl { + protected final GeoRef relTo; + protected final Supplier offset; + + /** + * Returns the value of the provided reference plus the given dynamic offset. + */ + public RelativeDynamic(GeoRef relTo, Supplier offset) { + this.setAxis(relTo.parameter.axis); + this.relTo = relTo; + this.offset = offset; + } + + @Override + protected double getImpl() { + return relTo.get() + getOffset(); + } + + public double getOffset() { + return offset.get(); + } + } + + public static class Between extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final double pos; + protected boolean clamp = false; + + public Between(GeoRef start, GeoRef end, double pos) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'Between' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.pos = pos; + } + + @Override + protected double getImpl() { + return start.get() + (end.get() - start.get()) * getPos(); + } + + public double getPos() { + return clamp ? Mth.clamp(pos, 0, 1) : pos; + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + + /** + * Ensure the output can not go bellow the min reference or above the max reference. + */ + public Between clamp() { + this.clamp = true; + return this; + } + } + + public static class BetweenDynamic extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final Supplier pos; + protected boolean clamp = false; + + public BetweenDynamic(GeoRef start, GeoRef end, Supplier pos) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'Between' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.pos = pos; + } + + @Override + protected double getImpl() { + return start.get() + (end.get() - start.get()) * getPos(); + } + + public double getPos() { + return clamp ? Mth.clamp(pos.get(), 0, 1) : pos.get(); + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + + /** + * Ensure the output can not go bellow the min reference or above the max reference. + */ + public BetweenDynamic clamp() { + this.clamp = true; + return this; + } + } + + public static class MidPoint extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final double offset; + + public MidPoint(GeoRef start, GeoRef end, double offset) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'MidPoint' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.offset = offset; + } + + @Override + protected double getImpl() { + return start.get() + ((end.get() - start.get()) / 2) + getOffset(); + } + + public double getOffset() { + return offset; + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + } + + public static class MidPointDynamic extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final Supplier offset; + + public MidPointDynamic(GeoRef start, GeoRef end, Supplier offset) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'MidPoint' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.offset = offset; + } + + @Override + protected double getImpl() { + return start.get() + ((end.get() - start.get()) / 2) + getOffset(); + } + + public double getOffset() { + return offset.get(); + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Direction.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Direction.java new file mode 100644 index 00000000..9e2513e8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Direction.java @@ -0,0 +1,40 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Created by brandon3055 on 04/09/2023 + */ +public enum Direction { + UP(Axis.Y), + LEFT(Axis.X), + DOWN(Axis.Y), + RIGHT(Axis.X); + + private static Direction[] VALUES = values(); + + private final Axis axis; + + Direction(Axis axis) { + this.axis = axis; + } + + public Axis getAxis() { + return axis; + } + + public Direction opposite() { + if (axis == Axis.X) return this == LEFT ? RIGHT : LEFT; + else return this == UP ? DOWN : UP; + } + + public Direction rotateCW() { + return values()[(ordinal() + VALUES.length - 1) % VALUES.length]; + } + + public Direction rotateCCW() { + return values()[(ordinal() + 1) % VALUES.length]; + } + + public double rotationTo(Direction other) { + return (this.ordinal() - other.ordinal()) * 90; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoParam.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoParam.java new file mode 100644 index 00000000..0f37720f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoParam.java @@ -0,0 +1,32 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Used to define the 6 core parameters that make up an elements geometry + * These are named Left, Right, Width, Top, Bottom, Height. + * These names were chosen for ease of use, and to make it clear what they represent. + * Internally they are known as xMin, xMax, xSize, yMin, yMax, ySize. + *

+ * Created by brandon3055 on 30/06/2023 + */ +public enum GeoParam { + /** X_MIN */ + LEFT(Axis.X), + /** X_MAX */ + RIGHT(Axis.X), + /** X_SIZE */ + WIDTH(Axis.X), + + /** Y_MIN */ + TOP(Axis.Y), + /** Y_MAX */ + BOTTOM(Axis.Y), + /** Y_SIZE */ + HEIGHT(Axis.Y); + + public final Axis axis; + + GeoParam(Axis axis) { + this.axis = axis; + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoRef.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoRef.java new file mode 100644 index 00000000..93ebf68e --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoRef.java @@ -0,0 +1,36 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import java.util.function.Supplier; + +/** + * Used to access one of the 6 core parameters that make up an element's geometry. + *

+ * The primary purpose of this class is to provide a convenient way to reference a geometry + * parameter when defining constraints. + * It also helps make the code more debuggable. + * I could just make literally everything a lambda, but that makes debugging kinda painful when things break. + *

+ * Created by brandon3055 on 30/06/2023 + */ +public class GeoRef implements Supplier { + public final GuiParent geometry; + public final GeoParam parameter; + + public GeoRef(GuiParent geometry, GeoParam parameter) { + this.geometry = geometry; + this.parameter = parameter; + } + + @Override + public Double get() { + return geometry.getValue(parameter); + } + + @Override + public String toString() { + return "GeoReference{" + + "geometry=" + geometry + + ", parameter=" + parameter + + '}'; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/GuiParent.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GuiParent.java new file mode 100644 index 00000000..9a2b8d77 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GuiParent.java @@ -0,0 +1,190 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.elements.GuiElement; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import org.jetbrains.annotations.ApiStatus; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This is the base interface that allows an element or screen to define its basic geometry. + * As well as defining the primary methods for handling child elements. + *

+ * It also provides a way to access some common minecraft fields. + *

+ * Created by brandon3055 on 29/06/2023 + */ +public interface GuiParent> { + + /** + * @return The position of the Left edge of this element. + */ + double xMin(); + + /** + * @return The position of the Right edge of this element. + */ + double xMax(); + + /** + * @return The Width of this element. + */ + double xSize(); + + /** + * @return The position of the Top edge of this element. + */ + double yMin(); + + /** + * @return The position of the Bottom edge of this element. + */ + double yMax(); + + /** + * @return The Height of this element. + */ + double ySize(); + + /** + * Returns a reference to the specified geometry parameter. + * This is primarily used when defining geometry constraints. + * But it can also be used as a simple {@link Supplier} + * that will return the current parameter value when requested. + *

+ * Note: The returned geometry reference will always be valid + * + * @param param The geometry parameter. + * @return A Geometry Reference + */ + default GeoRef get(GeoParam param) { + return new GeoRef(this, param); + } + + /** + * @param param The geometry parameter. + * @return The current value of the specified parameter. + */ + default double getValue(GeoParam param) { + return switch (param) { + case LEFT -> xMin(); + case RIGHT -> xMax(); + case WIDTH -> xSize(); + case TOP -> yMin(); + case BOTTOM -> yMax(); + case HEIGHT -> ySize(); + }; + } + + /** + * @return An unmodifiable list of all assigned child elements assigned to this parent. The list should be sorted in the order they were added. + */ + List> getChildren(); + + /** + * Adds a new child element to this parent. + * You should almost never need to use this because this is handled automatically when an element is created. + *

+ * Note: Due to the way relative coordinates work with the new geometry system, + * Transferring an element to a different parent can have unpredictable results. + * Therefor, to help avoid confusion it is not possible to transfer a child to a new parent using this method. + * + * @param child The child element to be added. + * @throws UnsupportedOperationException - If child has previously been assigned to a different parent. + * @see #adoptChild(GuiElement) + */ + void addChild(GuiElement child); + + /** + * This meant to be a convenience method that allows builder style addition of a child element. + * I'm not sure how useful it will be yet, so it may or may not stay. + * + * @param createChild A consumer that is given this element to be used in the construction of the child element. + * @return The parent element + */ + @ApiStatus.Experimental + @SuppressWarnings ("unchecked") + default T addChild(Consumer createChild) { + createChild.accept((T) this); + return (T) this; + } + + /** + * This method can be used to transfer an already initialized child to this parent element. + * This automatically handles removing the element from its previous parent, adds it to this element. + * Note: This will most likely break any relative constraints on the child's geometry. + * To fix this you will need to re-apply geometry constraints after the transfer. + * + * @param child The child element to be adopted. + */ + void adoptChild(GuiElement child); + + /** + * Allows the removal of a child element. + * Child removal is not instantaneous, Instead all removals occur at the end of the current screen thick. + * This is to avoid any possible concurrency issues. + * + * @param child The child element to be removed. + */ + void removeChild(GuiElement child); + + /** + * Checks if this element is a descendant of the specified. + * @return true if the specified element is a parent or grandparent etc... of this element. + */ + default boolean isDescendantOf(GuiElement ancestor) { + return false; + } + + /** + * @return The minecraft instance. + */ + Minecraft mc(); + + /** + * @return The active font instance. + */ + Font font(); + + /** + * @return The current gui screen width, As returned by mc.getWindow().getGuiScaledWidth() + */ + int scaledScreenWidth(); + + /** + * @return The current gui screen height, As returned by mc.getWindow().getGuiScaledHeight() + */ + int scaledScreenHeight(); + + /** + * @return the parent ModularGui instance. + */ + ModularGui getModularGui(); + + /** + * Called when the minecraft Screen is initialised or resized. + * + * @param mc The Minecraft instance. + * @param font The active font. + * @param screenWidth The current guiScaledWidth. + * @param screenHeight The current guiScaledHeight. + */ + default void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + getChildren().forEach(e -> e.onScreenInit(mc, font, screenWidth, screenHeight)); + } + + /** + * Allows an element to override the {@link GuiElement#isMouseOver()} method of its children. + * This is primarily used for things like scroll elements where mouseover interactions need to be blocked outside the view area. + * + * @param element The element on which isMouseOver is getting called. + * @return true if mouse-over interaction should be blocked for this child element. + */ + default boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return false; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Position.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Position.java new file mode 100644 index 00000000..df430507 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Position.java @@ -0,0 +1,103 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 24/08/2023 + */ +public interface Position { + + double x(); + + double y(); + + default Position offset(double x, double y) { + return create(x() + x, y() + y); + } + + /** + * Returns the position value for the given axis. + */ + default double get(Axis axis) { + return axis == Axis.X ? x() : y(); + } + + static Position create(double x, double y) { + return new Immutable(x, y); + } + + static Position create(Supplier getX, Supplier getY) { + return new Dynamic(getX, getY); + } + + /** + * Creates a new position, bound to the specified parent's position. + * */ + static Position create(GuiParent parent) { + return new Dynamic(parent::xMin, parent::yMin); + } + + record Immutable(@Override double x, @Override double y) implements Position { } + + record Dynamic(Supplier getX, Supplier getY) implements Position { + @Override + public double x() { + return getX.get(); + } + + @Override + public double y() { + return getY.get(); + } + + @Override + public String toString() { + return "Dynamic{" + + "x=" + x() + + ", y=" + y() + + '}'; + } + } + + static class Mutable implements Position { + private double x; + private double y; + + public Mutable(double x, double y) { + this.x = x; + this.y = y; + } + + @Override + public double x() { + return x; + } + + @Override + public double y() { + return y; + } + + @Override + public Position offset(double x, double y) { + this.x += x; + this.y += y; + return this; + } + + public Position set(double x, double y) { + this.x = x; + this.y = y; + return this; + } + + @Override + public String toString() { + return "Mutable{" + + "x=" + x() + + ", y=" + y() + + '}'; + } + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java new file mode 100644 index 00000000..4ad613f7 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java @@ -0,0 +1,308 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import net.minecraft.client.renderer.Rect2i; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 14/08/2023 + */ +public interface Rectangle { + + Position pos(); + + default double x() { + return pos().x(); + } + + default double y() { + return pos().y(); + } + + double width(); + + double height(); + + default double xMax() { + return x() + width(); + } + + default double yMax() { + return y() + height(); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle offsetPos(double xAmount, double yAmount) { + return create(x() + xAmount, y() + yAmount, width(), height()); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle setPos(double newX, double newY) { + return create(newX, newY, width(), height()); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle setSize(double width, double height) { + return create(x(), y(), width, height); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle offsetSize(double xAmount, double yAmount) { + return create(x(), y(), width() + xAmount, height() + yAmount); + } + + default Rect2i toRect2i() { + return new Rect2i((int) x(), (int) y(), (int) width(), (int) height()); + } + + default boolean intersects(double x, double y, double w, double h) { + double x0 = x(); + double y0 = y(); + return (x + w > x0 && y + h > y0 && x < x0 + width() && y < y0 + height()); + } + + default boolean intersects(Rectangle other) { + double x0 = x(); + double y0 = y(); + return (other.x() + other.width() > x0 && other.y() + other.height() > y0 && other.x() < x0 + width() && other.y() < y0 + height()); + } + + /** + * Returns a new rectangle that represents the intersection area between the two inputs + */ + default Rectangle intersect(Rectangle other) { + double x = Math.max(x(), other.x()); + double y = Math.max(y(), other.y()); + double width = Math.max(0, Math.min(xMax(), other.xMax()) - x()); + double height = Math.max(0, Math.min(yMax(), other.yMax()) - y()); + return create(x, y, width, height); + } + + /** + * Returns a new rectangle, the bounds of which enclose all the input rectangles. + * + * @param combineWith Rectangles to combine with the start rectangle + */ + default Rectangle combine(Rectangle... combineWith) { + double x = x(); + double y = y(); + double maxX = xMax(); + double maxY = yMax(); + for (Rectangle other : combineWith) { + x = Math.min(x, other.x()); + y = Math.min(y, other.y()); + maxX = Math.max(maxX, other.xMax()); + maxY = Math.max(maxY, other.yMax()); + } + return create(x, y, maxX - x, maxY - y); + } + + default boolean contains(double x, double y) { + return x >= x() && x <= x() + width() && y >= y() && y <= y() + height(); + } + + /** + * @return the size of this rectangle on the given axis. + */ + default double size(Axis axis) { + return axis == Axis.X ? width() : height(); + } + + /** + * @return the min value the specified axis (meaning x() or y()) + */ + default double min(Axis axis) { + return axis == Axis.X ? x() : y(); + } + + /** + * @return the max value the specified axis (meaning x() + width() or y() + height()) + */ + default double max(Axis axis) { + return axis == Axis.X ? xMax() : yMax(); + } + + /** + * Return the distance the given position is from this rectangle on the specified axis. + * Will return 0 if position is inside this rectangle on the given axis. + */ + default double distance(Axis axis, Position position) { + double pos = position.get(axis); + double min = min(axis); + double max = max(axis); + return pos < min ? min - pos : pos > max ? pos - max : 0; + } + + static Rectangle create(Position position, double width, double height) { + return new Immutable(position, width, height); + } + + static Rectangle create(double x, double y, double width, double height) { + return new Immutable(Position.create(x, y), width, height); + } + + /** + * Returns a new rectangle bound to the specified parent's geometry. + */ + static Rectangle create(GuiParent parent) { + return new Dynamic(Position.create(parent), parent::xSize, parent::ySize); + } + + static Rectangle create(Position position, Supplier getWidth, Supplier getHeight) { + return new Dynamic(position, getWidth, getHeight); + } + + default Mutable mutable() { + return new Mutable(new Position.Mutable(x(), y()), width(), height()); + } + + /** + * Should not be created directly + */ + record Immutable(Position position, double xSize, double ySize) implements Rectangle { + @Override + public Position pos() { + return position; + } + + @Override + public double width() { + return xSize; + } + + @Override + public double height() { + return ySize; + } + + @Override + public String toString() { + return "Immutable{" + + "pos=" + pos() + + ", width=" + width() + + ", height=" + height() + + '}'; + } + } + + record Dynamic(Position position, Supplier getWidth, Supplier getHeight) implements Rectangle { + @Override + public Position pos() { + return position; + } + + @Override + public double width() { + return getWidth.get(); + } + + @Override + public double height() { + return getHeight.get(); + } + + @Override + public String toString() { + return "Dynamic{" + + "pos=" + pos() + + ", width=" + width() + + ", height=" + height() + + '}'; + } + } + + class Mutable implements Rectangle { + private Position.Mutable pos; + private double width; + private double height; + + public Mutable(Position.Mutable pos, double width, double height) { + this.pos = pos; + this.width = width; + this.height = height; + } + + @Override + public Position pos() { + return pos; + } + + @Override + public double width() { + return width; + } + + @Override + public double height() { + return height; + } + + @Override + public Rectangle offsetPos(double xAmount, double yAmount) { + pos.offset(xAmount, yAmount); + return this; + } + + @Override + public Rectangle setPos(double newX, double newY) { + pos.set(newX, newY); + return this; + } + + @Override + public Rectangle setSize(double width, double height) { + this.width = width; + this.height = height; + return this; + } + + @Override + public Rectangle offsetSize(double xAmount, double yAmount) { + this.width += xAmount; + this.height += yAmount; + return this; + } + + @Override + public Rectangle intersect(Rectangle other) { + double x = Math.max(x(), other.x()); + double y = Math.max(y(), other.y()); + width = Math.max(0, Math.min(xMax(), other.xMax()) - x()); + height = Math.max(0, Math.min(yMax(), other.yMax()) - y()); + return setPos(x, y); + } + + public void set(Rectangle rectangle) { + this.pos.set(rectangle.x(), rectangle.y()); + this.width = rectangle.width(); + this.height = rectangle.height(); + } + + @Override + public Rectangle combine(Rectangle... combineWith) { + double x = x(); + double y = y(); + double maxX = xMax(); + double maxY = yMax(); + for (Rectangle other : combineWith) { + x = Math.min(x, other.x()); + y = Math.min(y, other.y()); + maxX = Math.max(maxX, other.xMax()); + maxY = Math.max(maxY, other.yMax()); + } + return setPos(x, y).setSize(maxX - x, maxY - y); + } + + public Immutable immutable() { + return new Immutable(Position.create(x(), y()), width(), height()); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java b/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java new file mode 100644 index 00000000..a3aaf28d --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java @@ -0,0 +1,59 @@ +package codechicken.lib.gui.modular.sprite; + +import codechicken.lib.CodeChickenLib; +import net.minecraft.resources.ResourceLocation; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +/** + * Gui texture handler implementation. + * This sets up a custom atlas that will be populated with all textures in "modid:textures/gui/" + * To use your own textures you can just create a carbon copy of this class with that uses your own modid. + *

+ * Created by brandon3055 on 21/10/2023 + */ +public class CCGuiTextures { + private static final ModAtlasHolder ATLAS_HOLDER = new ModAtlasHolder(CodeChickenLib.MOD_ID, "textures/atlas/gui.png", "gui"); + private static final Map MATERIAL_CACHE = new HashMap<>(); + + /** + * The returned AtlasLoader needs to be registered as a resource reload listener using the appropriate NeoForge / Fabric event. + */ + public static ModAtlasHolder getAtlasHolder() { + return ATLAS_HOLDER; + } + + /** + * Returns a cached Material for the specified gui texture. + * Warning: Do not use this if you intend to use the material with multiple render types. + * The material will cache the first render type it is used with. + * Instead use {@link #getUncached(String)} + * + * @param texture The texture path relative to "modid:gui/" + */ + public static Material get(String texture) { + return MATERIAL_CACHE.computeIfAbsent(CodeChickenLib.MOD_ID + ":" + texture, e -> getUncached(texture)); + } + + public static Material get(Supplier texture) { + return get(texture.get()); + } + + public static Supplier getter(Supplier texture) { + return () -> get(texture.get()); + } + + /** + * Use this to retrieve a new uncached material for the specified gui texture. + * Feel free to hold onto the returned material. + * Storing it somewhere is more efficient than recreating it every render frame. + * + * @param texture The texture path relative to "modid:gui/" + * @return A new Material for the specified gui texture. + */ + public static Material getUncached(String texture) { + return new Material(ATLAS_HOLDER.atlasLocation(), new ResourceLocation(CodeChickenLib.MOD_ID, "gui/" + texture), ATLAS_HOLDER::getSprite); + } +} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/Material.java b/src/main/java/codechicken/lib/gui/modular/sprite/Material.java new file mode 100644 index 00000000..888b45b3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/sprite/Material.java @@ -0,0 +1,126 @@ +package codechicken.lib.gui.modular.sprite; + +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection; +import net.minecraft.client.resources.metadata.animation.FrameSize; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Function; + +/** + * This is similar to Minecraft's {@link net.minecraft.client.resources.model.Material} + * This contains the essential data required to render an atlas sprite. + *

+ * The primary purpose of this class is to make porting between MC versions easier. + * It also allows for loading sprites from a custom texture atlas. Minecraft's material class can only load from vanilla atlases. + *

+ * Created by brandon3055 on 20/08/2023 + */ +public class Material { + private final ResourceLocation atlasLocation; + private final ResourceLocation texture; + private final Function spriteFunction; + + @Nullable + private RenderType renderType; + @Nullable + private net.minecraft.client.resources.model.Material vanillaMat; + + public Material(ResourceLocation atlasLocation, ResourceLocation texture, Function spriteFunction) { + this.atlasLocation = atlasLocation; + this.texture = texture; + this.spriteFunction = spriteFunction; + } + + public ResourceLocation atlasLocation() { + return atlasLocation; + } + + public ResourceLocation texture() { + return texture; + } + + public TextureAtlasSprite sprite() { + return spriteFunction.apply(texture()); + } + + /** + * Returns the cached render type for this material. + * The supplied function will be used to create the render type the first time this method is called. + * + * @param typeBuilder a function that will be used to create the render type if it does not already exist. + * @return The render type for this material. + */ + public RenderType renderType(Function typeBuilder) { + if (this.renderType == null) { + this.renderType = typeBuilder.apply(atlasLocation()); + } + return this.renderType; + } + + /** + * Convenience method to create a vertex consumer using this materials render type. + * + * @param buffers bugger source. + * @param typeBuilder a function that will be used to create the render type if it does not already exist. + */ + public VertexConsumer buffer(MultiBufferSource buffers, Function typeBuilder) { + return buffers.getBuffer(renderType(typeBuilder)); + } + + public net.minecraft.client.resources.model.Material getVanillaMat() { + if (vanillaMat == null) { + vanillaMat = new net.minecraft.client.resources.model.Material(atlasLocation, texture); + } + return vanillaMat; + } + + /** + * Convenient method for getting a material from a vanilla texture atlas. + * + * @return an un-cached material from a vanilla atlas. + */ + public static Material fromAtlas(ResourceLocation atlasLocation, String texture) { + return new Material(atlasLocation, new ResourceLocation(atlasLocation.getNamespace(), texture), e -> Minecraft.getInstance().getTextureAtlas(atlasLocation).apply(e)); + } + + /** + * Create a material from an existing sprite. + * Note: This will only work with sprites from a vanilla atlas. + */ + @Nullable + public static Material fromSprite(@Nullable TextureAtlasSprite sprite) { + if (sprite == null) return null; + return new Material(sprite.atlasLocation(), sprite.contents().name(), e -> Minecraft.getInstance().getTextureAtlas(sprite.atlasLocation()).apply(e)); + } + + public static Material fromRawTexture(ResourceLocation texture) { + return new Material(texture, texture, FullSprite::new); + } + + private static class FullSprite extends TextureAtlasSprite { + private FullSprite(ResourceLocation location) { + super(location, new SpriteContents(location, new FrameSize(1, 1), new NativeImage(1, 1, false), AnimationMetadataSection.EMPTY), 1, 1, 0, 0); + } + + @Override + public float getU(double u) + { + return (float) u / 16; + } + + @Override + public float getV(double v) + { + return (float) v / 16; + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java new file mode 100644 index 00000000..9d361894 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java @@ -0,0 +1,101 @@ +package codechicken.lib.gui.modular.sprite; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.SpriteLoader; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.PackResources; +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.util.profiling.ProfilerFiller; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * Created by brandon3055 on 20/08/2023 + */ +public class ModAtlasHolder implements PreparableReloadListener, AutoCloseable { + private final TextureAtlas textureAtlas; + private final ResourceLocation atlasLocation; + private final ResourceLocation atlasInfoLocation; + private final String modid; + + /** + * Defines a mod texture atlas. + * Must be registered as a resource reload listener via RegisterClientReloadListenersEvent + * This is all that is needed to create a custom texture atlas. + * + * @param modid The mod id of the mod registering this atlas. + * @param atlasLocation The texture atlas location. e.g. "textures/atlas/gui.png" (Will have the modid: prefix added automatically) + * @param atlasInfoLocation The path to the atlas json file relative to modid:atlases/ + * e.g. "gui" will point to modid:atlases/gui.json + */ + public ModAtlasHolder(String modid, String atlasLocation, String atlasInfoLocation) { + this.atlasInfoLocation = new ResourceLocation(modid, atlasInfoLocation); + this.atlasLocation = new ResourceLocation(modid, atlasLocation); + this.textureAtlas = new TextureAtlas(this.atlasLocation); + this.modid = modid; + Minecraft.getInstance().getTextureManager().register(this.textureAtlas.location(), this.textureAtlas); + } + + public ResourceLocation atlasLocation() { + return atlasLocation; + } + + public TextureAtlasSprite getSprite(ResourceLocation resourceLocation) { + return this.textureAtlas.getSprite(resourceLocation); + } + + @Override + public final @NotNull CompletableFuture reload(PreparationBarrier prepBarrier, ResourceManager resourceManager, ProfilerFiller profiler, ProfilerFiller profiler2, Executor executor, Executor executor2) { + Objects.requireNonNull(prepBarrier); + SpriteLoader spriteLoader = SpriteLoader.create(this.textureAtlas); + return spriteLoader.loadAndStitch(new ModResourceManager(resourceManager, modid), this.atlasInfoLocation, 0, executor) + .thenCompose(SpriteLoader.Preparations::waitForUpload) + .thenCompose(prepBarrier::wait) + .thenAcceptAsync((preparations) -> this.apply(preparations, profiler2), executor2); + } + + private void apply(SpriteLoader.Preparations preparations, ProfilerFiller profilerFiller) { + profilerFiller.startTick(); + profilerFiller.push("upload"); + this.textureAtlas.upload(preparations); + profilerFiller.pop(); + profilerFiller.endTick(); + } + + @Override + public void close() { + this.textureAtlas.clearTextureData(); + } + + public static class ModResourceManager implements ResourceManager { + private final ResourceManager wrapped; + private final String modid; + + public ModResourceManager(ResourceManager wrapped, String modid) { + this.wrapped = wrapped; + this.modid = modid; + } + + @Override + public Map listResources(String pPath, Predicate pFilter) { + return wrapped.listResources(pPath, pFilter.and(e -> e.getNamespace().equals(modid))); + } + + //@formatter:off + @Override public Set getNamespaces() { return wrapped.getNamespaces(); } + @Override public List getResourceStack(ResourceLocation pLocation) { return wrapped.getResourceStack(pLocation); } + @Override public Map> listResourceStacks(String pPath, Predicate pFilter) { return wrapped.listResourceStacks(pPath, pFilter); } + @Override public Stream listPacks() { return wrapped.listPacks(); } + @Override public Optional getResource(ResourceLocation pLocation) { return wrapped.getResource(pLocation); } + //@formatter:on + } +} diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java index a0186ba8..1e1eb056 100644 --- a/src/main/java/codechicken/lib/internal/ClientInit.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -3,13 +3,19 @@ import codechicken.lib.CodeChickenLib; import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.gui.modular.lib.CursorHelper; +import codechicken.lib.gui.modular.sprite.CCGuiTextures; import codechicken.lib.model.CompositeItemModel; import codechicken.lib.model.ClassModelLoader; import codechicken.lib.render.CCRenderEventHandler; import codechicken.lib.render.block.BlockRenderingRegistry; import net.covers1624.quack.util.CrashLock; +import net.minecraft.client.Minecraft; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.ResourceManagerReloadListener; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.client.event.ModelEvent; +import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @@ -36,6 +42,7 @@ public static void init() { bus.addListener(ClientInit::onClientSetup); bus.addListener(ClientInit::onRegisterGeometryLoaders); + bus.addListener(ClientInit::onResourceReload); } private static void onClientSetup(FMLClientSetupEvent event) { @@ -74,4 +81,9 @@ private static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event.register("item_composite", new CompositeItemModel()); event.register("class", new ClassModelLoader()); } + + public static void onResourceReload(RegisterClientReloadListenersEvent event) { + event.registerReloadListener(CCGuiTextures.getAtlasHolder()); + event.registerReloadListener((ResourceManagerReloadListener) e -> CursorHelper.onResourceReload()); + } } diff --git a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java index 99b73ea5..5655ef14 100644 --- a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java +++ b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java @@ -15,6 +15,10 @@ public class CCLNetwork { //Client handled. public static final int C_ADD_LANDING_EFFECTS = 1; public static final int C_OPEN_CONTAINER = 10; + public static final int C_GUI_SYNC = 20; + + //Server handled. + public static final int S_GUI_SYNC = 20; //Login handled. public static final int L_CONFIG_SYNC = 1; @@ -22,8 +26,8 @@ public class CCLNetwork { public static void init() { netChannel = PacketCustomChannelBuilder.named(NET_CHANNEL)// .assignClientHandler(() -> ClientPacketHandler::new)// + .assignServerHandler(() -> ServerPacketHandler::new)// .assignLoginHandler(() -> LoginPacketHandler::new)// .build(); } - } diff --git a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java index 8f7dd554..32bccf89 100644 --- a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java +++ b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java @@ -1,6 +1,7 @@ package codechicken.lib.internal.network; import codechicken.lib.inventory.container.ICCLContainerType; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; import codechicken.lib.packet.PacketCustom; import codechicken.lib.render.particle.CustomParticleHandler; @@ -17,8 +18,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.registries.ForgeRegistries; -import static codechicken.lib.internal.network.CCLNetwork.C_ADD_LANDING_EFFECTS; -import static codechicken.lib.internal.network.CCLNetwork.C_OPEN_CONTAINER; +import static codechicken.lib.internal.network.CCLNetwork.*; /** * Created by covers1624 on 14/07/2017. @@ -36,6 +36,7 @@ public void handlePacket(PacketCustom packet, Minecraft mc, ClientPacketListener CustomParticleHandler.addLandingEffects(mc.level, pos, state, vec, numParticles); } case C_OPEN_CONTAINER -> handleOpenContainer(packet, mc); + case C_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromServer(mc.player, packet); } } diff --git a/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java new file mode 100644 index 00000000..4edab263 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java @@ -0,0 +1,22 @@ +package codechicken.lib.internal.network; + +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; +import codechicken.lib.packet.PacketCustom; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; + +import static codechicken.lib.internal.network.CCLNetwork.S_GUI_SYNC; + +/** + * Created by covers1624 on 14/07/2017. + */ +public class ServerPacketHandler implements IServerPacketHandler { + + @Override + public void handlePacket(PacketCustom packet, ServerPlayer sender, ServerGamePacketListenerImpl handler) { + switch (packet.getType()) { + case S_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromClient(sender, packet); + } + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java new file mode 100644 index 00000000..759b2db8 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java @@ -0,0 +1,45 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.Tag; + +import java.util.Objects; + +/** + * The base class of a simple general purpose serializable data system. + * + * Created by brandon3055 on 08/09/2023 + */ +public abstract class AbstractDataStore { + + protected T value; + + public AbstractDataStore(T defaultValue) { + this.value = defaultValue; + } + + public T get() { + return value; + } + + public void set(T value) { + this.value = value; + markDirty(); + } + + public void markDirty(){} + + public abstract void toBytes(MCDataOutput buf); + + public abstract void fromBytes(MCDataInput buf); + + public abstract Tag toTag(); + + public abstract void fromTag(Tag tag); + + public boolean isSameValue(T newValue) { + return Objects.equals(value, newValue); + } +} + diff --git a/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java new file mode 100644 index 00000000..23bc32c0 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java @@ -0,0 +1,42 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.ByteTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class BooleanData extends AbstractDataStore { + + public BooleanData() { + super(false); + } + + public BooleanData(boolean defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeBoolean(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readBoolean(); + } + + @Override + public Tag toTag() { + return ByteTag.valueOf(value); + } + + @Override + public void fromTag(Tag tag) { + value = ((NumericTag) tag).getAsByte() != 0; + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/ByteData.java b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java new file mode 100644 index 00000000..c438282e --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java @@ -0,0 +1,42 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.ByteTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class ByteData extends AbstractDataStore { + + public ByteData() { + super((byte) 0); + } + + public ByteData(byte defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeByte(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readByte(); + } + + @Override + public Tag toTag() { + return ByteTag.valueOf(value); + } + + @Override + public void fromTag(Tag tag) { + value = ((NumericTag) tag).getAsByte(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java new file mode 100644 index 00000000..990f9475 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java @@ -0,0 +1,42 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.DoubleTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class DoubleData extends AbstractDataStore { + + public DoubleData() { + super(0D); + } + + public DoubleData(double defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeDouble(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readDouble(); + } + + @Override + public Tag toTag() { + return DoubleTag.valueOf(value); + } + + @Override + public void fromTag(Tag tag) { + value = ((NumericTag) tag).getAsDouble(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/FloatData.java b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java new file mode 100644 index 00000000..6a135bca --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java @@ -0,0 +1,42 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.FloatTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class FloatData extends AbstractDataStore { + + public FloatData() { + super(0F); + } + + public FloatData(float defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeFloat(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readFloat(); + } + + @Override + public Tag toTag() { + return FloatTag.valueOf(value); + } + + @Override + public void fromTag(Tag tag) { + value = ((NumericTag) tag).getAsFloat(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java new file mode 100644 index 00000000..5a5bf64c --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java @@ -0,0 +1,53 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraftforge.fluids.FluidStack; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class FluidData extends AbstractDataStore { + + public FluidData() { + super(FluidStack.EMPTY); + } + + public FluidData(FluidStack defaultValue) { + super(defaultValue); + } + + @Override + public void set(FluidStack value) { + this.value = value.copy(); + markDirty(); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeFluidStack(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readFluidStack(); + } + + @Override + public Tag toTag() { + return value.writeToNBT(new CompoundTag()); + } + + @Override + public void fromTag(Tag tag) { + value = FluidStack.loadFluidStackFromNBT((CompoundTag) tag); + } + + @Override + public boolean isSameValue(FluidStack newValue) { + return value.equals(newValue); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/IntData.java b/src/main/java/codechicken/lib/inventory/container/data/IntData.java new file mode 100644 index 00000000..fe43551a --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/IntData.java @@ -0,0 +1,42 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class IntData extends AbstractDataStore { + + public IntData() { + super(0); + } + + public IntData(int defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeVarInt(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readVarInt(); + } + + @Override + public Tag toTag() { + return IntTag.valueOf(value); + } + + @Override + public void fromTag(Tag tag) { + value = ((NumericTag) tag).getAsInt(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/LongData.java b/src/main/java/codechicken/lib/inventory/container/data/LongData.java new file mode 100644 index 00000000..9b928d9a --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/LongData.java @@ -0,0 +1,42 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.LongTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class LongData extends AbstractDataStore { + + public LongData() { + super(0L); + } + + public LongData(long defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeVarLong(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readVarLong(); + } + + @Override + public Tag toTag() { + return LongTag.valueOf(value); + } + + @Override + public void fromTag(Tag tag) { + value = ((NumericTag) tag).getAsLong(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/ShortData.java b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java new file mode 100644 index 00000000..9a29d0dd --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java @@ -0,0 +1,42 @@ +package codechicken.lib.inventory.container.data; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.ShortTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class ShortData extends AbstractDataStore { + + public ShortData() { + super((short) 0); + } + + public ShortData(short defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(MCDataOutput buf) { + buf.writeShort(value); + } + + @Override + public void fromBytes(MCDataInput buf) { + value = buf.readShort(); + } + + @Override + public Tag toTag() { + return ShortTag.valueOf(value); + } + + @Override + public void fromTag(Tag tag) { + value = ((NumericTag) tag).getAsShort(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java new file mode 100644 index 00000000..f6f043cc --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java @@ -0,0 +1,321 @@ +package codechicken.lib.inventory.container.modular; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import codechicken.lib.gui.modular.elements.GuiSlots; +import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; +import codechicken.lib.gui.modular.lib.container.DataSync; +import codechicken.lib.gui.modular.lib.container.SlotGroup; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.internal.network.CCLNetwork; +import codechicken.lib.packet.PacketCustom; +import codechicken.lib.vec.Vector3; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +import static codechicken.lib.internal.network.CCLNetwork.*; + +/** + * The base abstract ContainerMenu for all modular gui containers. + *

+ * Created by brandon3055 on 08/09/2023 + */ +public abstract class ModularGuiContainerMenu extends AbstractContainerMenu { + private static final Logger LOGGER = LogManager.getLogger(); + + public final Inventory inventory; + public final List slotGroups = new ArrayList<>(); + public final Map slotGroupMap = new HashMap<>(); + public final Map> zonedSlots = new HashMap<>(); + public final List> dataSyncs = new ArrayList<>(); + + protected ModularGuiContainerMenu(@Nullable MenuType menuType, int containerId, Inventory inventory) { + super(menuType, containerId); + this.inventory = inventory; + } + + /** + * Creates and returns a new slot group for this container. + * You can then add your inventory slots to this slot group, similar to how you would normally add slots to the container. + * With one big exception! You do not need to worry about setting slot positions! (Just use 0, 0) + *

+ * Make sure to save your slot groups to accessible fields in your container menu class. + * You will need to pass these to appropriate {@link GuiSlots} / {@link GuiSlots#singleSlot(GuiParent, ContainerScreenAccess, SlotGroup, int)} elements. + * The gui elements will handle positioning and rendering the slots. + *

+ * As far as splitting a containers slots into multiple groups, Typically the players main inventory and hot bar would be added as two separate groups. + * How you handle the containers slots is up to you, For something like a machine with several spread out slots, + * you can still add all the slots to a single group, then pass each individual slot from the group to a single {@link GuiSlots#singleSlot(GuiParent, ContainerScreenAccess, SlotGroup, int)} element. + * + * @param zoneId Used for quick-move (shift click) operations. Each group has a zone id, and you can specify which zones a group can quick-move to. + * Multiple groups can have the same zone id. Quick move work though the groups in a zone in the order the groups here added. + * @param quickMoveTo List of zones this group can quick-move to. + */ + protected SlotGroup createSlotGroup(int zoneId, int... quickMoveTo) { + SlotGroup group = new SlotGroup(this, zoneId, quickMoveTo); + slotGroups.add(group); + return group; + } + + /** + * Convenience method to create a slot group for player slots. + * Configured to quick-move to {@link #remoteSlotGroup()} groups. + * + * @see #createSlotGroup(int, int[]) + */ + protected SlotGroup playerSlotGroup() { + return createSlotGroup(0, 1); + } + + /** + * Convenience method to create a slot group for the 'other side' of the inventory + * So the Block/tile or whatever this inventory is attached to. + * Configured to quick-move to {@link #playerSlotGroup()} groups. + * + * @see #createSlotGroup(int, int[]) + */ + protected SlotGroup remoteSlotGroup() { + return createSlotGroup(1, 0); + } + + //=== Network ===// + /** + * Send a packet to the client side container. + * + * @param packetId message id, Can be any value from 0 to 254, 255 is used by the {@link DataSync} system. + * @param packetWriter Use this callback to write your data to the packet. + */ + public void sendPacketToClient(int packetId, Consumer packetWriter) { + if (inventory.player instanceof ServerPlayer serverPlayer) { + PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_GUI_SYNC); + packet.writeByte(containerId); + packet.writeByte((byte) packetId); + packetWriter.accept(packet); + packet.sendToPlayer(serverPlayer); + } + } + + /** + * Send a packet to the server side container. + * + * @param packetId message id, Can be any value from 0 to 255 + * @param packetWriter Use this callback to write your data to the packet. + */ + public void sendPacketToServer(int packetId, Consumer packetWriter) { + PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, S_GUI_SYNC); + packet.writeByte(containerId); + packet.writeByte((byte) packetId); + packetWriter.accept(packet); + packet.sendToServer(); + } + + public static void handlePacketFromClient(Player player, MCDataInput packet) { + int containerId = packet.readByte(); + int packetId = packet.readByte() & 0xFF; + if (player.containerMenu instanceof ModularGuiContainerMenu menu && menu.containerId == containerId) { + menu.handlePacketFromClient(player, packetId, packet); + } + } + + /** + * Override this in your container menu implementation in order to receive packets sent via {@link #sendPacketToServer(int, Consumer)} + */ + public void handlePacketFromClient(Player player, int packetId, MCDataInput packet) { + + } + + public static void handlePacketFromServer(Player player, MCDataInput packet) { + int containerId = packet.readByte(); + int packetId = packet.readByte() & 0xFF; + if (player.containerMenu instanceof ModularGuiContainerMenu menu && menu.containerId == containerId) { + menu.handlePacketFromServer(player, packetId, packet); + } + } + + /** + * Override this in your container menu implementation in order to receive packets sent via {@link #sendPacketToServer(int, Consumer)} + *

+ * Don't forget to call super if you plan on using the {@link DataSync} system. + */ + public void handlePacketFromServer(Player player, int packetId, MCDataInput packet) { + if (packetId == 255) { + int index = packet.readByte() & 0xFF; + if (dataSyncs.size() > index) { + dataSyncs.get(index).handleSyncPacket(packet); + } + } + } + + //=== Quick Move ===/// + + /** + * Determines if two @link {@link ItemStack} match and can be merged into a single slot + */ + public static boolean canStacksMerge(ItemStack stack1, ItemStack stack2) { + if (stack1.isEmpty() || stack2.isEmpty()) return false; + return ItemStack.matches(stack1, stack2); + } + + /** + * Transfers to the next zone in order, and will loop around to the lowest zone. + * TODO, Would be nice to have better control over quick-move + * Maybe just the ability to specify which zones each group quick-moves to... + */ + @Override + public ItemStack quickMoveStack(@NotNull Player player, int slotIndex) { + Slot slot = getSlot(slotIndex); + if (slot == null || !slot.hasItem()) { + return ItemStack.EMPTY; + } + + SlotGroup group = slotGroupMap.get(slot); + if (group == null) { + return ItemStack.EMPTY; + } + + ItemStack stack = slot.getItem(); + ItemStack result = stack.copy(); + + boolean movedAnything = false; + for (Integer zone : group.quickMoveTo) { + if (!zonedSlots.containsKey(zone)) { + LOGGER.warn("Attempted to quick move to zone id {} but there are no slots assigned to this zone! This is a bug!", zone); + continue; + } + if (moveItemStackTo(stack, zonedSlots.get(zone), false)) { + movedAnything = true; + break; + } + } + + if (!movedAnything) { + return ItemStack.EMPTY; + } + + if (stack.isEmpty()) { + slot.set(ItemStack.EMPTY); + } else { + slot.setChanged(); + } + + slot.onTake(player, stack); + return result; + } + + protected boolean moveItemStackTo(ItemStack stack, List targets, boolean reverse) { + int start = 0; + int end = targets.size(); + boolean moved = false; + int position = start; + if (reverse) { + position = end - 1; + } + + Slot slot; + ItemStack itemStack2; + if (stack.isStackable()) { + while (!stack.isEmpty()) { + if (reverse) { + if (position < start) { + break; + } + } else if (position >= end) { + break; + } + + slot = targets.get(position); + itemStack2 = slot.getItem(); + if (!itemStack2.isEmpty() && ItemStack.isSameItemSameTags(stack, itemStack2)) { + int l = itemStack2.getCount() + stack.getCount(); + if (l <= stack.getMaxStackSize()) { + stack.setCount(0); + itemStack2.setCount(l); + slot.setChanged(); + moved = true; + } else if (itemStack2.getCount() < stack.getMaxStackSize()) { + stack.shrink(stack.getMaxStackSize() - itemStack2.getCount()); + itemStack2.setCount(stack.getMaxStackSize()); + slot.setChanged(); + moved = true; + } + } + + if (reverse) { + --position; + } else { + ++position; + } + } + } + + if (!stack.isEmpty()) { + if (reverse) { + position = end - 1; + } else { + position = start; + } + + while (true) { + if (reverse) { + if (position < start) { + break; + } + } else if (position >= end) { + break; + } + + slot = targets.get(position); + itemStack2 = slot.getItem(); + if (itemStack2.isEmpty() && slot.mayPlace(stack)) { + if (stack.getCount() > slot.getMaxStackSize()) { + slot.set(stack.split(slot.getMaxStackSize())); + } else { + slot.set(stack.split(stack.getCount())); + } + + slot.setChanged(); + moved = true; + break; + } + + if (reverse) { + --position; + } else { + ++position; + } + } + } + + return moved; + } + + //=== Internal Methods ===// + + public void mapSlot(Slot slot, SlotGroup slotGroup) { + slotGroupMap.put(slot, slotGroup); + zonedSlots.computeIfAbsent(slotGroup.zone, e -> new ArrayList<>()).add(slot); + } + + @Override + public void broadcastChanges() { + super.broadcastChanges(); + dataSyncs.forEach(DataSync::detectAndSend); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java new file mode 100644 index 00000000..bfa02872 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java @@ -0,0 +1,121 @@ +package codechicken.lib.inventory.container.modular; + +import net.minecraft.world.Container; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; + +import java.util.function.*; + +/** + * A fully configurable inventory slot. + * If there is anything this slot can not do... Let me know. + *

+ * Created by brandon3055 on 10/09/2023 + */ +public class ModularSlot extends Slot { + private boolean canPlace = true; + private boolean checkContainer = true; + private Supplier enabled = () -> true; + private Predicate validator = stack -> true; + private Function stackLimit = stack -> Integer.MAX_VALUE; + private BiPredicate canRemove = (player, stack) -> true; + private BiConsumer onSet = (oldStack, newStack) -> {}; + + public ModularSlot(Container container, int index) { + this(container, index, 0, 0); + } + + public ModularSlot(Container container, int index, int xPos, int yPos) { + super(container, index, xPos, yPos); + } + + /** + * Configure this slot as an output only slot. + * Items can not be placed in this slot by the player. + */ + public ModularSlot output() { + canPlace = false; + return this; + } + + /** + * Do not use the containers canPlaceItem when checking if an item can be placed. + */ + public ModularSlot noCheck() { + checkContainer = false; + return this; + } + + /** + * Allows you to attach a validator to control what items are allowed in this slot. + * You can also limit a slots allowed contents via the {@link Container#canPlaceItem(int, ItemStack)} method of the container. + * + * @param validator The validator predicate, If the predicate returns false for a stack, the stack will not be placed. + */ + public ModularSlot setValidator(Predicate validator) { + this.validator = validator; + return this; + } + + /** + * Allows you to get a callback when the slot contents are set. + * Parameters given are Old stack then New stack. + */ + public ModularSlot onSet(BiConsumer onSet) { + this.onSet = onSet; + return this; + } + + /** + * Allows you to apply a stack size limit that (if smaller) will override the container and the item stack limits. + */ + public ModularSlot setStackLimit(Function stackLimit) { + this.stackLimit = stackLimit; + return this; + } + + /** + * Allows you to attach a "can remove" predicate that can block removal of a stack from the slot by the player. + */ + public ModularSlot setCanRemove(BiPredicate canRemove) { + this.canRemove = canRemove; + return this; + } + + public ModularSlot setEnabled(Supplier enabled) { + this.enabled = enabled; + return this; + } + + public ModularSlot setEnabled(boolean enabled) { + this.enabled = () -> enabled; + return this; + } + + @Override + public boolean mayPlace(ItemStack itemStack) { + return canPlace && validator.test(itemStack) && (!checkContainer || container.canPlaceItem(getContainerSlot(), itemStack)); + } + + @Override + public boolean mayPickup(Player player) { + return canRemove.test(player, getItem()); + } + + @Override + public void set(ItemStack itemStack) { + onSet.accept(getItem(), itemStack); + super.set(itemStack); + } + + @Override + public boolean isActive() { + return enabled.get(); + } + + @Override + public int getMaxStackSize(ItemStack itemStack) { + return Math.min(super.getMaxStackSize(itemStack), stackLimit.apply(itemStack)); + } +} diff --git a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java index 7bd13335..1f25a147 100644 --- a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java +++ b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java @@ -1,11 +1,13 @@ package codechicken.lib.render; +import codechicken.lib.gui.modular.lib.CursorHelper; import codechicken.lib.raytracer.VoxelShapeBlockHitResult; import codechicken.lib.vec.Matrix4; import net.minecraft.world.phys.BlockHitResult; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.RenderHighlightEvent; +import net.minecraftforge.client.event.ScreenEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.EventPriority; diff --git a/src/main/java/codechicken/lib/util/FormatUtil.java b/src/main/java/codechicken/lib/util/FormatUtil.java new file mode 100644 index 00000000..e3395419 --- /dev/null +++ b/src/main/java/codechicken/lib/util/FormatUtil.java @@ -0,0 +1,46 @@ +package codechicken.lib.util; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; + +/** + * Created by brandon3055 on 31/10/2023 + */ +public class FormatUtil { + + private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###,###,###,###,###", DecimalFormatSymbols.getInstance(Locale.ROOT)); + + public static String formatNumber(double value) { + if (Math.abs(value) < 1000D) return String.valueOf(value); + else if (Math.abs(value) < 1000000D) return addCommas((int) value); //I mean whats the point of displaying 1.235K instead of 1,235? + else if (Math.abs(value) < 1000000000D) return Math.round(value / 1000D) / 1000D + "M"; + else if (Math.abs(value) < 1000000000000D) return Math.round(value / 1000000D) / 1000D + "G"; + else return Math.round(value / 1000000000D) / 1000D + "T"; + } + + public static String formatNumber(long value) { + if (value == Long.MIN_VALUE) value = Long.MAX_VALUE; + if (Math.abs(value) < 1000L) return String.valueOf(value); + else if (Math.abs(value) < 1000000L) return addCommas(value); + else if (Math.abs(value) < 1000000000L) return Math.round((double)(value / 100000L)) / 10D + "M"; + else if (Math.abs(value) < 1000000000000L) return Math.round((double)(value / 100000000L)) / 10D + "G"; + else if (Math.abs(value) < 1000000000000000L) return Math.round((double)(value / 1000000000L)) / 1000D + "T"; + else if (Math.abs(value) < 1000000000000000000L) return Math.round((double)(value / 1000000000000L)) / 1000D + "P"; + else return Math.round((double) (value / 1000000000000000L)) / 1000D + "E"; + } + + /** + * Add commas to a number e.g. 161253126 > 161,253,126 + */ + public static String addCommas(int value) { + return DECIMAL_FORMAT.format(value); + } + + /** + * Add commas to a number e.g. 161253126 > 161,253,126 + */ + public static String addCommas(long value) { + return DECIMAL_FORMAT.format(value); + } +} diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 03a57caa..0cd041ee 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -63,3 +63,27 @@ public-f com.mojang.blaze3d.shaders.Uniform m_5679_(Lorg/joml/Matrix4f;)V # set public-f com.mojang.blaze3d.shaders.Uniform m_200759_(Lorg/joml/Matrix3f;)V # set public com.mojang.blaze3d.shaders.Program (Lcom/mojang/blaze3d/shaders/Program$Type;ILjava/lang/String;)V # public com.mojang.blaze3d.shaders.Program$Type m_85571_()I # getGlType + +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_280092_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/inventory/Slot;)V # renderSlot +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_280211_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/item/ItemStack;IILjava/lang/String;)V # renderFloatingItem +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97744_(DD)Lnet/minecraft/world/inventory/Slot; # findSlot +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97818_()V # recalculateQuickCraftRemaining +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97706_ # clickedSlot +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97711_ # draggingItem +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97710_ # isSplittingStack +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97717_ # quickCraftingType +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97720_ # quickCraftingRemainder +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97715_ # snapbackItem +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97714_ # snapbackTime +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97707_ # snapbackEnd +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97712_ # snapbackStartX +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97713_ # snapbackStartY +public-f net.minecraft.world.inventory.Slot f_40220_ # x +public-f net.minecraft.world.inventory.Slot f_40221_ # y +public net.minecraft.world.inventory.AbstractContainerMenu m_38897_(Lnet/minecraft/world/inventory/Slot;)Lnet/minecraft/world/inventory/Slot; # addSlot + +public net.minecraft.client.renderer.texture.TextureAtlas m_276092_()I # getWidth +public net.minecraft.client.renderer.texture.TextureAtlas m_276095_()I # getHeight +public net.minecraft.client.gui.GuiGraphics (Lnet/minecraft/client/Minecraft;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;)V # +public net.minecraft.client.gui.GuiGraphics m_286081_()V # flushIfUnmanaged +public net.minecraft.client.gui.GuiGraphics m_287246_()V # flushIfManaged \ No newline at end of file diff --git a/src/main/resources/assets/codechickenlib/atlases/gui.json b/src/main/resources/assets/codechickenlib/atlases/gui.json new file mode 100644 index 00000000..5da82735 --- /dev/null +++ b/src/main/resources/assets/codechickenlib/atlases/gui.json @@ -0,0 +1,9 @@ +{ + "sources": [ + { + "type": "directory", + "source": "gui", + "prefix": "gui/" + } + ] +} \ No newline at end of file diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/drag.png b/src/main/resources/assets/codechickenlib/textures/gui/cursors/drag.png new file mode 100644 index 0000000000000000000000000000000000000000..1e8c3266ad6e5f5e3f99ec6652b4ab6e1e6ea8c4 GIT binary patch literal 4183 zcmV-d5UB5oP) zaB^>EX>4U6ba`-PAZ2)IW&i+q+O3#tlH|Azg#YstK7#lFK^}+C2;acR_XkQ=&KG~FrWzV2<+}gs`S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aY5^{{S?T-GX2$=}p_s#v_rw>4edX>5X4i15lB4w}pygSm_ zw|{F|{rdqqMskpsfL^2k000JJOGiWi000000Qp0^e*gdg32;bRa{vGf6951U69E94 zoEQKA00(qQO+^Rf1qu#1FvOn>JOBU!)k#D_R9M5USIchHFcdw<4j%v#&_&fng{mSJ z6m{ks5I;a4@PCLOVU3v5&J652i>hijbUt(M%ofxN>BqaIKOXQTdmn>X_ z9tc4kPfsHq(X&ul-a|5Hc{wWp!#Xeka60`M?^0|4AbsKVHi1b24JO0RZeIzYAsi7H z=e4(!cU9a|5G}*P_ZP9gg(PTXU99|4L(+tadh8rX#gB;na;i&2dZ0_)dom08(N zNs}r+JR6YiXH)L81>mWG#{w=1{9(lxiDxoLuYF62G_W)kfDFJR0CNDp2;A5GRLxmK zT)D0qT>K?z`+R5V1X~W42CYj%0a?!6uTRDwJS%odLP_GJiUdTjKrae$Y#EhgK;PMd zi?y}h8pJfH1OVDC^x%*x%21VSGv^(uF$aJp!_|OV1&k!LC*dBzJ)zyA3Sl0MBA5#x zyD_)bCISZ2;gaFTL!SqdaCk8wX;w02c%XTHaNhZ9se>FG*{B+_nVHp}vkdBd{G2p| zrN#D-9j*gWn{Nks<&6-)H4_d`H+0Dr4E}6aB{kl8pu;rPr&r#z;j|lLdJu2&=mc$d z7OJZjAkt>1RX-4wk3rmUiY3YP?8PD`lzEr~O3rW3Dlss<$~)yjokvY84+y|t z`Pzj5y)4v=F-hok-U5JxQCwYKk zNiq%HbS0vU=Qd346I$n)tatDnS$(q}Seg?}VEzvPB&DhnOz=Lr__B_g tvyGLnxF2$4YkQ0k%jO>Fai0jm`~zXIjSMZy4vYW*002ovPDHLkV1i)}jB@}0 literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_trbl.png b/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_trbl.png new file mode 100644 index 0000000000000000000000000000000000000000..b306c6ba4b86116e5c22d20399474c5dbec375c9 G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YT6<|qPnfa6-Lx9rUPLSK&qO(zx|xubIUs*a2o^L6e& hnJN*I=zL2&{|_!vsePKv2mt^9002ovPDHLkV1iJ(Lht|p literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_h.png b/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_h.png new file mode 100644 index 0000000000000000000000000000000000000000..07baa61c49b5bb6d4b3c49fe61a15c172599c9f6 GIT binary patch literal 3325 zcmV zaB^>EX>4U6ba`-PAZ2)IW&i+q+O=3~lH@E7{Ld-&2u2_T#}ObR_6B?WO<`A+yQ{jt znTXx?l(BgTk*Sv_*nj@L!oToG?WiHM)Y3{h@RwU|q6t;FDhc=^K{i!Uzu^2O@t4e?xrRI6XC@uLHz~z8&ZKtu^af zcAidi0ixxys3Sbk@imy(0eRZX3NFEq@htmlxGJ_8AZH%q=(t8~k%0ROF~=D-u4ua* zaX`gPMuL`TP}+Sp2{jsEEILOi$3>D_nyG@hK^8z?PW03z?tRTKXZdy{1l{3SBBv;sw!nZOr7Z$F88*51=7cQkp@gS#? zBnwLskt$8JrkX3)Ql-|~sy1o~F_2qn(rRl>m4ad;g)GH{ZKahLud-y-)s{Y4yI6g@{(`l5 zu|}IIpC?b&&>KV^BBF;AcFw>Ub8Gu2Pb9U62GdXk4+0i_vF+oXoZo-Vt7%0pZ ziC27b_hRmkcne(rh&TEt=7LlAzhEwax_90_ur@v1jm_BUg^uZw;C&dks)4F{Qq#|E zFWO`Ad(v8%MG>`Fu*n!_gOI!usf3(xq?vRKzZ-D2l1ERu1I*52QmO{{6rhW0okF={ zT5FS=ur|NPNC6Qw&H@T;mSakXdup>~v1_ZHTVkDlx5;EG9_UPCX8bFo*!kq%|9JSN zWgvxwEyLerF5u!r{?45-iXgy zYC_+FoLOKvAZ4{;?CNtj$W`=9?uO$fSjmJ*>FNoDucB}Q%d7LM64r>`+l>2Y0)-aR zTO}E^F?M(&BgIstBdeL>&=**64;;=njbTsSL;mUze{L_3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Z2{ z1SF(IF8fI48R3*n3Qg<&A@IHTUWtvVri3!h98eVZA&q`ZPOZm24EWAT9t)DdLz@lT zbsAp>Ip6ym+c=ghkkX-T4 literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless.png new file mode 100644 index 0000000000000000000000000000000000000000..f1484440a40e387de4625f5a774eb84fc5c1c9d3 GIT binary patch literal 8152 zcmV;}A1C06P) zaB^>EX>4U6ba`-PAZ2)IW&i+q+O3*va^$*lg#Tj|UIOt3mV*Zo;T?GS{<6sKk$Bwc=Q~y#`a6jJc0b=pl_>4ZRWXD+`gqyT_N*X2--GYWPaiYa z`B?3Ba{P*n_^gD0{Mz2<_jUaY(61nWUb(+U|NH7M!4KnoKmH|_<&6<9{_z8!|2g;; z;vW;o?~20j57O}AZ`*ml&)Myq``O({g@~4yQJ4EfNB3~yWTgc^I?v4Q0Z zw*#{j!*?y-=Iu7$@{O6d=hEOA%yY~C_~rh$5C5Gncg|9X{MEj(VqHN2XBk3HKe-A( z{CRQ97U0j<3;*?lKTs6}vxT{_!Ew!Jh?)H#Zbid6a$V;4lNH|8{SH8gm^-r=A3@+M z8*(T?Z=+2Bkz*mB8VC)* zN-4vini?D$Ip&meF1hCBa?hj0l1eV6)FP1^HP%#fEw$EGdmSyd)N(7Ww$^$ZJ@kkM z=3aX3t@l1gaD#~kV-2n!yfed$GtE59th3EN$AUg9t-Q*rtF6Aq4m)mSVwYWa+kKDQ zyBnpr)1B{f*Sp>Q9tWX&kUWT2ApoI+FuR&hDF``XcJ)9~9*Db3pfZ-2MTztva_1u_p@^(<_pFdu}Fm;oR%+XPBolRyp>UFVVMESQ-gwv}qLt7?L^uGuZS4Au<|xl!*kmpQJc&*^?3?jL^mPd^|F(Li{x-gS}8zBEPpV{}9NTOQ#Y|{Oqd^JF9 z$;ON?G49%!ZsydW(>hds2&K=^r0-h)4AhdcK&gfnMZ+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wd*;uNiLCK6hsiD)N zDzo%joeYuJlvZn&>ADKU_xt^De*yvlQ@XBg4-DeqRS$8rT=#u{J{O3GrAk9xNR%ln z;zT?d2EpTr4UUQDkc_+vo~k7%57F*H!~tq`ic(@mXI>gVHo}e!8pjCKC3;Lu8!cNxKqaI^1O&?`r^E@B)y7(|-#1%H9 zr$V4K)1*Fkq{iOw_k#|h$6;FA5y1Pt_cj>G8pBXsRn_6S09A&f5$f?+XE;)OdgKo( zYB~!4GZFf9CIgseOq}+}R4_%!6?g%`(=HZ|_p;Wm*0}a%J%v#eMt{TO9B44j>AlaQ zPWdn_G3n_!MC=@zsTyrP)6foaCc$$**8>zpxQNZ7ovCcDG+75Jy`JN(IFIvCltx0! z=I!mxTdzJotD-DOe)eF8%59J!6d)bB8K(~?Lp-IWf`l@-s0c;A9dYCAsS)Sk(o!i6 zvIsdH)ke!mkIpo@v0L$Q1p(C4X*09i?PkA!|9*D>2&s?6aaN$@Mj2EbX5xvEf?w1K zK=sHo^bDV;InJI-#OX@bh_>>4vWP6yLs38AiI1L;o+>x%co`!dMN#gBA^hGnjf)KmAEODOa*A_+nY4KMTMW3D)e>G9mpB8^rQPdxi zc~w!=W${-PMg3{=le`ZV~eqUh=A@XLv!5#U}) z6!oXYUsV+K)8SVYMb~w;{N>9R`}XbIA?Mxi8 literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless_pressed.png b/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless_pressed.png new file mode 100644 index 0000000000000000000000000000000000000000..7273c079cd5a16f01199ad9a8c3f2d9718a68859 GIT binary patch literal 12424 zcmeHtc|4Ts|Mxw{z9yr^9u-qrhQSObW2tZ&#t@-&2Ez=-Huk+zI+8X~LrmEsl(HnD zj+oP8$rj@n;Y7$5Sz~_pXgQtd`MqAxbDr1p`|mrwZufQH*XMd)pZELvT%Y^8?z`Xc z)`!G|WrP6$5VN!}CxB-x_YmX<{}xdK*#IEbLpo~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Nvc`#E*DHcl;wFhW_0_)OwMLxhgQg^%Xxd;q<}Lrr&=K>_M|Eh;Wa(6Kaqbh?Zi zJOb2b)LoIrpq;8HQ~^V8alLw+PQ8M%F;-Lgh6t6x#K-gWqXNqZ^YD{IPG9xguGz>( zliuUVih>G5zgBu!9RRbpzGSWTAcS`NnSrQ(D@~Wx|HqhHQS>M$e>6`oB*^M`sSa~S zN4;rc1Jfg=47c<0c|W>V?$O_X+L56i4JA{g(j;-7Ns3Oq34ztjC^>3~&}Zi9wWL(n zeolON+@%OAraBqg;d=GD_*xRLM_)wjzBiv%cR#`a@&X#ENOfM%C)|jlABAThU>^<9$So_S5R_<=mt1t#+Mkx=7h+6wVOjD9%9@ zuBWx%o2N_O@POiNn6lM;fA>xKs$1Ur6bD&lJuzq{rVE0y=s*v{r+KnhGtWSmu&(DjZ?lBE=7O#*dvtz6C zt){HZ^B8S&YMcup8DY+Urke;0B21iwv z50$q!n0HY<$ZOyBW3Kh__WHyY`2f%N)?s=y+V#5Obn3r!HrX^o)}rCb@vK=<%g{8ui+1GPiW=x02$4R}# zkrc!3I&aM}wHVv;!p@b~ZulKZP^}Am^=z^kja1Tpic!iJ1yUYZC=@p~ zbG)Mlz;LeL0r=|K-&4b-8E$s3(CWgb_+3gzMK>ab0N3{z#}U8&;t{-ubxuPvgn(ff^lzPWSl3k-*Z2L6 zg#NL5m5@@xI88_~Hq#^lKb}k-5JJGZt}2Rl|L(8P{~cWttaZwvUf=)#002ovPDHLk FV1kaFt{ngX literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_borderless.png new file mode 100644 index 0000000000000000000000000000000000000000..677d04c1f27e3470d58ec161bcbe8326fe859784 GIT binary patch literal 14008 zcmeHucT`hN*Y63TN)ZqgkS6LwlRzLqLRX~sD#aE;fY3weq1iPeSU?bwBE2fo1Vluo zOA!zhq$3d#BE6G)g8Dq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PPl}P&cB~=F)SdLqBzAOt z*TBcHBA&~S77FoO?{CVdtQF?sja+XkIQiqp?i5;@Ldg9_Nx??$y;~AL$5$+vj_O|? ziRCqMU@?zTDKeJ&y7raJCz*>kKi$4ikL1Tx=;$kJtEQS) zMW?1pBQ@u%&g!1IPf7@%n69(9Uck2&Oja!nj8hO%^KE0V9nVd$9!spuY)!8j?~D5{ D-GY*S literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla.png b/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla.png new file mode 100644 index 0000000000000000000000000000000000000000..5e64e34babe124f2136081e47f342b05ae85af16 GIT binary patch literal 8373 zcmV;mAWGkfP) zaB^>EX>4U6ba`-PAZ2)IW&i+q+O3*va_qQ{g#U9Dvjp)?E{BxFh}pp`f4&4&W!E`& z-=2uE``BeYC=f^_5>UJQfBt*9|KcmhR$R)pm0rrhSL&&U!H0J2uWmp6k?f~^rRNlX ze;jx36M;jK-*Nw0$8-JQc>cQK^$b5hkGuAq3GG?vIq_OB>dAo**LNd19`-TYdchHBEU!UBc-hY4k!}(!6$KxNqERT=)@Z$-ee|EmP_}hcy z+oJG!;z~aLwVmhRT31`^-n$#A;L-9R>Toab=pHVdxIEfzh40G0%;##~o$q#x<0LrO zaUPTJ({~?u^m0D=%MZW&ZNE={Vqyw+sQeD$4AG9YSVIqIRGgB&{R)+cU9l0%Gu)2Q zr5N6}czbTQ=bgUsw;j0}kk39g0~^la{_-mVQfl%T_K6M@LF#7b<)DT0+! z20t}5Ff?+^Dd${r&CTVWM~NksTuP}$BsXfTspeX0t*!PtT5PH1R$6VX^)`Cw5f03~ z^x9kReT?7+4;rjBxPEYCh8bs?d6rpcn|+QG_?+p?XF2QH&VG(7T=9Y?u5#6@UHuxj zcQ;INr#s)}u6MipJr-D7aix`4S#`D5*LX+miRxe9|A(mgCu+eWrR(ZDY8-X7zLxN! zldPB#v5-6wuZjSG4vN{)d`dx)Q_PMY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mXTMS zpnlhfR-NF|p+q=rhjqVz0}x=T(QN73q&i z+78K(^8U{<&wB>hk4oAORQNN_^I~?|aQUdD?a&pD%D3|966C z?L6N?SETlRpZ8$e<~E5`f(pO9yx7m5Ka27aTJ(QysUBXV#@Qb# z(^dm9wBHaOHmk#s$}+Vw^!E1lFzSF{yuE54_$zX?omc(W|9t)*LHyt`>q7C;00000 LNkvXXu0mjfO5AST literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla_disabled.png b/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..aa29d9977b7b451e1f3f1180ce0538d538eaf9df GIT binary patch literal 6849 zcmV;y8b0NTP) zaB^>EX>4U6ba`-PAZ2)IW&i+q+O1hxa%4FU``0Pv2wExWI9em-26OxYDCOpKb@xO} zxooFjzNdu%K~QPdfBwDAzwj?6@g}BRq>5Pli#1l?@S@oBuj)@{qyE%?@xFz>KdzhS z8y=SeeuwjCZukC%>*@8tV-D9pubXn;@#PM5-*^ldIJ3u#`MyY8_vgC1D=~GQ7g9@p zUuyT~_joM1yuL%$p`U~BZ}Wa3W<+Tw+!efE!3C>7%UMA<-wodhKV1;q=R(En5URni z80uXK0`jrF$8T%j1N0H($1C$Q`p;KCg74eC9)849ZjA8a*Ed}HJ@^{pw~51ZMgH@R z+THhd?)Toa?7hzJS`sQ5BvCR&EGwrY)U&B@B zfyy>6y6KwRZt3sg29_B8@)^IqA3o@{60)y;1mYC=<+jg2Y=#0XhhGNJ#o(W7aXN3+ z`GzZ)c{<$c9R_oF`H3x88J9Y?b-dLIA)w1w9t)2vOHBe#^;0-|b3_6R!G@K*= zrhsV{25|$z+&NKdc86$PwE;`pZ%gAdAJdyVe`=F*j=~L<+TCH$`ZlP;>gxCEa+c7s zx+TTnL10>S|CNL5$OzDmA4@;0m@-6a04yC|K&bZ|+s|$I5U0hkefokpVjTZt=I&w( zh2gAcKbYuq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 zMvx)<@)_T*FbeIZ^xYmle`3R*(!Ik@RAzV(aedh6 vqbkoi2^%p%Co%7|6ZO|K!6E(SKcD{x6y=*Sul1!Y00000NkvXXu0mjfJp%3c literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_borderless.png new file mode 100644 index 0000000000000000000000000000000000000000..87a64d8b40e597de2f289eb04e33545c063d897e GIT binary patch literal 6281 zcmeHKc{r5o`yYE$B9$dFMiiNSm?g?uR5G%LWR`arnHgp=sF0mb5=GfN*0iI^5@jtX zQ4TF+sZ=UkN}SU1eMfapUBB-?UDxmXUo+P`^S;mXxj*-Pf1dk!-sedq@7%gnK|=uo zfh@JNwcZ8(n~SeSvfytSGiU$;k-Hh@?9Sgs5kdpG90oH0fbv5F0Voi{WI!Mxy)Ev{ z)ORAqxlX6yMX(#w1h2E)XyF{ryp7g2)lC>I%-xetM?fQGH458j2M7P0i(OW0+xpi@ zOGQf4O(5gUkPhpO(|dn>iQDI@y2bMjV=wMm_)#B+ezvD*M^yI3M+!ECOgTjD>f89b zT6batxn@zXD)nB%>XW+h zd$+8k;hZYWguDlAYsl-w{h9vQbL$Z|dMNnUD4RUg1C<&JF=~dnb?*k`v=2@_%DB-WqivaBVSCv+xx-r9>Nj+Y=JuzvaPsaPy~eAgMSpeIYi|J<1u9vY1$)h|5#E*GVHzUr=y z-W)b^xg>YLdNA~O-0JWc<*gc_#}mm}0mWJ2aq7OAq3Lq|8_yvJmys(r`WM=^-Iz6B zdLF$7cJ6MXYCA-&EJ5a}Bh=hH%}1p7MpK>}^(b9__Y?VTVGZXzEtV{*p|m;d_wn`9 zF}(FznXO-=!hX*=hL!A(zg71%INl=z)4k&IiP)#zM~)rD_9{+~X|i^fVJ)3chKLTa zFmTJPWcHF+M?vyqUD;j7SM5!m<%v9kBt$K8DeqRry*J@{kF&d(43Sa9HlcyZ%XisC zf8q9!@zXfO`m3b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j3U B_Fw=2 literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/codechickenlib/textures/gui/widgets/slot_large.png b/src/main/resources/assets/codechickenlib/textures/gui/widgets/slot_large.png new file mode 100644 index 0000000000000000000000000000000000000000..61c28017fb4f9b4b83470a2fbefd48fc3e662ce6 GIT binary patch literal 5546 zcmeH~dpuNI8^=ek(M3l&$f+@Mt7c};#h95)Vvvzr4RQ%*o7ux)W;8Px%E_fro#axv zB$1Mma;p@QsH8}Am6R^0T$7S=D({}5+vh!hynR0J`L8{ny=L#Vp69#P^IOl_YwxWt zPAg}s>Zl?Rh?xvK>oxGdj`UPfg3BZJ4y_1;5;e-zL%arzK!yqh9Bv4N6i0?aNJzrv zAP|zyLC>{m4Wt<#FPjJzNTs@oVTNW+uU@aP=NFT2H>aQQV5MG-8(AQi=G(XFBjv^H zjUhmSZsLpdG1Y|`>+ssUi*6fTKkd#xcV}T_f5-JfaX%1PZag?n80UTHJ}#IR9_#fg zKF{NH@<>-|m!ZWumCm`IWleeQBulOayQQyfZ%mD6A9Kb|%&v3Iyiaj*erXvqnQtAN z`X6EtwU+`bFNupwF5K^IK`im3lL{UW+s1pgXwzxkAx}745s@(+gXzEDP-i~q$un~2 zn?`pzod}^+%q+tq|Mrf&>y*9IGpo%aFnoP+*7I<0&7p(7Z5c1M(8;}onx*<8_hP!uGj}uMt+>%16o=%X}1jBxIx?7x`+unGeNK07w;vuI%(0Z zEQ99>JnAvlb;Egzwo3#vB4yK^npd4{>XxL zJqPIb6%eQ*j#dF$3lZE|{?<#6qF5rwREE`$4g@NvI$MXBePsmIKZxeQBDZ(SECKCWmtJ33TD5fj{LazcNGCZ#nYr7yG40o^E@_^m*17 zTvS$=y_b7RZxivM)pqpBuCU8%`i_gnXm9Q^ugkCEdFb$mhxPv?w>O#HCV6c#H}dG1 zAI!lU$T#dTtxPE0-j?R%L6!&a+7Pv7Tghow&S`bM*{TgXk(pPJi|?Md(`?PwymUUV zzjL^4Sp-|N;6j%{w{ewG_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wjfjZA zL=Z3nVE`6Kp-`{@9*f7LVGFb{x+MAm@q^Z4x5FALLeS&DuR2(eb?nmhNH_D52*wJTwbWm3l{r3OEH)8 zRjlvECT)?0^X))j_b=Sh$x9r`6d(fx zG~Sd#K@-jJ{%Eop2|{xyB!B}z6bgaB`3A+{i^L$G1xZmb9K(e;b354 zL1~`C02vmJg-RDfpjaSu6$nCTC@BId^^~PI(tL7K?6@M>B2t?1Q#sFs)=%C|E`boP ztO<#fr7aa?O?Dyz!=XtzVZX^HRv^d^fZ+8#l~AASx&JU(L=L>(DFA@R5l!Lw22Js3 zkcW@HY51hLp`q8UjR#uvIsz!67)LdY@zjuegtP9Rw{NMo6lCf{2}1VU1s0C;T! zL^K|7#RF6viE2t-f&-`kfWl4%jFqnH&k>tr|4S2dnZY-Y0oZS{4t~7APb=(~$JLZ( zQW^inV`?t`#U5bv&rW_w-=A{*leR!*QPbe6WejUeSG&uDEx36IK&7!Q*pCJ(m{hGG?prLk$B=od?%J`NIo16&y-QJ* krgPONkGB0O_zJ_bZ|?>N=9aEDhcO6-jg$3ptKZ}P1O9uM3;+NC literal 0 HcmV?d00001 From 7d8da8597c1d77490b8c633c5aa5451da6bf07b8 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sat, 27 Jan 2024 19:35:13 +1100 Subject: [PATCH 17/87] Add Supplier methods to RecipeProvider to better support RegistryObjects --- .../datagen/recipe/FurnaceRecipeBuilder.java | 68 +++++++++++++++++++ .../lib/datagen/recipe/RecipeProvider.java | 45 ++++++++++-- .../datagen/recipe/ShapedRecipeBuilder.java | 18 +++++ .../recipe/ShapelessRecipeBuilder.java | 26 +++++++ 4 files changed, 153 insertions(+), 4 deletions(-) diff --git a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java index b55e9d84..fe46f8a3 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java @@ -12,6 +12,8 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import java.util.function.Supplier; + /** * Created by covers1624 on 28/12/20. */ @@ -40,6 +42,18 @@ public static FurnaceRecipeBuilder smelting(ItemLike result, int count, Resource return smelting(new ItemStack(result, count), id); } + public static FurnaceRecipeBuilder smelting(Supplier result) { + return smelting(result.get(), 1); + } + + public static FurnaceRecipeBuilder smelting(Supplier result, int count) { + return smelting(new ItemStack(result.get(), count)); + } + + public static FurnaceRecipeBuilder smelting(Supplier result, int count, ResourceLocation id) { + return smelting(new ItemStack(result.get(), count), id); + } + public static FurnaceRecipeBuilder smelting(ItemStack result) { return smelting(result, ForgeRegistries.ITEMS.getKey(result.getItem())); } @@ -63,6 +77,18 @@ public static FurnaceRecipeBuilder blasting(ItemLike result, int count, Resource return blasting(new ItemStack(result, count), id); } + public static FurnaceRecipeBuilder blasting(Supplier result) { + return blasting(result.get(), 1); + } + + public static FurnaceRecipeBuilder blasting(Supplier result, int count) { + return blasting(new ItemStack(result.get(), count)); + } + + public static FurnaceRecipeBuilder blasting(Supplier result, int count, ResourceLocation id) { + return blasting(new ItemStack(result.get(), count), id); + } + public static FurnaceRecipeBuilder blasting(ItemStack result) { return blasting(result, ForgeRegistries.ITEMS.getKey(result.getItem())); } @@ -86,6 +112,18 @@ public static FurnaceRecipeBuilder smoking(ItemLike result, int count, ResourceL return smoking(new ItemStack(result, count), id); } + public static FurnaceRecipeBuilder smoking(Supplier result) { + return smoking(result.get(), 1); + } + + public static FurnaceRecipeBuilder smoking(Supplier result, int count) { + return smoking(new ItemStack(result.get(), count)); + } + + public static FurnaceRecipeBuilder smoking(Supplier result, int count, ResourceLocation id) { + return smoking(new ItemStack(result.get(), count), id); + } + public static FurnaceRecipeBuilder smoking(ItemStack result) { return smoking(result, ForgeRegistries.ITEMS.getKey(result.getItem())); } @@ -109,6 +147,18 @@ public static FurnaceRecipeBuilder campfire(ItemLike result, int count, Resource return campfire(new ItemStack(result, count), id); } + public static FurnaceRecipeBuilder campfire(Supplier result) { + return campfire(result.get(), 1); + } + + public static FurnaceRecipeBuilder campfire(Supplier result, int count) { + return campfire(new ItemStack(result.get(), count)); + } + + public static FurnaceRecipeBuilder campfire(Supplier result, int count, ResourceLocation id) { + return campfire(new ItemStack(result.get(), count), id); + } + public static FurnaceRecipeBuilder campfire(ItemStack result) { return campfire(result, ForgeRegistries.ITEMS.getKey(result.getItem())); } @@ -132,6 +182,18 @@ public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemLi return custom(serializer, new ItemStack(result, count), id); } + public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, Supplier result) { + return custom(serializer, result.get(), 1); + } + + public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, Supplier result, int count) { + return custom(serializer, new ItemStack(result.get(), count)); + } + + public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { + return custom(serializer, new ItemStack(result.get(), count), id); + } + public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemStack result) { return custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem())); } @@ -153,6 +215,12 @@ public FurnaceRecipeBuilder ingredient(ItemLike item) { return this; } + public FurnaceRecipeBuilder ingredient(Supplier item) { + addAutoCriteria(item.get()); + this.ingredient = Ingredient.of(item.get()); + return this; + } + public FurnaceRecipeBuilder ingredient(Ingredient ingredient) { if (generateCriteria) { logger.warn("Criteria not automatically generated for raw ingredient.", new Throwable("Here, have a stack trace")); diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java index cd97519b..cb38c5ed 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java @@ -1,7 +1,5 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import net.minecraft.advancements.critereon.*; import net.minecraft.data.CachedOutput; @@ -17,8 +15,6 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraftforge.registries.ForgeRegistries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import java.nio.file.Path; import java.util.HashMap; @@ -26,6 +22,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; /** * Created by covers1624 on 27/12/20. @@ -71,48 +68,84 @@ protected T builder(T builder) { protected ShapedRecipeBuilder shapedRecipe(ItemLike result) { return builder(ShapedRecipeBuilder.builder(result, 1)); } protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result, count))); } protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result, count), id)); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result) { return builder(ShapedRecipeBuilder.builder(result.get(), 1)); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result.get(), count))); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result.get(), count), id)); } protected ShapedRecipeBuilder shapedRecipe(ItemStack result) { return builder(ShapedRecipeBuilder.builder(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected ShapedRecipeBuilder shapedRecipe(ItemStack result, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(result, id)); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result) { return builder(ShapelessRecipeBuilder.builder(result, 1)); } protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result, count))); } protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result, count), id)); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result) { return builder(ShapelessRecipeBuilder.builder(result.get(), 1)); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result.get(), count))); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result.get(), count), id)); } protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result) { return builder(ShapelessRecipeBuilder.builder(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(result, id)); } + protected FurnaceRecipeBuilder smelting(ItemLike result) { return builder(FurnaceRecipeBuilder.smelting(result, 1)); } protected FurnaceRecipeBuilder smelting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result, count))); } protected FurnaceRecipeBuilder smelting(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder smelting(Supplier result) { return builder(FurnaceRecipeBuilder.smelting(result.get(), 1)); } + protected FurnaceRecipeBuilder smelting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder smelting(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result.get(), count), id)); } protected FurnaceRecipeBuilder smelting(ItemStack result) { return builder(FurnaceRecipeBuilder.smelting(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected FurnaceRecipeBuilder smelting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(result, id)); } + protected FurnaceRecipeBuilder blasting(ItemLike result) { return builder(FurnaceRecipeBuilder.blasting(result, 1)); } protected FurnaceRecipeBuilder blasting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result, count))); } protected FurnaceRecipeBuilder blasting(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder blasting(Supplier result) { return builder(FurnaceRecipeBuilder.blasting(result.get(), 1)); } + protected FurnaceRecipeBuilder blasting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder blasting(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result.get(), count), id)); } protected FurnaceRecipeBuilder blasting(ItemStack result) { return builder(FurnaceRecipeBuilder.blasting(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected FurnaceRecipeBuilder blasting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(result, id)); } + protected FurnaceRecipeBuilder smoking(ItemLike result) { return builder(FurnaceRecipeBuilder.smoking(result, 1)); } protected FurnaceRecipeBuilder smoking(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result, count))); } protected FurnaceRecipeBuilder smoking(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder smoking(Supplier result) { return builder(FurnaceRecipeBuilder.smoking(result.get(), 1)); } + protected FurnaceRecipeBuilder smoking(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder smoking(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result.get(), count), id)); } protected FurnaceRecipeBuilder smoking(ItemStack result) { return builder(FurnaceRecipeBuilder.smoking(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected FurnaceRecipeBuilder smoking(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(result, id)); } + protected FurnaceRecipeBuilder campfire(ItemLike result) { return builder(FurnaceRecipeBuilder.campfire(result, 1)); } protected FurnaceRecipeBuilder campfire(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result, count))); } protected FurnaceRecipeBuilder campfire(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder campfire(Supplier result) { return builder(FurnaceRecipeBuilder.campfire(result.get(), 1)); } + protected FurnaceRecipeBuilder campfire(Supplier result, int count) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder campfire(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result.get(), count), id)); } protected FurnaceRecipeBuilder campfire(ItemStack result) { return builder(FurnaceRecipeBuilder.campfire(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected FurnaceRecipeBuilder campfire(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(result, id)); } + protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result) { return builder(ShapedRecipeBuilder.custom(serializer, result, 1)); } protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result, int count) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result, count))); } protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } + protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, Supplier result) { return builder(ShapedRecipeBuilder.custom(serializer, result.get(), 1)); } + protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, Supplier result, int count) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result.get(), count))); } + protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result.get(), count), id)); } protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemStack result) { return builder(ShapedRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, result, id)); } + protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result) { return builder(ShapelessRecipeBuilder.custom(serializer, result, 1)); } protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result, int count) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result, count))); } protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } + protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, Supplier result) { return builder(ShapelessRecipeBuilder.custom(serializer, result.get(), 1)); } + protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, Supplier result, int count) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result.get(), count))); } + protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result.get(), count), id)); } protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemStack result) { return builder(ShapelessRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, result, id)); } + protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result) { return builder(FurnaceRecipeBuilder.custom(serializer, result, 1)); } protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result, int count) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result, count))); } protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, Supplier result) { return builder(FurnaceRecipeBuilder.custom(serializer, result.get(), 1)); } + protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, Supplier result, int count) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result.get(), count), id)); } protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result) { return builder(FurnaceRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, result, id)); } + protected SpecialCraftingRecipeBuilder special(SimpleCraftingRecipeSerializer serializer, String id) { return builder(SpecialCraftingRecipeBuilder.builder(serializer, id)); } protected SpecialCraftingRecipeBuilder special(SimpleCraftingRecipeSerializer serializer, ResourceLocation id) { return builder(SpecialCraftingRecipeBuilder.builder(serializer, id)); } //@formatter:on @@ -125,6 +158,10 @@ protected InventoryChangeTrigger.TriggerInstance hasItem(ItemLike itemIn) { return hasItem(ItemPredicate.Builder.item().of(itemIn).build()); } + protected InventoryChangeTrigger.TriggerInstance hasItem(Supplier itemIn) { + return hasItem(ItemPredicate.Builder.item().of(itemIn.get()).build()); + } + protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { return hasItem(ItemPredicate.Builder.item().of(tagIn).build()); } diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java index fcdbede1..6b9ae66e 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java @@ -19,6 +19,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.function.Supplier; /** * Created by covers1624 on 28/12/20. @@ -46,6 +47,18 @@ public static ShapedRecipeBuilder builder(ItemLike result, int count, ResourceLo return builder(new ItemStack(result, count), id); } + public static ShapedRecipeBuilder builder(Supplier result) { + return builder(result.get(), 1); + } + + public static ShapedRecipeBuilder builder(Supplier result, int count) { + return builder(new ItemStack(result.get(), count)); + } + + public static ShapedRecipeBuilder builder(Supplier result, int count, ResourceLocation id) { + return builder(new ItemStack(result.get(), count), id); + } + public static ShapedRecipeBuilder builder(ItemStack result) { return builder(result, ForgeRegistries.ITEMS.getKey(result.getItem())); } @@ -86,6 +99,11 @@ public ShapedRecipeBuilder key(char key, ItemLike item) { return keyInternal(key, Ingredient.of(item)); } + public ShapedRecipeBuilder key(char key, Supplier item) { + addAutoCriteria(item.get()); + return keyInternal(key, Ingredient.of(item.get())); + } + public ShapedRecipeBuilder key(char key, Ingredient ingredient) { if (generateCriteria) { logger.warn("Criteria not automatically generated for raw ingredient.", new Throwable("Here, have a stack trace")); diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java index 4694124c..9569e51f 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java @@ -15,6 +15,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.function.Supplier; /** * Created by covers1624 on 28/12/20. @@ -41,6 +42,18 @@ public static ShapelessRecipeBuilder builder(ItemLike result, int count, Resourc return builder(new ItemStack(result, count), id); } + public static ShapelessRecipeBuilder builder(Supplier result) { + return builder(result.get(), 1); + } + + public static ShapelessRecipeBuilder builder(Supplier result, int count) { + return builder(new ItemStack(result.get(), count)); + } + + public static ShapelessRecipeBuilder builder(Supplier result, int count, ResourceLocation id) { + return builder(new ItemStack(result.get(), count), id); + } + public static ShapelessRecipeBuilder builder(ItemStack result) { return builder(result, ForgeRegistries.ITEMS.getKey(result.getItem())); } @@ -84,6 +97,19 @@ public ShapelessRecipeBuilder addIngredient(TagKey tag, int quantity) { return this; } + public ShapelessRecipeBuilder addIngredient(Supplier item) { + return addIngredient(item.get(), 1); + } + + public ShapelessRecipeBuilder addIngredient(Supplier item, int quantity) { + addAutoCriteria(item.get()); + Ingredient ingredient = Ingredient.of(item.get()); + for (int i = 0; i < quantity; ++i) { + ingredients.add(ingredient); + } + return this; + } + public ShapelessRecipeBuilder addIngredient(ItemLike item) { return addIngredient(item, 1); } From 1f9034a984343bbb535bd1657907fe8f0d31cac0 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Fri, 9 Feb 2024 20:40:26 +1100 Subject: [PATCH 18/87] Added Dynamic Texture data gen. --- .../lib/datagen/DynamicTextureProvider.java | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java diff --git a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java new file mode 100644 index 00000000..b251e4c0 --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java @@ -0,0 +1,185 @@ +package codechicken.lib.datagen; + +import codechicken.lib.gui.modular.lib.DynamicTextures; +import com.google.common.hash.Hashing; +import com.google.common.hash.HashingOutputStream; +import net.minecraft.Util; +import net.minecraft.data.CachedOutput; +import net.minecraft.data.DataGenerator; +import net.minecraft.data.DataProvider; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.resources.Resource; +import net.minecraftforge.common.data.ExistingFileHelper; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +/** + * This provider can be used to create a data generator that can generate various textures programmatically. + * The primary function is to convert dynamically resized textures into new fixed size textures. + *

+ * Created by brandon3055 on 07/09/2023 + */ +public class DynamicTextureProvider implements DataProvider { + private final DataGenerator gen; + private final ExistingFileHelper fileHelper; + private final String modid; + private final List results = new ArrayList<>(); + + public DynamicTextureProvider(DataGenerator gen, ExistingFileHelper fileHelper, String modid) { + this.gen = gen; + this.fileHelper = fileHelper; + this.modid = modid; + } + + /** + * If you are extending this provider, then override this method to add your textures. + */ + public void addTextures() { + } + + public void addDynamicTextures(DynamicTextures dynamicTextures) { + dynamicTextures.makeTextures(t -> { + addDynamicTexture(t.dynamicInput(), t.outputLocation(), t.width(), t.height(), t.topBorder(), t.leftBorder(), t.bottomBorder(), t.rightBorder()); + return t.guiTexturePath(); + }); + } + + public void addDynamicTexture(String dynamicInput, String outputTexture, int width, int height, int border) { + addDynamicTexture(dynamicInput, outputTexture, width, height, border, border, border, border); + } + + public void addDynamicTexture(String dynamicInput, String outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + addDynamicTexture(new ResourceLocation(modid, dynamicInput), new ResourceLocation(modid, outputTexture), width, height, topBorder, leftBorder, bottomBorder, rightBorder); + } + + public void addDynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputTexture, int width, int height, int border) { + addDynamicTexture(dynamicInput, outputTexture, width, height, border, border, border, border); + } + + public void addDynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + try { + if (!dynamicInput.getPath().endsWith(".png")) { + dynamicInput = new ResourceLocation(dynamicInput.getNamespace(), dynamicInput.getPath() + ".png"); + } + if (!outputTexture.getPath().endsWith(".png")) { + outputTexture = new ResourceLocation(outputTexture.getNamespace(), outputTexture.getPath() + ".png"); + } + + Resource inputResource = fileHelper.getResource(dynamicInput, PackType.CLIENT_RESOURCES); + PackOutput packOutput = gen.getPackOutput("assets/" + outputTexture.getNamespace()); + Path outputFile = packOutput.getOutputFolder().resolve(outputTexture.getPath()); + + BufferedImage input = ImageIO.read(inputResource.open()); + BufferedImage output = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); + Graphics2D graphics = output.createGraphics(); + + int texWidth = input.getWidth(); + int texHeight = input.getHeight(); + int trimWidth = texWidth - leftBorder - rightBorder; + int trimHeight = texHeight - topBorder - bottomBorder; + if (width <= texWidth) trimWidth = Math.min(trimWidth, width - rightBorder); + if (width <= 0 || height <= 0 || trimWidth <= 0 || trimHeight <= 0) throw new IllegalArgumentException("Invalid size parameters"); + + for (int x = 0; x < width; ) { + int rWidth = Math.min(width - x, trimWidth); + int trimU = 0; + if (x != 0) { + if (x + leftBorder + trimWidth <= width) { + trimU = leftBorder; + } else { + trimU = (texWidth - (width - x)); + } + } + + //Top & Bottom trim + bufferDynamic(graphics, input, x, 0, trimU, 0, rWidth, topBorder); + bufferDynamic(graphics, input, x, height - bottomBorder, trimU, texHeight - bottomBorder, rWidth, bottomBorder); + + rWidth = Math.min(width - x - leftBorder - rightBorder, trimWidth); + for (int y = 0; y < height; ) { + int rHeight = Math.min(height - y - topBorder - bottomBorder, trimHeight); + int trimV; + if (y + (texHeight - topBorder - bottomBorder) <= height) { + trimV = topBorder; + } else { + trimV = texHeight - (height - y); + } + + //Left & Right trim + if (x == 0 && y + topBorder < height - bottomBorder) { + bufferDynamic(graphics, input, 0, y + topBorder, 0, trimV, leftBorder, rHeight); + bufferDynamic(graphics, input, width - rightBorder, y + topBorder, trimU + texWidth - rightBorder, trimV, rightBorder, rHeight); + } + + //Core + if (y + topBorder < height - bottomBorder && x + leftBorder < width - rightBorder) { + bufferDynamic(graphics, input, x + leftBorder, y + topBorder, leftBorder, topBorder, rWidth, rHeight); + } + y += trimHeight; + } + x += trimWidth; + } + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ImageIO.write(output, "png", bos); + results.add(new GeneratorResult(bos.toByteArray(), outputFile)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private void bufferDynamic(Graphics2D graphics, BufferedImage image, int x, int y, int textureX, int textureY, int width, int height) { + graphics.drawImage(image, x, y, x + width, y + height, textureX, textureY, textureX + width, textureY + height, null); + } + + @Override + public CompletableFuture run(CachedOutput writer) { + addTextures(); + CompletableFuture[] futures = new CompletableFuture[results.size()]; + for (int i = 0; i < results.size(); i++) { + futures[i] = saveResult(writer, results.get(i)); + } + return CompletableFuture.allOf(futures); + } + + @SuppressWarnings ("UnstableApiUsage") + static CompletableFuture saveResult(CachedOutput arg, GeneratorResult result) { + return CompletableFuture.runAsync(() -> { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + HashingOutputStream hos = new HashingOutputStream(Hashing.sha1(), bos); + hos.write(result.fileBytes); + arg.writeIfNeeded(result.path, bos.toByteArray(), hos.hash()); + LOGGER.info("Saved file to {}", result.path); + } catch (IOException ex) { + LOGGER.error("Failed to save file to {}", result.path, ex); + } + + }, Util.backgroundExecutor()); + } + + @Override + public String getName() { + return "dynamic-textures:" + modid; + } + + private static class GeneratorResult { + private final byte[] fileBytes; + private final Path path; + + private GeneratorResult(byte[] fileBytes, Path filePath) { + this.fileBytes = fileBytes; + this.path = filePath; + } + } +} From 8d1bc29d378e079eb2948e39b019871d894a3e00 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Fri, 9 Feb 2024 20:41:43 +1100 Subject: [PATCH 19/87] Fixed gradientFillV and gradientFillH --- .../lib/gui/modular/lib/GuiRender.java | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java index a91b7bd8..bc13e1ec 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java @@ -235,14 +235,14 @@ public void gradientFillV(double xMin, double yMin, double xMax, double yMax, in */ public void gradientFillV(RenderType type, double xMin, double yMin, double xMax, double yMax, int topColour, int bottomColour) { VertexConsumer buffer = buffers().getBuffer(type); - float sA = a(topColour) / 255.0F; - float sR = r(topColour) / 255.0F; - float sG = g(topColour) / 255.0F; - float sB = b(topColour) / 255.0F; - float eA = a(bottomColour) / 255.0F; - float eR = r(bottomColour) / 255.0F; - float eG = g(bottomColour) / 255.0F; - float eB = b(bottomColour) / 255.0F; + float sA = a(topColour); + float sR = r(topColour); + float sG = g(topColour); + float sB = b(topColour); + float eA = a(bottomColour); + float eR = r(bottomColour); + float eG = g(bottomColour); + float eB = b(bottomColour); Matrix4f mat = pose.last().pose(); buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //R-B buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(sR, sG, sB, sA).endVertex(); //R-T @@ -263,14 +263,14 @@ public void gradientFillH(double xMin, double yMin, double xMax, double yMax, in */ public void gradientFillH(RenderType type, double xMin, double yMin, double xMax, double yMax, int leftColour, int rightColour) { VertexConsumer buffer = buffers().getBuffer(type); - float sA = a(leftColour) / 255.0F; - float sR = r(leftColour) / 255.0F; - float sG = g(leftColour) / 255.0F; - float sB = b(leftColour) / 255.0F; - float eA = a(rightColour) / 255.0F; - float eR = r(rightColour) / 255.0F; - float eG = g(rightColour) / 255.0F; - float eB = b(rightColour) / 255.0F; + float sA = a(leftColour); + float sR = r(leftColour); + float sG = g(leftColour); + float sB = b(leftColour); + float eA = a(rightColour); + float eR = r(rightColour); + float eG = g(rightColour); + float eB = b(rightColour); Matrix4f mat = pose.last().pose(); buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //R-B buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(eR, eG, eB, eA).endVertex(); //R-T From c59e0a7cf0a4e94086b798554d549d9e0929062c Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Tue, 13 Feb 2024 15:06:49 +1100 Subject: [PATCH 20/87] Added missing localization and added IItemHandler support to ModularSlot --- .../15d5dd4ace2ad25407a17728f6fbc07b246efd63 | 6 +++--- .../assets/codechickenlib/lang/en_us.json | 11 ++++++++++- .../data/codechickenlib/lang/en_us.json | 11 ++++++++++- .../lib/gui/modular/elements/GuiEnergyBar.java | 10 +++++----- .../lib/gui/modular/elements/GuiFluidTank.java | 12 ++++++------ .../lib/internal/DataGenerators.java | 10 ++++++++++ .../container/modular/ModularSlot.java | 17 ++++++++++++++--- 7 files changed, 58 insertions(+), 19 deletions(-) diff --git a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 index 9a6224e4..5c59c3eb 100644 --- a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 +++ b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 @@ -1,3 +1,3 @@ -// 1.20.1 2023-09-08T20:35:35.335872512 codechickenlib Languages: en_us -ce1ce42a962941336b9de69689e94a97219ad7d9 assets/codechickenlib/lang/en_us.json -ce1ce42a962941336b9de69689e94a97219ad7d9 data/codechickenlib/lang/en_us.json +// 1.20.1 2024-02-13T15:00:40.20834201 codechickenlib Languages: en_us +d535acbe9649e564744ed63aef209ce1508ec451 assets/codechickenlib/lang/en_us.json +d535acbe9649e564744ed63aef209ce1508ec451 data/codechickenlib/lang/en_us.json diff --git a/src/main/generated/assets/codechickenlib/lang/en_us.json b/src/main/generated/assets/codechickenlib/lang/en_us.json index ccfb00ae..b647596b 100644 --- a/src/main/generated/assets/codechickenlib/lang/en_us.json +++ b/src/main/generated/assets/codechickenlib/lang/en_us.json @@ -7,5 +7,14 @@ "ccl.commands.killall.fail": "Found no entities.", "ccl.commands.killall.fail.player": "You cannot kill players with this command.", "ccl.commands.killall.success": "Killed %s entities.", - "ccl.commands.killall.success.line": "Killed %s" + "ccl.commands.killall.success.line": "Killed %s", + "ccl.energy_bar.capacity": "Capacity:", + "ccl.energy_bar.energy_storage": "Energy Storage", + "ccl.energy_bar.rf": "RF", + "ccl.energy_bar.stored": "Stored:", + "ccl.fluid_tank.capacity": "Capacity:", + "ccl.fluid_tank.contains": "Contains:", + "ccl.fluid_tank.fluid_storage": "Fluid Storage", + "ccl.fluid_tank.mb": "mB", + "ccl.fluid_tank.stored": "Stored:" } \ No newline at end of file diff --git a/src/main/generated/data/codechickenlib/lang/en_us.json b/src/main/generated/data/codechickenlib/lang/en_us.json index ccfb00ae..b647596b 100644 --- a/src/main/generated/data/codechickenlib/lang/en_us.json +++ b/src/main/generated/data/codechickenlib/lang/en_us.json @@ -7,5 +7,14 @@ "ccl.commands.killall.fail": "Found no entities.", "ccl.commands.killall.fail.player": "You cannot kill players with this command.", "ccl.commands.killall.success": "Killed %s entities.", - "ccl.commands.killall.success.line": "Killed %s" + "ccl.commands.killall.success.line": "Killed %s", + "ccl.energy_bar.capacity": "Capacity:", + "ccl.energy_bar.energy_storage": "Energy Storage", + "ccl.energy_bar.rf": "RF", + "ccl.energy_bar.stored": "Stored:", + "ccl.fluid_tank.capacity": "Capacity:", + "ccl.fluid_tank.contains": "Contains:", + "ccl.fluid_tank.fluid_storage": "Fluid Storage", + "ccl.fluid_tank.mb": "mB", + "ccl.fluid_tank.stored": "Stored:" } \ No newline at end of file diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java index 478e86a8..f91ce143 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java @@ -54,27 +54,27 @@ public static EnergyBar simpleBar(@NotNull GuiParent parent) { public static BiFunction> defaultFormatter() { return (energy, capacity) -> { List tooltip = new ArrayList<>(); - tooltip.add(Component.translatable("energy_bar.polylib.energy_storage").withStyle(DARK_AQUA)); + tooltip.add(Component.translatable("ccl.energy_bar.energy_storage").withStyle(DARK_AQUA)); boolean shift = Screen.hasShiftDown(); - tooltip.add(Component.translatable("energy_bar.polylib.capacity") + tooltip.add(Component.translatable("ccl.energy_bar.capacity") .withStyle(GOLD) .append(" ") .append(Component.literal(shift ? FormatUtil.addCommas(capacity) : FormatUtil.formatNumber(capacity)) .withStyle(GRAY) .append(" ") - .append(Component.translatable("energy_bar.polylib.rf") + .append(Component.translatable("ccl.energy_bar.rf") .withStyle(GRAY) ) ) ); - tooltip.add(Component.translatable("energy_bar.polylib.stored") + tooltip.add(Component.translatable("ccl.energy_bar.stored") .withStyle(GOLD) .append(" ") .append(Component.literal(shift ? FormatUtil.addCommas(energy) : FormatUtil.formatNumber(energy)) .withStyle(GRAY) ) .append(" ") - .append(Component.translatable("energy_bar.polylib.rf") + .append(Component.translatable("ccl.energy_bar.rf") .withStyle(GRAY) ) .append(Component.literal(String.format(" (%.2f%%)", ((double) energy / (double) capacity) * 100D)) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java index a2d4eb9a..12ce2600 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java @@ -182,9 +182,9 @@ private double computeGaugeSpacing() { public static BiFunction> defaultFormatter() { return (fluidStack, capacity) -> { List tooltip = new ArrayList<>(); - tooltip.add(Component.translatable("fluid_tank.polylib.fluid_storage").withStyle(DARK_AQUA)); + tooltip.add(Component.translatable("ccl.fluid_tank.fluid_storage").withStyle(DARK_AQUA)); if (!fluidStack.isEmpty()) { - tooltip.add(Component.translatable("fluid_tank.polylib.contains") + tooltip.add(Component.translatable("ccl.fluid_tank.contains") .withStyle(GOLD) .append(" ") .append(fluidStack.getDisplayName().copy() @@ -195,25 +195,25 @@ public static BiFunction> defaultFormatter() { ); } - tooltip.add(Component.translatable("fluid_tank.polylib.capacity") + tooltip.add(Component.translatable("ccl.fluid_tank.capacity") .withStyle(GOLD) .append(" ") .append(Component.literal(FormatUtil.addCommas(capacity)) .withStyle(GRAY) .append(" ") - .append(Component.translatable("fluid_tank.polylib.mb") + .append(Component.translatable("ccl.fluid_tank.mb") .withStyle(GRAY) ) ) ); - tooltip.add(Component.translatable("fluid_tank.polylib.stored") + tooltip.add(Component.translatable("ccl.fluid_tank.stored") .withStyle(GOLD) .append(" ") .append(Component.literal(FormatUtil.addCommas(fluidStack.getAmount())) .withStyle(GRAY) ) .append(" ") - .append(Component.translatable("fluid_tank.polylib.mb") + .append(Component.translatable("ccl.fluid_tank.mb") .withStyle(GRAY) ) .append(Component.literal(String.format(" (%.2f%%)", ((double) fluidStack.getAmount() / (double) capacity) * 100D)) diff --git a/src/main/java/codechicken/lib/internal/DataGenerators.java b/src/main/java/codechicken/lib/internal/DataGenerators.java index 62673c3f..89cad861 100644 --- a/src/main/java/codechicken/lib/internal/DataGenerators.java +++ b/src/main/java/codechicken/lib/internal/DataGenerators.java @@ -153,6 +153,16 @@ protected void addTranslations() { addServer("ccl.commands.killall.success.line", "Killed %s"); addServer("ccl.commands.count.fail", "Found no entities."); addServer("ccl.commands.count.total", "Found %s entities."); + + addServer("ccl.energy_bar.energy_storage", "Energy Storage"); + addServer("ccl.energy_bar.capacity", "Capacity:"); + addServer("ccl.energy_bar.stored", "Stored:"); + addServer("ccl.energy_bar.rf", "RF"); + addServer("ccl.fluid_tank.fluid_storage", "Fluid Storage"); + addServer("ccl.fluid_tank.capacity", "Capacity:"); + addServer("ccl.fluid_tank.stored", "Stored:"); + addServer("ccl.fluid_tank.mb", "mB"); + addServer("ccl.fluid_tank.contains", "Contains:"); } } } diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java index bfa02872..c652f2cd 100644 --- a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java @@ -4,6 +4,9 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.SlotItemHandler; +import net.minecraftforge.items.wrapper.InvWrapper; import java.util.function.*; @@ -13,7 +16,7 @@ *

* Created by brandon3055 on 10/09/2023 */ -public class ModularSlot extends Slot { +public class ModularSlot extends SlotItemHandler { private boolean canPlace = true; private boolean checkContainer = true; private Supplier enabled = () -> true; @@ -23,11 +26,19 @@ public class ModularSlot extends Slot { private BiConsumer onSet = (oldStack, newStack) -> {}; public ModularSlot(Container container, int index) { - this(container, index, 0, 0); + this(new InvWrapper(container), index, 0, 0); + } + + public ModularSlot(IItemHandler itemHandler, int index) { + this(itemHandler, index, 0, 0); } public ModularSlot(Container container, int index, int xPos, int yPos) { - super(container, index, xPos, yPos); + super(new InvWrapper(container), index, xPos, yPos); + } + + public ModularSlot(IItemHandler itemHandler, int index, int xPos, int yPos) { + super(itemHandler, index, xPos, yPos); } /** From 30e6cb841570e8208038849801ccd97f7394d1d0 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sat, 2 Mar 2024 01:08:45 +1100 Subject: [PATCH 21/87] Dev/gui improvements (#455) * A bunch of modular GUI fixes / improvements. Fixed some issues with GuiContextMenu Fixed GuiText depth not accounting for underline's additional z offset. Fixed slot overlay rendering. Fixed GuiEntityRenderer. Added filtering to GuiList. Support line breaks in tooltip translations. Made some improvements to text field suggestions. * Fixed "Between" constraint and ModularSlot place item validation. * Added a little more functionality to GuiSlots * Move JEI compat to internal package and added JEI runtime dep. --- build.gradle | 1 + .../codechicken/lib/compat/JEIPlugin.java | 37 ------ .../lib/gui/modular/ModularGui.java | 39 +++--- .../lib/gui/modular/ModularGuiContainer.java | 27 +++- .../lib/gui/modular/ModularGuiScreen.java | 2 +- .../gui/modular/elements/GuiContextMenu.java | 51 +++++-- .../lib/gui/modular/elements/GuiElement.java | 104 ++++++++++++--- .../modular/elements/GuiEntityRenderer.java | 9 +- .../gui/modular/elements/GuiItemStack.java | 2 +- .../lib/gui/modular/elements/GuiList.java | 13 ++ .../lib/gui/modular/elements/GuiSlots.java | 124 +++++++++++++++--- .../lib/gui/modular/elements/GuiText.java | 2 +- .../gui/modular/elements/GuiTextField.java | 21 ++- .../lib/gui/modular/lib/TooltipHandler.java | 3 +- .../modular/lib/geometry/ConstraintImpl.java | 4 +- .../lib/internal/compat/JEIPlugin.java | 87 ++++++++++++ .../container/modular/ModularSlot.java | 2 +- .../resources/META-INF/accesstransformer.cfg | 1 + 18 files changed, 409 insertions(+), 120 deletions(-) delete mode 100644 src/main/java/codechicken/lib/compat/JEIPlugin.java create mode 100644 src/main/java/codechicken/lib/internal/compat/JEIPlugin.java diff --git a/build.gradle b/build.gradle index 6c3b0857..e4dea2da 100644 --- a/build.gradle +++ b/build.gradle @@ -85,6 +85,7 @@ dependencies { compileOnly(fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")) compileOnly(fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")) + runtimeOnly(fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")) } test { diff --git a/src/main/java/codechicken/lib/compat/JEIPlugin.java b/src/main/java/codechicken/lib/compat/JEIPlugin.java deleted file mode 100644 index c9608464..00000000 --- a/src/main/java/codechicken/lib/compat/JEIPlugin.java +++ /dev/null @@ -1,37 +0,0 @@ -package codechicken.lib.compat; - -import codechicken.lib.CodeChickenLib; -import codechicken.lib.gui.modular.ModularGuiContainer; -import mezz.jei.api.IModPlugin; -import mezz.jei.api.JeiPlugin; -import mezz.jei.api.gui.handlers.IGuiContainerHandler; -import mezz.jei.api.registration.IGuiHandlerRegistration; -import net.minecraft.client.renderer.Rect2i; -import net.minecraft.resources.ResourceLocation; - -import java.util.List; - -/** - * Created by brandon3055 on 31/12/2023 - */ -@JeiPlugin -public class JEIPlugin implements IModPlugin { - private static final ResourceLocation ID = new ResourceLocation(CodeChickenLib.MOD_ID, "jei_plugin"); - - public JEIPlugin() {} - - @Override - public ResourceLocation getPluginUid() { - return ID; - } - - @Override - public void registerGuiHandlers(IGuiHandlerRegistration registration) { - registration.addGuiContainerHandler(ModularGuiContainer.class, new IGuiContainerHandler<>() { - @Override - public List getGuiExtraAreas(ModularGuiContainer screen) { - return screen.getModularGui().getJeiExclusions().map(e -> e.getRectangle().toRect2i()).toList(); - } - }); - } -} diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGui.java b/src/main/java/codechicken/lib/gui/modular/ModularGui.java index b0a9d527..242ca4c0 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGui.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGui.java @@ -15,18 +15,15 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.util.TriConsumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.function.Consumer; -import java.util.stream.Stream; /** * The modular gui system is built around "Gui Elements" but those elements need to be rendered by a base parent element. That's what this class is. @@ -68,7 +65,7 @@ public class ModularGui implements GuiParent { private final List> preKeyPressListeners = new ArrayList<>(); private final List> postKeyPressListeners = new ArrayList<>(); - private final List> jeiExclusions = new ArrayList<>(); + private int jeiHighlightTime = 0; /** * @param provider The gui builder that will be used to construct this modular gui when the screen is initialized. @@ -208,6 +205,7 @@ public boolean vanillaSlotRendering() { * @param buffers BufferSource can be retried from {@link GuiGraphics} * @return A new {@link GuiRender} for the current render call. */ + @Deprecated //If you have the GuiGraphics, use GuiRender#convert to ensure the underlying PoseStack is carried over. That will ensure things like the JEI overlay will be rendered at a public GuiRender createRender(MultiBufferSource.BufferSource buffers) { return new GuiRender(mc, buffers); } @@ -216,7 +214,7 @@ public GuiRender createRender(MultiBufferSource.BufferSource buffers) { * Primary render method for ModularGui. The screen implementing ModularGui must call this in its render method. * Followed by the {@link #renderOverlay(GuiRender, float)} method to handle overlay rendering. * - * @param render A new gui render call should be constructed for each frame via {@link #createRender(MultiBufferSource.BufferSource)} + * @param render GuiRender instance converted from Minecraft's {@link GuiGraphics} via {@link GuiRender#convert(GuiGraphics)} */ public void render(GuiRender render, float partialTicks) { root.clearGeometryCache(); @@ -260,6 +258,7 @@ public void tick() { tickListeners.forEach(Runnable::run); root.tick(mouseX, mouseY); CursorHelper.setCursor(newCursor); + if (jeiHighlightTime > 0) jeiHighlightTime--; } /** @@ -524,26 +523,20 @@ public void setCursor(ResourceLocation cursor) { this.newCursor = cursor; } - /** - * Add an element to the list of jei exclusions. - * Use this for any elements that render outside the normal gui bounds. - * This will ensure JEI does not try to render on top of these elements. - */ - public void jeiExclude(GuiElement element) { - if (!jeiExclusions.contains(element)) { - jeiExclusions.add(element); - } + public List> getJeiExclusions() { + return root.addJeiExclusions(new ArrayList<>()); } - /** - * Remove an element from the list of jei exclusions. - */ - public void removeJEIExclude(GuiElement element) { - jeiExclusions.remove(element); + public List> getJeiDropTargets() { + return root.addJeiDropTargets(new ArrayList<>()); + } + + public void setJeiHighlightTime(int jeiHighlightTime) { + this.jeiHighlightTime = jeiHighlightTime; } - public FastStream> getJeiExclusions() { - return FastStream.of(jeiExclusions).filter(GuiElement::isEnabled); + public int getJeiHighlightTime() { + return jeiHighlightTime; } /** diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java index 0063b6a6..8e74eba6 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -29,6 +29,10 @@ public class ModularGuiContainer extends AbstractContainerScreen implements ContainerScreenAccess { public final ModularGui modularGui; + /** + * Flag used to disable vanilla slot highlight rendering. + * */ + private boolean renderingSlots = false; public ModularGuiContainer(T containerMenu, Inventory inventory, ContainerGuiProvider provider) { super(containerMenu, inventory, Component.empty()); @@ -74,7 +78,7 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float if (modularGui.renderBackground()) { renderBackground(graphics); } - GuiRender render = modularGui.createRender(graphics.bufferSource()); + GuiRender render = GuiRender.convert(graphics);//modularGui.createRender(graphics.bufferSource()); modularGui.render(render, partialTicks); super.render(graphics, mouseX, mouseY, partialTicks); @@ -125,7 +129,7 @@ protected boolean handleFloatingItemRender(GuiRender render, int mouseX, int mou protected boolean renderHoveredStackToolTip(GuiRender guiGraphics, int mouseX, int mouseY) { if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) { GuiElement handler = modularGui.getSlotHandler(hoveredSlot); - if (handler != null && handler.blockMouseOver(handler, mouseX, mouseY)) { + if (handler != null && (handler.blockMouseOver(handler, mouseX, mouseY) || !handler.isMouseOver())) { return false; } ItemStack itemStack = this.hoveredSlot.getItem(); @@ -191,7 +195,11 @@ protected void renderBg(GuiGraphics guiGraphics, float f, int i, int j) { @Override public void renderSlot(GuiGraphics guiGraphics, Slot slot) { - if (modularGui.vanillaSlotRendering()) super.renderSlot(guiGraphics, slot); + if (modularGui.vanillaSlotRendering()) { + super.renderSlot(guiGraphics, slot); + } else { + renderingSlots = true; + } } //Modular gui friendly version of the slot render @@ -240,8 +248,21 @@ public void renderSlot(GuiRender render, Slot slot) { } } + @Override + public boolean isHovering(Slot pSlot, double pMouseX, double pMouseY) { + boolean ret = super.isHovering(pSlot, pMouseX, pMouseY); + //Override the isHovering check before renderSlotHighlight is called. + if (ret && renderingSlots && pSlot.isActive()) { + //This breaks the default hoveredSlot assignment, so we need to handle that here. + hoveredSlot = pSlot; + return false; + } + return ret; + } + @Override //Disable vanilla title and inventory name rendering protected void renderLabels(GuiGraphics guiGraphics, int i, int j) { + renderingSlots = false; } @Override diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java index 10fd1060..2e6251fd 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java @@ -67,7 +67,7 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float if (modularGui.renderBackground()) { renderBackground(graphics); } - GuiRender render = modularGui.createRender(graphics.bufferSource()); + GuiRender render = GuiRender.convert(graphics); modularGui.render(render, partialTicks); modularGui.renderOverlay(render, partialTicks); } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java index 77c2b343..704c701b 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java @@ -3,13 +3,9 @@ import codechicken.lib.gui.modular.ModularGui; import codechicken.lib.gui.modular.lib.Constraints; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import net.covers1624.quack.collection.FastStream; import net.minecraft.network.chat.Component; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.function.BiFunction; import java.util.function.Supplier; @@ -26,14 +22,17 @@ public class GuiContextMenu extends GuiElement { private BiFunction, GuiButton> buttonBuilder = (menu, label) -> GuiButton.flatColourButton(menu, label, hover -> hover ? 0xFF475b6a : 0xFF151515).constrain(HEIGHT, literal(12)); - private final Map, Runnable> options = new HashMap<>(); + private final Map, Runnable> options = new LinkedHashMap<>(); private final Map, Supplier>> tooltips = new HashMap<>(); private final List buttons = new ArrayList<>(); private boolean closeOnItemClicked = true; private boolean closeOnOutsideClick = true; + private boolean actionOnClick = false; public GuiContextMenu(ModularGui gui) { super(gui.getRoot()); + jeiExclude(); + setOpaque(true); } public static GuiContextMenu tooltipStyleMenu(GuiParent parent) { @@ -52,6 +51,16 @@ public GuiContextMenu setCloseOnOutsideClick(boolean closeOnOutsideClick) { return this; } + /** + * By default, the option action fires on mouse button release (like pretty much any UI button in existence) + * Calling this will change that to action on mouse button press, (What minecraft uses for its buttons) + */ + public GuiContextMenu actionOnClick() { + this.actionOnClick = true; + rebuildButtons(); + return this; + } + /** * Only height should be constrained, with will be set automatically to accommodate the provided label. */ @@ -87,16 +96,20 @@ private void rebuildButtons() { //Menu options can be dynamic so the width constraint needs to be dynamic. //This is probably a little expensive, but its only while a context menu is open. - constrain(WIDTH, dynamic(() -> FastStream.of(options.keySet()).map(Supplier::get).intSum(font()::width) + 6D + 4D)); + constrain(WIDTH, dynamic(() -> options.keySet().stream().mapToInt(e -> font().width(e.get())).max().orElse(0) + 6D + 4D)); double height = 3; for (Supplier label : options.keySet()) { Runnable action = options.get(label); GuiButton button = buttonBuilder.apply(this, label) - .onPress(action) .constrain(TOP, relative(get(TOP), height)) .constrain(LEFT, relative(get(LEFT), 3)) .constrain(RIGHT, relative(get(RIGHT), -3)); + if (actionOnClick) { + button.onClick(action); + } else { + button.onPress(action); + } if (tooltips.containsKey(label)) { button.setTooltip(tooltips.get(label)); } @@ -111,10 +124,12 @@ private void rebuildButtons() { public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { consumed = super.mouseClicked(mouseX, mouseY, button, consumed); if (isMouseOver() || consumed) { - if (consumed && closeOnItemClicked) { - close(); + if (actionOnClick) { + if (consumed && closeOnItemClicked) { + close(); + } + return true; } - return true; } else if (closeOnOutsideClick) { close(); return true; @@ -123,6 +138,20 @@ public boolean mouseClicked(double mouseX, double mouseY, int button, boolean co return consumed; } + @Override + public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + consumed = super.mouseReleased(mouseX, mouseY, button, consumed); + if (isMouseOver() || consumed) { + if (!actionOnClick) { + if (consumed && closeOnItemClicked) { + close(); + } + return true; + } + } + return consumed; + } + public void close() { getParent().removeChild(this); } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java index 8942e51f..4ea5e1ac 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java @@ -1,5 +1,6 @@ package codechicken.lib.gui.modular.elements; +import codechicken.lib.colour.ColourARGB; import com.google.common.collect.Lists; import com.mojang.blaze3d.vertex.PoseStack; import codechicken.lib.gui.modular.ModularGui; @@ -13,6 +14,7 @@ import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -20,6 +22,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.function.Consumer; import java.util.function.Supplier; /** @@ -68,6 +71,9 @@ public class GuiElement> extends ConstrainedGeometry private Supplier> toolTip = null; private Rectangle renderCull = Rectangle.create(Position.create(0, 0), () -> (double) screenWidth, () -> (double) screenHeight); + private Consumer jeiDropConsumer = null; + private boolean isJeiExcluded = false; + /** * @param parent parent {@link GuiParent}. */ @@ -220,6 +226,10 @@ public T setEnableToolTip(Supplier enableToolTip) { return SneakyUtils.unsafeCast(this); } + public boolean isTooltipEnabled() { + return enableToolTip.get(); + } + @Override public boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { return getParent().blockMouseOver(element, mouseX, mouseY); @@ -265,24 +275,6 @@ public String toString() { '}'; } - /** - * Add this element to the list of jei exclusions. - * Use this for any elements that render outside the normal gui bounds. - * This will ensure JEI does not try to render on top of these elements. - */ - public T jeiExclude() { - getModularGui().jeiExclude(this); - return SneakyUtils.unsafeCast(this); - } - - /** - * Remove this element from the list of jei exclusions. - */ - public T removeJEIExclude() { - getModularGui().removeJEIExclude(this); - return SneakyUtils.unsafeCast(this); - } - //=== Render / Update ===// /** @@ -422,8 +414,12 @@ public boolean renderOverlay(GuiRender render, double mouseX, double mouseY, flo return consumed || (showToolTip() && renderTooltip(render, mouseX, mouseY)); } - private boolean showToolTip() { - return isMouseOver() && enableToolTip.get() && hoverTime() >= getTooltipDelay(); + /** + * @return true if all conditions are bet for this element to be rendering its tool tip. + * Meaning mouse is over the element, hover time has elapsed and tooltip is enabled. + */ + public boolean showToolTip() { + return isMouseOver() && isTooltipEnabled() && hoverTime() >= getTooltipDelay(); } /** @@ -488,4 +484,72 @@ public T setTooltip(@Nullable Supplier> tooltip) { this.toolTip = tooltip; return SneakyUtils.unsafeCast(this); } + + //=== JEI Integration ===// + + /** + * Add this element to the list of jei exclusions. + * Use this for any elements that render outside the normal gui bounds. + * This will ensure JEI does not try to render on top of these elements. + */ + public T jeiExclude() { + isJeiExcluded = true; + return SneakyUtils.unsafeCast(this); + } + + public T setJeiExcluded(boolean jeiExcluded) { + isJeiExcluded = jeiExcluded; + return SneakyUtils.unsafeCast(this); + } + + public boolean isJeiExcluded() { + return isJeiExcluded; + } + + /** + * Allows you get notified when a player drags and drops an ItemStack from jai onto this element. + * If using the standard highlight then you should call this after adding any other required child elements to ensure the highlight is on top. + */ + public T setJeiDropTarget(Consumer onDrop, boolean installStandardHighlight) { + jeiDropConsumer = onDrop; + if (installStandardHighlight) { + GuiRectangle highlight = new GuiRectangle(this) + .setEnabled(() -> getModularGui().getJeiHighlightTime() > 0) + .fill(() -> ColourARGB.packARGB(0, 0xFF, 0, Math.min(getModularGui().getJeiHighlightTime() * 2, 0x50))); + Constraints.bind(highlight, this); + } + return SneakyUtils.unsafeCast(this); + } + + public Consumer getJeiDropConsumer() { + return jeiDropConsumer; + } + + public boolean isJeiDropTarget() { + return jeiDropConsumer != null; + } + + public List> addJeiExclusions(List> list) { + if (isJeiExcluded()) { + list.add(this); + } + for (GuiElement child : childElements) { + if (child.isEnabled()) { + child.addJeiExclusions(list); + } + } + return list; + } + + public List> addJeiDropTargets(List> list) { + if (isJeiDropTarget()) { + list.add(this); + } + for (GuiElement child : childElements) { + if (child.isEnabled()) { + child.addJeiDropTargets(list); + } + } + return list; + } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java index ac09f9b3..f3e3b0db 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java @@ -160,7 +160,9 @@ public GuiEntityRenderer setForce2dSize(boolean force2dSize) { @Override public double getBackgroundDepth() { Rectangle rect = getRectangle(); + if (invalidEntity || entity == null) return 0.01; float scale = (float) (force2dSize ? (Math.min(rect.height() / entity.getBbHeight(), rect.width() / entity.getBbWidth())) : rect.height() / entity.getBbHeight()); + if (Float.isInfinite(scale)) scale = 1; return scale * 2; } @@ -182,6 +184,11 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo } else { renderEntityInInventoryWithRotation(render, xPos, yPos, scale, rotation, living); } + } else { + Quaternionf quaternionf = new Quaternionf().rotateZ((float)Math.PI); + Quaternionf quaternionf1 = Axis.YP.rotationDegrees(rotation); + quaternionf.mul(quaternionf1); + renderEntityInInventory(render, xPos, yPos, scale, quaternionf, quaternionf1, entity); } } } catch (Throwable e) { @@ -242,7 +249,7 @@ public static void renderEntityInInventoryWithRotation(GuiRender render, double living.yHeadRot = f6; } - public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, LivingEntity pEntity) { + public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, Entity pEntity) { render.pose().pushPose(); render.pose().translate(pX, pY, 50.0D); render.pose().mulPoseMatrix((new Matrix4f()).scaling((float)pScale, (float)pScale, (float)(-pScale))); diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java index 2ff85905..099d2c8a 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java @@ -92,7 +92,7 @@ public double getStackSize() { @Override public double getBackgroundDepth() { - return getStackSize(); + return getStackSize() * 2; } @Override diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java index 909d5d53..fe26fb75 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java @@ -9,6 +9,7 @@ import java.util.*; import java.util.function.BiFunction; +import java.util.function.Predicate; import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; @@ -35,6 +36,7 @@ public class GuiList extends GuiElement> { */ public boolean enableScissor = true; private double yScrollPos = 0; + private double lastWidth = 0; private double contentHeight = 0; private double itemSpacing = 1; private boolean rebuild = true; @@ -43,6 +45,7 @@ public class GuiList extends GuiElement> { private final List listContent = new ArrayList<>(); private final Map> elementMap = new HashMap<>(); private final LinkedList> visible = new LinkedList<>(); + private Predicate filter = e -> true; private BiFunction, E, ? extends GuiElement> displayBuilder = (parent, e) -> { GuiText text = new GuiText(parent, () -> Component.literal(String.valueOf(e))).setWrap(true); @@ -83,6 +86,11 @@ public GuiList setDisplayBuilder(BiFunction, E, ? extends GuiEleme return this; } + public GuiList setFilter(Predicate filter) { + this.filter = filter; + return this; + } + public GuiList setItemSpacing(double itemSpacing) { this.itemSpacing = itemSpacing; return this; @@ -127,6 +135,10 @@ public double hiddenSize() { @Override public void tick(double mouseX, double mouseY) { + if (lastWidth != xSize()) { + lastWidth = xSize(); + markDirty(); + } if (rebuild) { rebuildElements(); } @@ -138,6 +150,7 @@ public void rebuildElements() { elementMap.clear(); for (E item : listContent) { + if (!filter.test(item)) continue; GuiElement next = displayBuilder.apply(this, item); next.constrain(LEFT, match(get(LEFT))); next.constrain(RIGHT, match(get(RIGHT))); diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java index 9ce861eb..aa21af09 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -7,9 +7,12 @@ import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GeoParam; import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Position; import codechicken.lib.gui.modular.sprite.CCGuiTextures; import codechicken.lib.gui.modular.sprite.Material; +import net.covers1624.quack.collection.FastStream; import net.minecraft.world.inventory.Slot; +import org.apache.logging.log4j.util.TriConsumer; import org.jetbrains.annotations.NotNull; import java.util.function.Function; @@ -38,9 +41,10 @@ public class GuiSlots extends GuiElement implements BackgroundRender { private final SlotGroup slots; private final ContainerScreenAccess screenAccess; - private Material slotTexture = CCGuiTextures.getUncached("widgets/slot"); - private Function slotIcons = slot -> null; - private Function highlightColour = slot -> 0x80ffffff; + private Function slotTexture = slot -> CCGuiTextures.getUncached("widgets/slot"); + private Function slotIcons = slot -> null; + private Function highlightColour = slot -> 0x80ffffff; + private TriConsumer slotOverlay = null; private int xSlotSpacing = 0; private int ySlotSpacing = 0; @@ -78,6 +82,7 @@ public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAcc } updateSlots(parent.getModularGui().getRoot()); + setZStacking(false); } //=== Construction Helpers ===// @@ -126,7 +131,7 @@ public static PlayerWithArmor playerWithArmor(@NotNull GuiParent parent, Cont GuiSlots armor = new GuiSlots(container, screenAccess, armorSlots, 1) .setYSlotSpacing(groupSpacing / 3) - .setEmptyIcon(index -> slotIcons ? ARMOR_SLOTS[index] : null) + .setEmptyIconI(index -> slotIcons ? ARMOR_SLOTS[index] : null) .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); @@ -155,7 +160,7 @@ public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerSc GuiSlots armor = new GuiSlots(container, screenAccess, armorSlots, 1) .setYSlotSpacing(groupSpacing / 3) - .setEmptyIcon(index -> slotIcons ? ARMOR_SLOTS[index] : null) + .setEmptyIconI(index -> slotIcons ? ARMOR_SLOTS[index] : null) .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); @@ -168,7 +173,7 @@ public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerSc .constrain(LEFT, match(main.get(LEFT))); GuiSlots offHand = new GuiSlots(container, screenAccess, offhandSlots, 1) - .setEmptyIcon(index -> slotIcons ? OFF_HAND_SLOT : null) + .setEmptyIconI(index -> slotIcons ? OFF_HAND_SLOT : null) .constrain(TOP, match(bar.get(TOP))) .constrain(LEFT, relative(bar.get(RIGHT), groupSpacing)); @@ -181,10 +186,28 @@ public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerSc * Allows you to use a custom slot texture, The default is the standard vanilla slot. */ public GuiSlots setSlotTexture(Material slotTexture) { + this.slotTexture = e -> slotTexture; + return this; + } + + /** + * Allows you to use a custom per-slot slot textures, The default is the standard vanilla texture for all slots. + */ + public GuiSlots setSlotTexture(Function slotTexture) { this.slotTexture = slotTexture; return this; } + /** + * Allows you to use a custom per-slot slot textures, The default is the standard vanilla texture for all slots. + *

+ * Similar to {@link #setSlotTexture(Function)} except you are given the index of the slot within the {@link GuiSlots} element. + */ + public GuiSlots setSlotTextureI(Function slotTexture) { + this.slotTexture = slot -> slotTexture.apply(slots.indexOf(slot) - firstSlot); + return this; + } + /** * Sets a custom slot highlight colour (The highlight you get when your cursor is over a slot.) */ @@ -196,11 +219,22 @@ public GuiSlots setHighlightColour(int highlightColour) { * Allows you to set per-slot highlight colours, The integer passed to the function is the * index of the slot within the {@link SlotGroup} */ - public GuiSlots setHighlightColour(Function highlightColour) { + public GuiSlots setHighlightColour(Function highlightColour) { this.highlightColour = highlightColour; return this; } + /** + * Allows you to set per-slot highlight colours, The integer passed to the function is the + * index of the slot within the {@link SlotGroup} + *

+ * Similar to {@link #setHighlightColour(Function)} except you are given the index of the slot within the {@link GuiSlots} element. + */ + public GuiSlots setHighlightColourI(Function highlightColour) { + this.highlightColour = slot -> highlightColour.apply(slots.indexOf(slot) - firstSlot); + return this; + } + /** * Applies a single empty slot icon to all slots. * Recommended texture size is 16x16 @@ -215,11 +249,48 @@ public GuiSlots setEmptyIcon(Material texture) { * * @param slotIcons A function that is given the slot index within the {@link SlotGroup}, and should return a material or null. */ - public GuiSlots setEmptyIcon(Function slotIcons) { + public GuiSlots setEmptyIcon(Function slotIcons) { this.slotIcons = slotIcons; return this; } + /** + * Allows you to provide a texture to be rendered in each slot when the slot is empty. + * Recommended texture size is 16x16 + *

+ * Similar to {@link #setEmptyIcon(Function)} except you are given the index of the slot within the {@link GuiSlots} element. + * + * @param slotIcons A function that is given the slot index within the {@link SlotGroup}, and should return a material or null. + */ + public GuiSlots setEmptyIconI(Function slotIcons) { + this.slotIcons = slot -> slotIcons.apply(slots.indexOf(slot) - firstSlot); + return this; + } + + /** + * Allows you to attach an overlay renderer that will get called for each slot, after all slots have been rendered. + * This can be used to render pretty much anything you want to overtop the slot. + * + * @param slotOverlay Render callback providing the slot, screen position of the slot (top-left corner) and the active GuiRender. + */ + public GuiSlots setSlotOverlay(TriConsumer slotOverlay) { + this.slotOverlay = slotOverlay; + return this; + } + + /** + * Allows you to attach an overlay renderer that will get called for each slot, after all slots have been rendered. + * This can be used to render pretty much anything you want to overtop the slot. + *

+ * Similar to {@link #setSlotOverlay(TriConsumer)} except you are given the index of the slot within the {@link GuiSlots} element. + * + * @param slotOverlay Render callback providing the slot, screen position of the slot (top-left corner) and the active GuiRender. + */ + public GuiSlots setSlotOverlayI(TriConsumer slotOverlay) { + this.slotOverlay = (slot, position, render) -> slotOverlay.accept(slots.indexOf(slot) - firstSlot, position, render); + return this; + } + public GuiSlots setXSlotSpacing(int xSlotSpacing) { this.xSlotSpacing = xSlotSpacing; return this; @@ -275,7 +346,7 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo for (int index = 0; index < slotCount; index++) { Slot slot = slots.getSlot(index + firstSlot); - render.texRect(slotTexture, slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); + render.texRect(slotTexture.apply(slot), slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); } render.pose().translate(0, 0, 0.4); @@ -284,29 +355,50 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo Slot slot = slots.getSlot(index + firstSlot); if (!slot.isActive()) continue; if (!slot.hasItem()) { - Material icon = slotIcons.apply(index + firstSlot); + Material icon = slotIcons.apply(slot); if (icon != null) { render.texRect(icon, slot.x + root.xMin(), slot.y + root.yMin(), 16, 16); } } screenAccess.renderSlot(render, slot); - if (GuiRender.isInRect(slot.x + root.xMin(), slot.y + root.yMin(), 16, 16, mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY)) { + if (GuiRender.isInRect(slot.x + root.xMin(), slot.y + root.yMin(), 16, 16, mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY) && isMouseOver()) { highlightSlot = slot; } } + render.pose().translate(0, 0, getBackgroundDepth() - 0.8); + + if (slotOverlay != null) { + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + if (!slot.isActive()) continue; + slotOverlay.accept(slot, Position.create(slot.x + root.xMin(), slot.y + root.yMin()), render); + } + } + if (highlightSlot != null) { - render.pose().translate(0, 0, getBackgroundDepth() - 0.8); - render.rect(highlightSlot.x + root.xMin(), highlightSlot.y + root.yMin(), 16, 16, highlightColour.apply(slots.indexOf(highlightSlot))); + render.rect(highlightSlot.x + root.xMin(), highlightSlot.y + root.yMin(), 16, 16, highlightColour.apply(highlightSlot)); } render.pose().popPose(); } - public record Player(GuiElement container, GuiSlots main, GuiSlots hotBar) {} + public record Player(GuiElement container, GuiSlots main, GuiSlots hotBar) { + public FastStream stream() { + return FastStream.of(main, hotBar); + } + } - public record PlayerWithArmor(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor) {} + public record PlayerWithArmor(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor) { + public FastStream stream() { + return FastStream.of(main, hotBar, armor); + } + } - public record PlayerAll(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor, GuiSlots offHand) {} + public record PlayerAll(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor, GuiSlots offHand) { + public FastStream stream() { + return FastStream.of(main, hotBar, armor, offHand); + } + } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java index 2776c2d5..f553d660 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java @@ -204,7 +204,7 @@ public GuiText setRotatePoint(Position rotatePoint) { @Override public double getForegroundDepth() { - return 0.035; + return 0.05; } @Override diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java index 680b918c..c9c0a62f 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java @@ -62,6 +62,7 @@ public class GuiTextField extends GuiElement implements Background private Supplier suggestion = null; private Supplier suggestionColour = () -> 0x7f7f80; + private Supplier suggestionShadow = () -> true; private Predicate filter = Objects::nonNull; private BiFunction formatter = (string, pos) -> FormattedCharSequence.forward(string, Style.EMPTY); @@ -162,8 +163,24 @@ public GuiTextField setSuggestion(@Nullable Supplier suggestion) { /** * Set the colour of the suggestion text. */ - public void setSuggestionColour(Supplier suggestionColour) { + public GuiTextField setSuggestionColour(Supplier suggestionColour) { this.suggestionColour = suggestionColour; + return this; + } + + public GuiTextField setSuggestionColour(int suggestionColour) { + this.suggestionColour = () -> suggestionColour; + return this; + } + + public GuiTextField setSuggestionShadow(Supplier suggestionShadow) { + this.suggestionShadow = suggestionShadow; + return this; + } + + public GuiTextField setSuggestionShadow(boolean suggestionShadow) { + this.suggestionShadow = () -> suggestionShadow; + return this; } /** @@ -630,7 +647,7 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo } if (suggestion != null && value.isEmpty()) { - render.drawString(suggestion.get(), (float) (k1 - 1), (float) drawY, suggestionColour.get(), shadow.get()); + render.drawString(suggestion.get(), (float) (k1 - 1), (float) drawY, suggestionColour.get(), suggestionShadow.get()); } if (cursorBlink) { diff --git a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java index 7bc1bb20..46ebc188 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java @@ -99,7 +99,8 @@ default boolean renderTooltip(GuiRender render, double mouseX, double mouseY) { if (supplier == null) return false; List list = supplier.get(); if (list.isEmpty()) return false; - render.componentTooltip(list, mouseX, mouseY); + //Run all components though split to account for newline characters in translations + render.renderTooltip(list.stream().flatMap(component -> render.font().split(component, Integer.MAX_VALUE).stream()).toList(), mouseX, mouseY); return true; } } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java index 646abe93..207fb8ae 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java @@ -160,7 +160,7 @@ public Between(GeoRef start, GeoRef end, double pos) { @Override protected double getImpl() { - return start.get() + (end.get() - start.get()) * getPos(); + return start.get() + ((end.get() - start.get()) * getPos()); } public double getPos() { @@ -202,7 +202,7 @@ public BetweenDynamic(GeoRef start, GeoRef end, Supplier pos) { @Override protected double getImpl() { - return start.get() + (end.get() - start.get()) * getPos(); + return start.get() + ((end.get() - start.get()) * getPos()); } public double getPos() { diff --git a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java new file mode 100644 index 00000000..3a0bea86 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java @@ -0,0 +1,87 @@ +package codechicken.lib.internal.compat; + +import codechicken.lib.CodeChickenLib; +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.ModularGuiContainer; +import codechicken.lib.gui.modular.elements.GuiElement; +import mezz.jei.api.IModPlugin; +import mezz.jei.api.JeiPlugin; +import mezz.jei.api.constants.VanillaTypes; +import mezz.jei.api.gui.handlers.IGhostIngredientHandler; +import mezz.jei.api.gui.handlers.IGuiContainerHandler; +import mezz.jei.api.ingredients.ITypedIngredient; +import mezz.jei.api.registration.IGuiHandlerRegistration; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.renderer.Rect2i; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created by brandon3055 on 31/12/2023 + */ +@JeiPlugin +public class JEIPlugin implements IModPlugin { + private static final ResourceLocation ID = new ResourceLocation(CodeChickenLib.MOD_ID, "jei_plugin"); + + public JEIPlugin() { + } + + @Override + public ResourceLocation getPluginUid() { + return ID; + } + + @Override + public void registerGuiHandlers(IGuiHandlerRegistration registration) { + registration.addGuiContainerHandler(ModularGuiContainer.class, new IGuiContainerHandler<>() { + @Override + public List getGuiExtraAreas(ModularGuiContainer screen) { + return FastStream.of(screen.getModularGui().getJeiExclusions()).map(e -> e.getRectangle().toRect2i()).toList(); + } + }); + registration.addGhostIngredientHandler(ModularGuiContainer.class, new IngredientDropHandler()); + } + + private static class IngredientDropHandler implements IGhostIngredientHandler { + private ModularGui gui; + private boolean highlight = true; + + @Override + public List> getTargetsTyped(ModularGuiContainer screen, ITypedIngredient ingredient, boolean doStart) { + gui = screen.getModularGui(); + gui.setJeiHighlightTime(doStart ? 60 * 20 : 3 * 20); + highlight = !doStart; + if (!doStart) return Collections.emptyList(); + List> targets = new ArrayList<>(); + ingredient.getIngredient(VanillaTypes.ITEM_STACK).ifPresent(stack -> gui.getJeiDropTargets().forEach(e -> targets.add(new DropTarget<>(e)))); + return targets; + } + + @Override + public void onComplete() { + highlight = true; + gui.setJeiHighlightTime(0); + } + + @Override + public boolean shouldHighlightTargets() { + return highlight; + } + } + + private record DropTarget(GuiElement element) implements IGhostIngredientHandler.Target { + @Override + public Rect2i getArea() { + return element.getRectangle().toRect2i(); + } + + @Override + public void accept(I ingredient) { + element.getJeiDropConsumer().accept((ItemStack) ingredient); + } + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java index c652f2cd..75dcc995 100644 --- a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java @@ -106,7 +106,7 @@ public ModularSlot setEnabled(boolean enabled) { @Override public boolean mayPlace(ItemStack itemStack) { - return canPlace && validator.test(itemStack) && (!checkContainer || container.canPlaceItem(getContainerSlot(), itemStack)); + return canPlace && validator.test(itemStack) && (!checkContainer || getItemHandler().isItemValid(getContainerSlot(), itemStack)); } @Override diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 0cd041ee..3c773fef 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -67,6 +67,7 @@ public com.mojang.blaze3d.shaders.Program$Type m_85571_()I # getGlType public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_280092_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/inventory/Slot;)V # renderSlot public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_280211_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/item/ItemStack;IILjava/lang/String;)V # renderFloatingItem public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97744_(DD)Lnet/minecraft/world/inventory/Slot; # findSlot +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97774_(Lnet/minecraft/world/inventory/Slot;DD)Z # isHovering public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97818_()V # recalculateQuickCraftRemaining public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97706_ # clickedSlot public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97711_ # draggingItem From 751420af7d6c6cc1185d416a48ef803f5e45db4d Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 2 Mar 2024 16:13:06 +1030 Subject: [PATCH 22/87] Remove hack from LightCoordAttribute. You can't translate to world space via a model transform. --- .../lib/render/pipeline/attribute/LightCoordAttribute.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java index d8135cda..2380d8b5 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java @@ -14,7 +14,6 @@ public class LightCoordAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("light_coord", LC[]::new); private final Vector3 vec = new Vector3();//for computation - private final Vector3 pos = new Vector3(); private LC[] lcRef; @@ -29,7 +28,6 @@ public boolean load(CCRenderState ccrs) { return lcRef != null; } - pos.set(ccrs.lightMatrix.pos); ccrs.pipeline.addDependency(ccrs.sideAttrib); ccrs.pipeline.addRequirement(Transformation.operationIndex); return true; @@ -40,7 +38,7 @@ public void operate(CCRenderState ccrs) { if (lcRef != null) { ccrs.lc.set(lcRef[ccrs.vertexIndex]); } else { - ccrs.lc.compute(vec.set(ccrs.vert.vec).subtract(pos), ccrs.side); + ccrs.lc.compute(vec.set(ccrs.vert.vec), ccrs.side); } } } From 1fddcf84b429a83dc0162cddd42a9658e8473250 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sun, 3 Mar 2024 18:23:28 +1100 Subject: [PATCH 23/87] Some final fixes for GuiSlots and ContextMenu --- .../lib/gui/modular/elements/GuiContextMenu.java | 6 +++++- .../codechicken/lib/gui/modular/elements/GuiSlots.java | 8 ++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java index 704c701b..33f344f4 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java @@ -28,6 +28,7 @@ public class GuiContextMenu extends GuiElement { private boolean closeOnItemClicked = true; private boolean closeOnOutsideClick = true; private boolean actionOnClick = false; + private boolean pressed = false; public GuiContextMenu(ModularGui gui) { super(gui.getRoot()); @@ -123,6 +124,7 @@ private void rebuildButtons() { @Override public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { consumed = super.mouseClicked(mouseX, mouseY, button, consumed); + pressed = isMouseOver(); if (isMouseOver() || consumed) { if (actionOnClick) { if (consumed && closeOnItemClicked) { @@ -143,12 +145,14 @@ public boolean mouseReleased(double mouseX, double mouseY, int button, boolean c consumed = super.mouseReleased(mouseX, mouseY, button, consumed); if (isMouseOver() || consumed) { if (!actionOnClick) { - if (consumed && closeOnItemClicked) { + if (consumed && closeOnItemClicked && pressed) { close(); } + pressed = false; return true; } } + pressed = false; return consumed; } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java index aa21af09..c2bfd086 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -72,9 +72,9 @@ public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAcc if (firstSlot + slotCount > slots.size()) { throw new IllegalStateException("Specified slot range is out of bounds, Last slot in group is at index " + (slots.size() - 1) + " Specified range is from index " + firstSlot + " to " + (firstSlot + slotCount - 1)); } - int columns = Math.min(gridColumns, slots.size()); + int columns = Math.min(gridColumns, slotCount); this.constrain(WIDTH, Constraint.dynamic(() -> (double) (columns * 18) + ((columns - 1) * xSlotSpacing))); - int rows = Math.max(1, slots.size() / gridColumns); + int rows = Math.max(1, slotCount / gridColumns); this.constrain(GeoParam.HEIGHT, Constraint.dynamic(() -> (double) (rows * 18) + ((rows - 1) * ySlotSpacing))); for (int index = 0; index < slotCount; index++) { Slot slot = slots.getSlot(index + firstSlot); @@ -315,8 +315,8 @@ public double getBackgroundDepth() { } private void updateSlots(GuiElement root) { - int columns = Math.min(this.columns, slots.size()); - int rows = Math.max(1, slots.size() / columns); + int columns = Math.min(this.columns, slotCount); + int rows = Math.max(1, slotCount / columns); double width = (columns * 18) + (columns - 1) * xSlotSpacing; double height = (rows * 18) + (rows - 1) * ySlotSpacing; int top = (int) (yCenter() - (height / 2) - root.yMin()); From 7f936e8f7276158ce58690cd8ea9aff7f5254366 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sat, 16 Mar 2024 18:11:49 +1100 Subject: [PATCH 24/87] A few minor GUI fixes and additions. --- .../lib/gui/modular/elements/GuiElement.java | 35 ++++++- .../gui/modular/elements/GuiManipulable.java | 91 +++++++++++++++---- .../lib/gui/modular/elements/GuiSlots.java | 5 +- .../modular/ModularGuiContainerMenu.java | 8 +- 4 files changed, 113 insertions(+), 26 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java index 4ea5e1ac..1282998c 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java @@ -19,9 +19,7 @@ import org.jetbrains.annotations.Nullable; import java.security.InvalidParameterException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.util.*; import java.util.function.Consumer; import java.util.function.Supplier; @@ -53,6 +51,7 @@ public class GuiElement> extends ConstrainedGeometry private final List> removeQueue = new ArrayList<>(); private final List> childElements = new ArrayList<>(); private final List> childElementsUnmodifiable = Collections.unmodifiableList(childElements); + private final Map, Integer> reorderMap = new HashMap<>(); public boolean initialized = false; private Minecraft mc; @@ -119,6 +118,15 @@ public void addChild(GuiElement child) { } protected void applyQueuedChildUpdates() { + if (!reorderMap.isEmpty()) { + reorderMap.forEach((element, index) -> { + if (!childElements.contains(element)) return; + childElements.remove(element); + childElements.add(Math.min(index, childElements.size()), element); + }); + reorderMap.clear(); + } + if (!removeQueue.isEmpty()) { childElements.removeAll(removeQueue); removeQueue.clear(); @@ -155,6 +163,27 @@ public void removeChild(GuiElement child) { addedQueue.remove(child); } + /** + * Sets a child as the last element in the child lest, meaning it will render over all other elements. + */ + public void bringChildToForeground(GuiElement child) { + sendChildToIndex(child, childElements.size() - 1); + } + + /** + * sends a child to a specific index in the child lest. + */ + public void sendChildToIndex(GuiElement child, int index) { + reorderMap.put(child, index); + } + + /** + * Sets a child as the first element in the child lest, meaning it will render under all other elements. + */ + public void sendChildToBackground(GuiElement child) { + sendChildToIndex(child, 0); + } + @Override public boolean isDescendantOf(GuiElement ancestor) { return ancestor == parent || parent.isDescendantOf(ancestor); diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java index d95835e4..d85daf4a 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java @@ -8,10 +8,11 @@ import codechicken.lib.gui.modular.lib.geometry.Rectangle; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.function.Consumer; + import static codechicken.lib.gui.modular.lib.geometry.Constraint.literal; import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; @@ -44,6 +45,7 @@ public class GuiManipulable extends GuiElement implements Conten private boolean dragBottom = false; private boolean dragRight = false; private boolean enableCursors = false; + private boolean resetOnUiInit = true; //Made available for external position restraints public int xMin = 0; @@ -53,8 +55,8 @@ public class GuiManipulable extends GuiElement implements Conten protected Rectangle minSize = Rectangle.create(0, 0, 50, 50); protected Rectangle maxSize = Rectangle.create(0, 0, 256, 256); - protected Runnable onMovedCallback = null; - protected Runnable onResizedCallback = null; + protected Consumer onMovedCallback = null; + protected Consumer onResizedCallback = null; protected PositionRestraint positionRestraint = draggable -> { if (xMin < 0) { int move = -xMin; @@ -112,7 +114,15 @@ public GuiManipulable constrain(GeoParam param, @Nullable Constraint constraint) @Override public void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { super.onScreenInit(mc, font, screenWidth, screenHeight); - resetBounds(); + if (resetOnUiInit) resetBounds(); + } + + /** + * @param resetOnUiInit If true, element bounds will be reset on UI init. (Default: true) + */ + public GuiManipulable setResetOnUiInit(boolean resetOnUiInit) { + this.resetOnUiInit = resetOnUiInit; + return this; } @Override @@ -137,6 +147,11 @@ public GuiManipulable addTopHandle(int handleSize) { return this; } + public GuiManipulable setTopHandle(GuiElement topHandle) { + this.topHandle = topHandle; + return this; + } + public GuiManipulable addBottomHandle(int handleSize) { this.bottomHandle .constrain(BOTTOM, match(contentElement.get(BOTTOM))) @@ -146,6 +161,11 @@ public GuiManipulable addBottomHandle(int handleSize) { return this; } + public GuiManipulable setBottomHandle(GuiElement bottomHandle) { + this.bottomHandle = bottomHandle; + return this; + } + public GuiManipulable addLeftHandle(int handleSize) { this.leftHandle .constrain(LEFT, match(contentElement.get(LEFT))) @@ -155,6 +175,11 @@ public GuiManipulable addLeftHandle(int handleSize) { return this; } + public GuiManipulable setLeftHandle(GuiElement leftHandle) { + this.leftHandle = leftHandle; + return this; + } + public GuiManipulable addRightHandle(int handleSize) { this.rightHandle .constrain(RIGHT, match(contentElement.get(RIGHT))) @@ -164,6 +189,11 @@ public GuiManipulable addRightHandle(int handleSize) { return this; } + public GuiManipulable setRightHandle(GuiElement rightHandle) { + this.rightHandle = rightHandle; + return this; + } + public GuiManipulable addMoveHandle(int handleSize) { this.moveHandle .constrain(TOP, match(contentElement.get(TOP))) @@ -173,6 +203,11 @@ public GuiManipulable addMoveHandle(int handleSize) { return this; } + public GuiManipulable setMoveHandle(GuiElement moveHandle) { + this.moveHandle = moveHandle; + return this; + } + /** * You can use this to retrieve the current move handle. * You are free to update the constraints on this handle, but it must be constrained relative to the content element. @@ -222,11 +257,21 @@ public GuiManipulable enableCursors(boolean enableCursors) { } public GuiManipulable setOnMovedCallback(Runnable onMovedCallback) { + this.onMovedCallback = finished -> onMovedCallback.run(); + return this; + } + + public GuiManipulable setOnMovedCallback(Consumer onMovedCallback) { this.onMovedCallback = onMovedCallback; return this; } public GuiManipulable setOnResizedCallback(Runnable onResizedCallback) { + this.onResizedCallback = finished -> onResizedCallback.run(); + return this; + } + + public GuiManipulable setOnResizedCallback(Consumer onResizedCallback) { this.onResizedCallback = onResizedCallback; return this; } @@ -324,13 +369,12 @@ public void mouseMoved(double mouseX, double mouseY) { int xMove = (int) (mouseX - dragXOffset) - xMin; int yMove = (int) (mouseY - dragYOffset) - yMin; if (dragPos) { - Rectangle previous = Rectangle.create(xMin, yMin, xMax - xMin, yMax - yMin); xMin += xMove; xMax += xMove; yMin += yMove; yMax += yMove; - validatePosition(); - onMoved(); + validatePosition(false); + onMoved(false); } else { Rectangle min = getMinSize(); Rectangle max = getMaxSize(); @@ -358,8 +402,8 @@ public void mouseMoved(double mouseX, double mouseY) { if (xMax - xMin > max.width()) xMax = xMin + (int) max.width(); if (xMax > scaledScreenWidth()) xMax = scaledScreenWidth(); } - validatePosition(); - onResized(); + validatePosition(false); + onResized(false); } } super.mouseMoved(mouseX, mouseY); @@ -367,34 +411,45 @@ public void mouseMoved(double mouseX, double mouseY) { @Override public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { - if (isDragging) { - validatePosition(); + if (isMoving()) { + validatePosition(true); + } + if (isResizing()) { + onResized(true); } isDragging = dragPos = dragTop = dragLeft = dragBottom = dragRight = false; return super.mouseReleased(mouseX, mouseY, button, consumed); } - protected void validatePosition() { + protected void validatePosition(boolean finished) { double x = xMin; double y = yMin; positionRestraint.restrainPosition(this); - if ((x != xMin || y != yMin) && onMovedCallback != null) { - onMovedCallback.run(); + if ((x != xMin || y != yMin)) { + onMoved(finished); } } - protected void onMoved() { + protected void onMoved(boolean finished) { if (onMovedCallback != null) { - onMovedCallback.run(); + onMovedCallback.accept(finished); } } - protected void onResized() { + protected void onResized(boolean finished) { if (onResizedCallback != null) { - onResizedCallback.run(); + onMovedCallback.accept(finished); } } + public boolean isMoving() { + return dragPos; + } + + public boolean isResizing() { + return dragTop || dragLeft || dragBottom || dragRight; + } + public interface PositionRestraint { void restrainPosition(GuiManipulable draggable); } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java index c2bfd086..4fb97fdb 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -346,7 +346,10 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo for (int index = 0; index < slotCount; index++) { Slot slot = slots.getSlot(index + firstSlot); - render.texRect(slotTexture.apply(slot), slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); + Material tex = slotTexture.apply(slot); + if (tex != null) { + render.texRect(tex, slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); + } } render.pose().translate(0, 0, 0.4); diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java index f6f043cc..02338869 100644 --- a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java @@ -244,12 +244,12 @@ protected boolean moveItemStackTo(ItemStack stack, List targets, boolean r itemStack2 = slot.getItem(); if (!itemStack2.isEmpty() && ItemStack.isSameItemSameTags(stack, itemStack2)) { int l = itemStack2.getCount() + stack.getCount(); - if (l <= stack.getMaxStackSize()) { + if (l <= Math.min(stack.getMaxStackSize(), slot.getMaxStackSize(stack))) { stack.setCount(0); itemStack2.setCount(l); slot.setChanged(); moved = true; - } else if (itemStack2.getCount() < stack.getMaxStackSize()) { + } else if (itemStack2.getCount() < Math.min(stack.getMaxStackSize(), slot.getMaxStackSize(stack))) { stack.shrink(stack.getMaxStackSize() - itemStack2.getCount()); itemStack2.setCount(stack.getMaxStackSize()); slot.setChanged(); @@ -284,8 +284,8 @@ protected boolean moveItemStackTo(ItemStack stack, List targets, boolean r slot = targets.get(position); itemStack2 = slot.getItem(); if (itemStack2.isEmpty() && slot.mayPlace(stack)) { - if (stack.getCount() > slot.getMaxStackSize()) { - slot.set(stack.split(slot.getMaxStackSize())); + if (stack.getCount() > slot.getMaxStackSize(stack)) { + slot.set(stack.split(slot.getMaxStackSize(stack))); } else { slot.set(stack.split(stack.getCount())); } From 463deb19f01f3bfdfb763e0ad993b7d5dac61de9 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Wed, 3 Apr 2024 18:23:05 +1100 Subject: [PATCH 25/87] A few more gui fixes and tweaks. --- .../lib/gui/modular/ModularGui.java | 12 +++++ .../lib/gui/modular/ModularGuiContainer.java | 4 +- .../gui/modular/elements/GuiItemStack.java | 2 +- .../gui/modular/elements/GuiManipulable.java | 3 +- .../gui/modular/lib/geometry/Constraint.java | 54 +++++++++++++++---- .../modular/lib/geometry/ConstraintImpl.java | 28 ++++++++++ .../gui/modular/lib/geometry/Rectangle.java | 15 ++++-- 7 files changed, 98 insertions(+), 20 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGui.java b/src/main/java/codechicken/lib/gui/modular/ModularGui.java index 242ca4c0..8955970c 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGui.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGui.java @@ -45,6 +45,7 @@ public class ModularGui implements GuiParent { private boolean closeOnEscape = true; private boolean renderBackground = true; private boolean vanillaSlotRendering = false; + private boolean floatingItemDisablesToolTips = true; private Font font; private Minecraft mc; @@ -523,6 +524,17 @@ public void setCursor(ResourceLocation cursor) { this.newCursor = cursor; } + /** + * By default, tool tips are disabled while where is a floating item on screen. This can be used to re-enable them. + */ + public void setFloatingItemDisablesToolTips(boolean floatingItemDisablesToolTips) { + this.floatingItemDisablesToolTips = floatingItemDisablesToolTips; + } + + public boolean doesFloatingItemDisableToolTips() { + return floatingItemDisablesToolTips; + } + public List> getJeiExclusions() { return root.addJeiExclusions(new ArrayList<>()); } diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java index 8e74eba6..f1dbb21b 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -105,7 +105,7 @@ protected boolean handleFloatingItemRender(GuiRender render, int mouseX, int mou } } renderFloatingItem(render, stack, mouseX - 8, mouseY - yOffset, countOverride); - ret = true; + ret = modularGui.doesFloatingItemDisableToolTips(); } if (!this.snapbackItem.isEmpty()) { @@ -120,7 +120,7 @@ protected boolean handleFloatingItemRender(GuiRender render, int mouseX, int mou int xPos = snapbackStartX + (int) ((float) xDist * anim); int yPos = snapbackStartY + (int) ((float) yDist * anim); renderFloatingItem(render, snapbackItem, xPos + leftPos, yPos + topPos, null); - ret = true; + ret = modularGui.doesFloatingItemDisableToolTips(); } return ret; diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java index 099d2c8a..3e074eec 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java @@ -109,7 +109,7 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo @Override public boolean renderOverlay(GuiRender render, double mouseX, double mouseY, float partialTicks, boolean consumed) { if (super.renderOverlay(render, mouseX, mouseY, partialTicks, consumed)) return true; - if (isMouseOver() && !stack.get().isEmpty()) { + if (isMouseOver() && !stack.get().isEmpty() && toolTip.get()) { render.renderTooltip(stack.get(), mouseX, mouseY); return true; } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java index d85daf4a..239ec6e5 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java @@ -413,6 +413,7 @@ public void mouseMoved(double mouseX, double mouseY) { public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { if (isMoving()) { validatePosition(true); + onMoved(true); } if (isResizing()) { onResized(true); @@ -438,7 +439,7 @@ protected void onMoved(boolean finished) { protected void onResized(boolean finished) { if (onResizedCallback != null) { - onMovedCallback.accept(finished); + onResizedCallback.accept(finished); } } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java index 63d80344..a3fb6acf 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java @@ -78,7 +78,7 @@ static ConstraintImpl.Relative match(GeoRef relativeTo) { * Contains a parameter to the given reference plus the provided fixed offset. * * @param relativeTo The relative geometry. - * @param offset The offset to apply. + * @param offset The offset to apply. */ static ConstraintImpl.Relative relative(GeoRef relativeTo, double offset) { return new ConstraintImpl.Relative(relativeTo, offset); @@ -88,7 +88,7 @@ static ConstraintImpl.Relative relative(GeoRef relativeTo, double offset) { * Contains a parameter to the given reference plus the provided dynamic offset. * * @param relativeTo The relative geometry. - * @param offset The dynamic offset to apply. + * @param offset The dynamic offset to apply. */ static ConstraintImpl.RelativeDynamic relative(GeoRef relativeTo, Supplier offset) { return new ConstraintImpl.RelativeDynamic(relativeTo, offset); @@ -99,32 +99,64 @@ static ConstraintImpl.RelativeDynamic relative(GeoRef relativeTo, Supplier + * This variant also allows a pixel offset. + * + * @param start The Start position. + * @param end The End position. + * @param position The position between start and end. (0=start to 1=end) + * @param offset position offset in pixels + */ + static ConstraintImpl.BetweenOffset between(GeoRef start, GeoRef end, double position, double offset) { + return new ConstraintImpl.BetweenOffset(start, end, position, offset); + } + /** * Contains a parameter to a dynamic position between the two provided references. * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. * To prevent this call .clamp() on the returned constraint. * - * @param start The Start position. - * @param end The End position. + * @param start The Start position. + * @param end The End position. * @param position The dynamic position between start and end. (0=start to 1=end) */ static ConstraintImpl.BetweenDynamic between(GeoRef start, GeoRef end, Supplier position) { return new ConstraintImpl.BetweenDynamic(start, end, position); } + /** + * Contains a parameter to a dynamic position between the two provided references. + * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. + * To prevent this call .clamp() on the returned constraint. + *

+ * This variant also allows a pixel offset. + * + * @param start The Start position. + * @param end The End position. + * @param position The dynamic position between start and end. (0=start to 1=end) + * @param offset Dynamic position offset in pixels + */ + static ConstraintImpl.BetweenDynamic between(GeoRef start, GeoRef end, Supplier position, Supplier offset) { + return new ConstraintImpl.BetweenOffsetDynamic(start, end, position, offset); + } + /** * Contains a parameter to the mid-point between the two provided references. * * @param start The Start position. - * @param end The End position. + * @param end The End position. */ static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end) { return new ConstraintImpl.MidPoint(start, end, 0); @@ -133,8 +165,8 @@ static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end) { /** * Contains a parameter to the mid-point between the two provided references with a fixed offset. * - * @param start The Start position. - * @param end The End position. + * @param start The Start position. + * @param end The End position. * @param offset offset distance. */ static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end, double offset) { @@ -144,8 +176,8 @@ static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end, double offset) /** * Contains a parameter to the mid-point between the two provided references with a dynamic offset. * - * @param start The Start position. - * @param end The End position. + * @param start The Start position. + * @param end The End position. * @param offset offset distance suppler. */ static ConstraintImpl.MidPointDynamic midPoint(GeoRef start, GeoRef end, Supplier offset) { diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java index 207fb8ae..258437d0 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java @@ -226,6 +226,34 @@ public BetweenDynamic clamp() { } } + public static class BetweenOffset extends Between { + private final double offset; + + public BetweenOffset(GeoRef start, GeoRef end, double pos, double offset) { + super(start, end, pos); + this.offset = offset; + } + + @Override + protected double getImpl() { + return super.getImpl() + offset; + } + } + + public static class BetweenOffsetDynamic extends BetweenDynamic { + private final Supplier offset; + + public BetweenOffsetDynamic(GeoRef start, GeoRef end, Supplier pos, Supplier offset) { + super(start, end, pos); + this.offset = offset; + } + + @Override + protected double getImpl() { + return super.getImpl() + offset.get(); + } + } + public static class MidPoint extends ConstraintImpl { protected final GeoRef start; protected final GeoRef end; diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java index 4ad613f7..d770073d 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java @@ -79,11 +79,16 @@ default boolean intersects(Rectangle other) { * Returns a new rectangle that represents the intersection area between the two inputs */ default Rectangle intersect(Rectangle other) { - double x = Math.max(x(), other.x()); - double y = Math.max(y(), other.y()); - double width = Math.max(0, Math.min(xMax(), other.xMax()) - x()); - double height = Math.max(0, Math.min(yMax(), other.yMax()) - y()); - return create(x, y, width, height); + double left = Math.max(x(), other.x()); + double right = Math.min(xMax(), other.xMax()); + if (right > left) { + double top = Math.max(y(), other.y()); + double bottom = Math.min(yMax(), other.yMax()); + if (bottom > top) { + return create(left, top, right - left, bottom - top); + } + } + return create(0, 0, 0, 0); } /** From 9ed6604d67eeceaaed244aa48606e3de9cecd5fd Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sun, 7 Apr 2024 16:56:52 +1000 Subject: [PATCH 26/87] Support line break wrapping in GuiText --- src/main/java/codechicken/lib/gui/modular/elements/GuiText.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java index f553d660..de758c31 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java @@ -237,7 +237,7 @@ public void renderForeground(GuiRender render, double mouseX, double mouseY, flo render.drawString(formatted, xPos, yPos, getTextColour(), getShadow()); } //Draw Wrapped - else if (tooLong && wrap) { + else if ((tooLong || font().split(component, Integer.MAX_VALUE).size() > 1) && wrap) { textHeight = font.wordWrapHeight(component, (int) xSize()); List list = font.split(component, (int) xSize()); From 512050d0580e1f223f25824c3c1a4bb671308266 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sat, 13 Apr 2024 05:46:23 +1000 Subject: [PATCH 27/87] Added option to not reset tooltip time on button press. --- .../lib/gui/modular/elements/GuiButton.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java index b8df4d2b..2f291833 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java @@ -35,6 +35,7 @@ public class GuiButton extends GuiElement { private Supplier disabled = () -> false; private Supplier toggleState; private GuiText label = null; + private boolean resetHoverOnPress = true; /** * In its default state this is a blank, invisible element that can fire callbacks when pressed. @@ -164,6 +165,15 @@ public GuiText getLabel() { return label; } + /** + * By default, hover time is reset when button is pressed. + * THis allows you to disable that functionality to the tooltip will remain open when button is pressed. + */ + public GuiButton setResetHoverOnPress(boolean resetHoverOnPress) { + this.resetHoverOnPress = resetHoverOnPress; + return this; + } + /** * This event is fired immediately when this button is left-clicked. * This is the logic used by most vanilla gui buttons. @@ -294,7 +304,7 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { Runnable onPress = this.onPress.get(button); if (onClick == null && onPress == null) return false; pressed = true; - hoverTime = 1; + if (resetHoverOnPress) hoverTime = 1; boolean consume = false; if (onClick != null) { @@ -318,7 +328,7 @@ public boolean mouseReleased(double mouseX, double mouseY, int button, boolean c Runnable onClick = this.onClick.get(button); Runnable onPress = this.onPress.get(button); if (onClick == null && onPress == null) return consumed; - hoverTime = 1; + if (resetHoverOnPress) hoverTime = 1; if (!isDisabled() && isMouseOver()) { if (pressed && onPress != null) { From d712280c019b17bcd22c2f406bd3daf7f813e999 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sun, 14 Apr 2024 08:32:08 +1000 Subject: [PATCH 28/87] Fixed an issue with tooltip wrapping. --- .../lib/gui/modular/lib/GuiRender.java | 22 ++++++++++++++----- .../lib/gui/modular/lib/TooltipHandler.java | 3 ++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java index bc13e1ec..bcae9359 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java @@ -1302,11 +1302,8 @@ public void renderTooltip(Component message, double mouseX, double mouseY) { } public void renderTooltip(Component message, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - this.renderTooltip(List.of(message.getVisualOrderText()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom); - } - - public void componentTooltip(List tooltips, double mouseX, double mouseY) { - componentTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); + List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, List.of(message), Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); + this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); } public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { @@ -1318,21 +1315,34 @@ public void componentTooltip(List tooltips, double mous componentTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f, stack); } - public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ItemStack stack) { + public void componentTooltip(List tooltips, double mouseX, double mouseY) { + componentTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f, ItemStack.EMPTY); + } + + public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ItemStack stack) { this.tooltipStack = stack; List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); this.tooltipStack = ItemStack.EMPTY; } + /** + * Warning: This tooltip method with not automatically wrap tooltip lines + */ public void renderTooltip(List tooltips, double mouseX, double mouseY) { renderTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); } + /** + * Warning: This tooltip method with not automatically wrap tooltip lines + */ public void renderTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { this.renderTooltipInternal(tooltips.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); } + /** + * Warning: This tooltip method with not automatically wrap tooltip lines + */ public void renderTooltip(List tooltips, ClientTooltipPositioner positioner, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { this.renderTooltipInternal(tooltips.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, positioner); } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java index 46ebc188..0f1d5cfc 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java @@ -7,6 +7,7 @@ import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.function.Supplier; /** @@ -100,7 +101,7 @@ default boolean renderTooltip(GuiRender render, double mouseX, double mouseY) { List list = supplier.get(); if (list.isEmpty()) return false; //Run all components though split to account for newline characters in translations - render.renderTooltip(list.stream().flatMap(component -> render.font().split(component, Integer.MAX_VALUE).stream()).toList(), mouseX, mouseY); + render.componentTooltip(list.stream().flatMap(component -> render.font().getSplitter().splitLines(component, Integer.MAX_VALUE, component.getStyle()).stream()).toList(), mouseX, mouseY); return true; } } From a5887ecd0313786b647aa19d840a59d36f111097 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Mon, 15 Apr 2024 09:50:27 +1000 Subject: [PATCH 29/87] GuiProgressIcon texture improvements. --- .../gui/modular/elements/GuiProgressIcon.java | 94 ++++++++++++++----- 1 file changed, 72 insertions(+), 22 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java index 3e56ce61..47a0caf0 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java @@ -25,26 +25,46 @@ */ public class GuiProgressIcon extends GuiElement implements BackgroundRender { - private Material background = null; - private Material animated; + private Supplier background = null; + private Supplier animated; private Supplier progress = () -> 0D; + private boolean rotateToDirection = true; private Direction direction = Direction.RIGHT; - public GuiProgressIcon(@NotNull GuiParent parent, Material animated) { + public GuiProgressIcon(@NotNull GuiParent parent, Supplier animated) { super(parent); this.animated = animated; } - public GuiProgressIcon(@NotNull GuiParent parent, Material background, Material animated) { + public GuiProgressIcon(@NotNull GuiParent parent, Material animated) { + this(parent, () -> animated); + } + + public GuiProgressIcon(@NotNull GuiParent parent, Supplier background, Supplier animated) { super(parent); this.background = background; this.animated = animated; } + public GuiProgressIcon(@NotNull GuiParent parent, Material background, Material animated) { + this(parent, () -> background, () -> animated); + } + + public GuiProgressIcon(@NotNull GuiParent parent) { super(parent); } + /** + * The expected default direction for a progress texture is left-to-right e.g. furnace arrow. + * The texture will then be rotated to the direction specified via {@link #setDirection(Direction)} + * If you do not want the texture to be rotated then set this to false. + */ + public GuiProgressIcon setRotateToDirection(boolean rotateToDirection) { + this.rotateToDirection = rotateToDirection; + return this; + } + /** * Set the direction this progress icon is pointing, Default is RIGHT */ @@ -57,6 +77,14 @@ public GuiProgressIcon setDirection(Direction direction) { * Sets the background texture, aka the "empty" texture. */ public GuiProgressIcon setBackground(@Nullable Material background) { + this.background = () -> background; + return this; + } + + /** + * Sets the background texture, aka the "empty" texture. + */ + public GuiProgressIcon setBackground(@Nullable Supplier background) { this.background = background; return this; } @@ -65,6 +93,14 @@ public GuiProgressIcon setBackground(@Nullable Material background) { * Sets the texture that will be animated. */ public GuiProgressIcon setAnimated(Material animated) { + this.animated = () -> animated; + return this; + } + + /** + * Sets the texture that will be animated. + */ + public GuiProgressIcon setAnimated(Supplier animated) { this.animated = animated; return this; } @@ -92,24 +128,38 @@ public double getProgress() { @Override public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { - render.pose().pushPose(); - - double width = direction.getAxis() == Axis.X ? xSize() : ySize(); - double height = direction.getAxis() == Axis.X ? ySize() : xSize(); - - render.pose().translate(xMin() + (xSize() / 2), yMin() + (ySize() / 2), 0); - render.pose().mulPose(com.mojang.math.Axis.ZP.rotationDegrees((float) Direction.RIGHT.rotationTo(direction))); - - double halfWidth = width / 2; - double halfHeight = height / 2; - if (background != null) { - render.tex(background, -halfWidth, -halfHeight, halfWidth, halfHeight, 0xFFFFFFFF); + if (rotateToDirection) { + render.pose().pushPose(); + + double width = direction.getAxis() == Axis.X ? xSize() : ySize(); + double height = direction.getAxis() == Axis.X ? ySize() : xSize(); + + render.pose().translate(xMin() + (xSize() / 2), yMin() + (ySize() / 2), 0); + render.pose().mulPose(com.mojang.math.Axis.ZP.rotationDegrees((float) Direction.RIGHT.rotationTo(direction))); + + double halfWidth = width / 2; + double halfHeight = height / 2; + if (background != null && background.get() != null) { + render.tex(background.get(), -halfWidth, -halfHeight, halfWidth, halfHeight, 0xFFFFFFFF); + } + + if (animated == null || animated.get() == null) return; + float progress = (float) getProgress(); + render.partialSprite(animated.get().renderType(GuiRender::texColType), -halfWidth, -halfHeight, -halfWidth + (width * progress), -halfHeight + height, animated.get().sprite(), 0F, 0F, progress, 1F, 0xFFFFFFFF); + + render.pose().popPose(); + } else { + if (background != null && background.get() != null) { + render.texRect(background.get(), getRectangle()); + } + if (animated == null || animated.get() == null) return; + float progress = (float) getProgress(); + switch (direction) { + case UP -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMin(), yMax() - (ySize() * progress), xMax(), yMax(), animated.get().sprite(), 0F, 1F - progress, 1F, 1F, 0xFFFFFFFF); + case LEFT -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMax() - (xSize() * progress), yMin(), xMax(), yMax(), animated.get().sprite(), 1F - progress, 0F, 1F, 1F, 0xFFFFFFFF); + case DOWN -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMin() + (ySize() * progress), animated.get().sprite(), 0F, 0F, 1F, progress, 0xFFFFFFFF); + case RIGHT -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMin(), yMin(), xMin() + (xSize() * progress), yMax(), animated.get().sprite(), 0F, 0F, progress, 1F, 0xFFFFFFFF); + } } - - if (animated == null) return; - float progress = (float) getProgress(); - render.partialSprite(animated.renderType(GuiRender::texColType), -halfWidth, -halfHeight, -halfWidth + (width* progress), -halfHeight + height, animated.sprite(), 0F, 0F, progress, 1F, 0xFFFFFFFF); - - render.pose().popPose(); } } From fe58ede1a560fc8f694bb1194ef28c3029ea7ec5 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sun, 21 Apr 2024 17:11:19 +1000 Subject: [PATCH 30/87] Added ability to rotate GuiTexture --- .../lib/gui/modular/elements/GuiTexture.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java index da5c0577..542b6ee2 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java @@ -17,6 +17,7 @@ public class GuiTexture extends GuiElement implements BackgroundRend private Supplier getMaterial; private Supplier colour = () -> 0xFFFFFFFF; private Borders dynamicBorders = null; + private Supplier rotation = () -> 0; /** * @param parent parent {@link GuiParent}. @@ -97,6 +98,24 @@ public GuiTexture setColour(Supplier colour) { return this; } + /** + * Sets the texture rotation, each integer increment will rotate the texture by 90 degrees. + * (Not compatible with dynamic textures) + */ + public GuiTexture setRotation(Supplier rotation) { + this.rotation = rotation; + return this; + } + + /** + * Sets the texture rotation, each integer increment will rotate the texture by 90 degrees. + * (Not compatible with dynamic textures) + */ + public GuiTexture setRotation(int rotation) { + this.rotation = () -> rotation; + return this; + } + @Override public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { Material material = getMaterial(); @@ -104,7 +123,7 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo if (dynamicBorders != null) { render.dynamicTex(material, getRectangle(), dynamicBorders, colour.get()); } else { - render.texRect(material, getRectangle(), colour.get()); + render.texRect(material, rotation.get(), getRectangle(), colour.get()); } } } From 3a47b5883c9b7e9f6720a40a57982f8eddafb14e Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Sun, 21 Apr 2024 18:45:06 +1000 Subject: [PATCH 31/87] Fixed colour bug and improved colour picker. --- .../java/codechicken/lib/colour/Colour.java | 8 ++-- .../gui/modular/elements/GuiColourPicker.java | 45 +++++++++++++++---- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/main/java/codechicken/lib/colour/Colour.java b/src/main/java/codechicken/lib/colour/Colour.java index 61b22b05..ca083a8a 100644 --- a/src/main/java/codechicken/lib/colour/Colour.java +++ b/src/main/java/codechicken/lib/colour/Colour.java @@ -175,19 +175,19 @@ public Colour aF(int a) { } public float rF() { - return r / 255F; + return r() / 255F; } public float gF() { - return g / 255F; + return g() / 255F; } public float bF() { - return b / 255F; + return b() / 255F; } public float aF() { - return a / 255F; + return a() / 255F; } public int r() { diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java index c576a7e8..1d4d6b71 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java @@ -19,11 +19,15 @@ public class GuiColourPicker extends GuiManipulable { private ColourState colourState = ColourState.create(); + private final Colour initialColour; + private boolean blockOutsideClicks = false; + private boolean closeOnOutsideClick = false; private GuiButton okButton; private GuiButton cancelButton; - public GuiColourPicker(@NotNull GuiParent parent) { + public GuiColourPicker(@NotNull GuiParent parent, Colour initialColour) { super(parent); + this.initialColour = initialColour; } public static GuiColourPicker create(GuiParent guiParent, ColourState colourState) { @@ -31,11 +35,10 @@ public static GuiColourPicker create(GuiParent guiParent, ColourState colourS } public static GuiColourPicker create(GuiParent guiParent, ColourState colourState, boolean hasAlpha) { - Colour initialColour = colourState.getColour(); - GuiColourPicker picker = new GuiColourPicker(guiParent.getModularGui().getRoot()); + GuiColourPicker picker = new GuiColourPicker(guiParent.getModularGui().getRoot(), colourState.getColour()); picker.setOpaque(true); picker.setColourState(colourState); - Constraints.size(picker, 80, hasAlpha ? 80 : 68); + Constraints.size(picker, 80, hasAlpha ? 80 : 70); GuiRectangle background = GuiRectangle.toolTipBackground(picker.getContentElement()); Constraints.bind(background, picker.getContentElement()); @@ -77,10 +80,7 @@ public static GuiColourPicker create(GuiParent guiParent, ColourState colourS picker.cancelButton = GuiButton.flatColourButton(background, () -> Component.translatable("gui.cancel"), e -> 0xFF000000, e -> e ? 0xFF777777 : 0xFF555555) .setOpaque(true) - .onPress(() -> { - colourState.set(initialColour); - picker.getParent().removeChild(picker); - }) + .onPress(picker::cancel) .constrain(HEIGHT, literal(10)) .constrain(TOP, relative(preview.get(BOTTOM), 2)) .constrain(LEFT, midPoint(background.get(LEFT), background.get(RIGHT), -4)) @@ -121,6 +121,35 @@ public static SliderBG makeSlider(GuiElement background, int colour, SliderSt return slideBG; } + public GuiColourPicker setBlockOutsideClicks(boolean blockOutsideClicks) { + this.blockOutsideClicks = blockOutsideClicks; + return this; + } + + public GuiColourPicker setCancelOnOutsideClick(boolean closeOnOutsideClick) { + this.closeOnOutsideClick = closeOnOutsideClick; + return this; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + if (closeOnOutsideClick && !getContentElement().getRectangle().contains(mouseX, mouseY)) { + cancel(); + } + return super.mouseClicked(mouseX, mouseY, button, consumed) || blockOutsideClicks; + } + + public void cancel() { + if (cancelButton != null && cancelButton.isEnabled()){ + colourState.set(initialColour); + } + close(); + } + + public void close() { + getParent().removeChild(this); + } + private static boolean validHex(String value) { try { Integer.parseUnsignedInt(value, 16); From f95f2a82096c7e6a2b0d7a4ad485635351bfee9e Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Tue, 23 Apr 2024 07:47:17 +1000 Subject: [PATCH 32/87] Added center constraint with offset --- .../java/codechicken/lib/gui/modular/lib/Constraints.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java index 1cb4de5b..91c84555 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java @@ -90,6 +90,11 @@ public static void center(ConstrainedGeometry element, ConstrainedGeometry element.constrain(LEFT, midPoint(centerOn.get(LEFT), centerOn.get(RIGHT), () -> element.xSize() / -2)); } + public static void center(ConstrainedGeometry element, ConstrainedGeometry centerOn, double xOffset, double yOffset) { + element.constrain(TOP, midPoint(centerOn.get(TOP), centerOn.get(BOTTOM), () -> (element.ySize() / -2) + yOffset)); + element.constrain(LEFT, midPoint(centerOn.get(LEFT), centerOn.get(RIGHT), () -> (element.xSize() / -2) + xOffset)); + } + /** * Constrain the specified element to a position inside the specified targetElement. * See the following image for an example of what each LayoutPos does: From baf638fea19a96c9595308034c3c83806494f62b Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 22 Apr 2024 14:23:06 +0930 Subject: [PATCH 33/87] Fix VBORenderType. --- .../java/codechicken/lib/render/buffer/VBORenderType.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java index 5427d82d..2a021c6b 100644 --- a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java @@ -68,13 +68,15 @@ public WithCallbacks withState(RenderStateShard shard) { private void render() { rebuild(); - this.vertexBuffer.drawWithShader(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), RenderSystem.getShader()); + vertexBuffer.bind(); + vertexBuffer.drawWithShader(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), RenderSystem.getShader()); } private void rebuild() { if (!dirty) return; builder.begin(mode(), format()); factory.accept(format(), builder); + vertexBuffer.bind(); vertexBuffer.upload(builder.end()); builder.clear(); dirty = false; From 24d2c4fcc44c4465cf596d8314750f5db24b57ee Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 22 Apr 2024 14:32:00 +0930 Subject: [PATCH 34/87] Add default names to all data providers. --- .../lib/datagen/ItemModelProvider.java | 5 +++++ .../lib/datagen/LootTableProvider.java | 19 ++++++++++--------- .../lib/datagen/recipe/RecipeProvider.java | 9 ++++++++- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java index 96b21847..20b17f49 100644 --- a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java +++ b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java @@ -165,6 +165,11 @@ private ExistingFileHelper getExistingFileHelper() { return existingFileHelper; } + @Override + public String getName() { + return modid + " Item models."; + } + public static class SimpleItemModelBuilder { private final ItemModelProvider provider; diff --git a/src/main/java/codechicken/lib/datagen/LootTableProvider.java b/src/main/java/codechicken/lib/datagen/LootTableProvider.java index bf3bf7ef..458a4bad 100644 --- a/src/main/java/codechicken/lib/datagen/LootTableProvider.java +++ b/src/main/java/codechicken/lib/datagen/LootTableProvider.java @@ -40,13 +40,14 @@ public abstract class LootTableProvider implements DataProvider { private static final Logger logger = LogManager.getLogger(); - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); private final PackOutput.PathProvider output; + protected final String modId; private final Map tables = new HashMap<>(); - protected LootTableProvider(PackOutput output) { + protected LootTableProvider(PackOutput output, String modId) { this.output = output.createPathProvider(PackOutput.Target.DATA_PACK, "loot_tables"); + this.modId = modId; } @Override @@ -88,10 +89,6 @@ protected void registerTable(ResourceLocation name, LootTable table) { } } - private static Path getPath(Path pathIn, ResourceLocation id) { - return pathIn.resolve("data/" + id.getNamespace() + "/loot_tables/" + id.getPath() + ".json"); - } - public static abstract class BlockLootProvider extends LootTableProvider { protected static final LootItemCondition.Builder SILK_TOUCH = MatchTool.toolMatches(ItemPredicate.Builder.item() @@ -99,8 +96,8 @@ public static abstract class BlockLootProvider extends LootTableProvider { ); protected static final LootItemCondition.Builder NO_SILK_TOUCH = SILK_TOUCH.invert(); - protected BlockLootProvider(PackOutput output) { - super(output); + protected BlockLootProvider(PackOutput output, String modId) { + super(output, modId); } protected LootPool.Builder singleItem(ItemLike item) { @@ -160,6 +157,10 @@ public void register(Block block, LootTable.Builder builder) { protected void register(ResourceLocation name, LootTable.Builder builder) { registerTable(new ResourceLocation(name.getNamespace(), "blocks/" + name.getPath()), builder.setParamSet(LootContextParamSets.BLOCK).build()); } - } + @Override + public String getName() { + return modId + " Block Loot Tables"; + } + } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java index cb38c5ed..d1098c45 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java @@ -31,9 +31,11 @@ public abstract class RecipeProvider implements DataProvider { private final Map recipes = new HashMap<>(); private final PackOutput output; + protected final String modId; - public RecipeProvider(PackOutput output) { + public RecipeProvider(PackOutput output, String modId) { this.output = output; + this.modId = modId; } @Override @@ -169,4 +171,9 @@ protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { protected InventoryChangeTrigger.TriggerInstance hasItem(ItemPredicate... predicates) { return new InventoryChangeTrigger.TriggerInstance(ContextAwarePredicate.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); } + + @Override + public String getName() { + return modId + " Recipes."; + } } From d85dd463630c7f6565d68029295d16d43759ff06 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 22 Apr 2024 14:32:24 +0930 Subject: [PATCH 35/87] Add utility for setting UV tex on all CCModel vertices. --- src/main/java/codechicken/lib/render/CCModel.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/codechicken/lib/render/CCModel.java b/src/main/java/codechicken/lib/render/CCModel.java index 568144a4..4c953e4d 100644 --- a/src/main/java/codechicken/lib/render/CCModel.java +++ b/src/main/java/codechicken/lib/render/CCModel.java @@ -364,6 +364,13 @@ public CCModel setColour(int c) { return this; } + public CCModel setTex(int tex) { + for (Vertex5 vert : verts) { + vert.uv.tex = tex; + } + return this; + } + /** * Computes the minecraft lighting coordinates for use with a LightMatrix * From 55e1fefd686c2360a22e16e0187687350b106206 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Tue, 7 May 2024 17:24:31 +1000 Subject: [PATCH 36/87] Fixed flat entity rendering --- .../modular/elements/GuiEntityRenderer.java | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java index f3e3b0db..b7b502cb 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java @@ -180,15 +180,15 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo if (entity instanceof LivingEntity living) { int eyeOffset = (int) ((entity.getEyeHeight()) * scale); if (trackMouse.get()) { - renderEntityInInventoryFollowsMouse(render, xPos, yPos, scale, xPos - (float) mouseX, yPos - (float) mouseY - eyeOffset, living); + renderEntityInInventoryFollowsMouse(render, xPos, yPos, scale, force2dSize, xPos - (float) mouseX, yPos - (float) mouseY - eyeOffset, living); } else { - renderEntityInInventoryWithRotation(render, xPos, yPos, scale, rotation, living); + renderEntityInInventoryWithRotation(render, xPos, yPos, scale, force2dSize, rotation, living); } } else { Quaternionf quaternionf = new Quaternionf().rotateZ((float)Math.PI); Quaternionf quaternionf1 = Axis.YP.rotationDegrees(rotation); quaternionf.mul(quaternionf1); - renderEntityInInventory(render, xPos, yPos, scale, quaternionf, quaternionf1, entity); + renderEntityInInventory(render, xPos, yPos, scale, force2dSize, quaternionf, quaternionf1, entity); } } } catch (Throwable e) { @@ -200,12 +200,20 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo } public static void renderEntityInInventoryFollowsMouse(GuiRender render, double pX, double pY, double pScale, float offsetX, float offsetY, LivingEntity pEntity) { + renderEntityInInventoryFollowsMouse(render, pX, pY, pScale, false, offsetX, offsetY, pEntity); + } + + public static void renderEntityInInventoryFollowsMouse(GuiRender render, double pX, double pY, double pScale, boolean flat, float offsetX, float offsetY, LivingEntity pEntity) { float xAngle = (float)Math.atan(offsetX / 40.0F); float yAngle = (float)Math.atan(offsetY / 40.0F); - renderEntityInInventoryFollowsAngle(render, pX, pY, pScale, xAngle, yAngle, pEntity); + renderEntityInInventoryFollowsAngle(render, pX, pY, pScale, flat, xAngle, yAngle, pEntity); } public static void renderEntityInInventoryFollowsAngle(GuiRender render, double pX, double pY, double pScale, float angleX, float angleY, LivingEntity pEntity) { + renderEntityInInventoryFollowsAngle(render, pX, pY, pScale, false, angleX, angleY, pEntity); + } + + public static void renderEntityInInventoryFollowsAngle(GuiRender render, double pX, double pY, double pScale, boolean flat, float angleX, float angleY, LivingEntity pEntity) { Quaternionf quaternionf = (new Quaternionf()).rotateZ((float)Math.PI); Quaternionf quaternionf1 = (new Quaternionf()).rotateX(angleY * 20.0F * ((float)Math.PI / 180F)); quaternionf.mul(quaternionf1); @@ -219,7 +227,7 @@ public static void renderEntityInInventoryFollowsAngle(GuiRender render, double pEntity.setXRot(-angleY * 20.0F); pEntity.yHeadRot = pEntity.getYRot(); pEntity.yHeadRotO = pEntity.getYRot(); - renderEntityInInventory(render, pX, pY, pScale, quaternionf, quaternionf1, pEntity); + renderEntityInInventory(render, pX, pY, pScale, flat, quaternionf, quaternionf1, pEntity); pEntity.yBodyRot = f2; pEntity.setYRot(f3); pEntity.setXRot(f4); @@ -228,6 +236,10 @@ public static void renderEntityInInventoryFollowsAngle(GuiRender render, double } public static void renderEntityInInventoryWithRotation(GuiRender render, double xPos, double yPos, double scale, double rotation, LivingEntity living) { + renderEntityInInventoryWithRotation(render, xPos, yPos, scale, false, rotation, living); + } + + public static void renderEntityInInventoryWithRotation(GuiRender render, double xPos, double yPos, double scale, boolean flat, double rotation, LivingEntity living) { Quaternionf quaternionf = new Quaternionf().rotateZ((float)Math.PI); Quaternionf quaternionf1 = Axis.YP.rotationDegrees((float) rotation); quaternionf.mul(quaternionf1); @@ -241,7 +253,7 @@ public static void renderEntityInInventoryWithRotation(GuiRender render, double living.setXRot(0); living.yHeadRot = living.getYRot(); living.yHeadRotO = living.getYRot(); - renderEntityInInventory(render, xPos, yPos, scale, quaternionf, quaternionf1, living); + renderEntityInInventory(render, xPos, yPos, scale, flat, quaternionf, quaternionf1, living); living.yBodyRot = f2; living.setYRot(f3); living.setXRot(f4); @@ -250,9 +262,13 @@ public static void renderEntityInInventoryWithRotation(GuiRender render, double } public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, Entity pEntity) { + renderEntityInInventory(render, pX, pY, pScale, false, quat, pCameraOrientation, pEntity); + } + + public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, boolean flat, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, Entity pEntity) { render.pose().pushPose(); render.pose().translate(pX, pY, 50.0D); - render.pose().mulPoseMatrix((new Matrix4f()).scaling((float)pScale, (float)pScale, (float)(-pScale))); + render.pose().mulPoseMatrix((new Matrix4f()).scaling((float)pScale, (float)pScale, flat ? -1 : (float)(-pScale))); render.pose().mulPose(quat); Lighting.setupForEntityInInventory(); EntityRenderDispatcher entityrenderdispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); From 3e46ee2b400d49599915ff17a42b9cc3e5d7a2bd Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 May 2024 17:23:33 +0930 Subject: [PATCH 37/87] Mark LexForge as supported in publishing metadata. --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index e4dea2da..5b1e73bb 100644 --- a/build.gradle +++ b/build.gradle @@ -118,7 +118,7 @@ def publishingMetadataTask = tasks.register("publishingMetadata") { 'mcVersion' : "${mc_version}", 'version' : "${mod_version}", 'classifier' : 'universal', - 'modLoader' : 'neoforge', + 'modLoader' : ['neoforge', 'forge'], 'curseforgeId': '242818', 'modrinthId' : '2gq0ALnz' ] From 3bf35a18e97b70735805758ac8e19a194867ee1c Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 12 May 2024 17:24:14 +0930 Subject: [PATCH 38/87] Add support for rendering items to webp, improve performance. --- .../lib/internal/ItemFileRenderer.java | 309 +++++++++++++----- .../client/RenderItemToFileCommand.java | 51 ++- 2 files changed, 260 insertions(+), 100 deletions(-) diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index cd861795..8aef2588 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -1,5 +1,6 @@ package codechicken.lib.internal; +import com.google.common.base.Suppliers; import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.platform.NativeImage; @@ -7,28 +8,29 @@ import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexSorting; import net.covers1624.quack.image.AnimatedGifEncoder; -import net.covers1624.quack.io.IOUtils; -import net.covers1624.quack.util.SneakyUtils; +import net.covers1624.quack.platform.OperatingSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.item.ItemStack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.lwjgl.opengl.GL11; import javax.imageio.ImageIO; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import java.util.function.Supplier; /** * Mostly internal, intended for developer use. @@ -43,144 +45,281 @@ public class ItemFileRenderer { private static final Logger LOGGER = LogManager.getLogger(); private static final LinkedList tasks = new LinkedList<>(); - private static final List gifTasks = new LinkedList<>(); + private static final Path OUTPUT = Paths.get("exports"); + private static @Nullable RenderTarget target; - public static void addRenderTask(ItemStack stack, Path file, int resolution) { - tasks.add(new RenderTask(stack, file, resolution)); + public static void renderStatic(ItemStack stack, String file, int resolution) { + tasks.add(new StaticRenderTask(stack, resolution, OUTPUT.resolve(file))); } - public static void addGifRenderTask(ItemStack stack, Path file, int resolution, int fps, int duration) { - gifTasks.add(new GifRenderTask(stack, file, resolution, fps, duration)); + public static void addGifRenderTask(ItemStack stack, String file, int resolution, int fps, int duration) { + tasks.add(new GifRenderTask(stack, resolution, OUTPUT.resolve(file), fps, duration)); } - public static void tick() { - renderStackToFile(); - renderGifs(); - } + public static boolean addWebpRenderTask(ItemStack stack, String file, int resolution, int fps, int duration) { + if (!WebpRenderTask.isFfmpegAvailable()) return false; - private static void renderStackToFile() { - if (tasks.isEmpty()) return; + tasks.add(new WebpRenderTask(stack, resolution, OUTPUT.resolve(file), fps, duration)); + return true; + } - RenderTask task = tasks.pop(); - takeItemScreenshot(task.stack, task.resolution, image -> { - try { - image.writeToFile(IOUtils.makeParents(task.file)); - } catch (IOException ex) { - LOGGER.error("Failed to write image to file.", ex); - } - }); + public static void tick() { + RenderTask task = tasks.peek(); + if (task != null && guardRender(task)) { + tasks.pop(); + } } - private static void renderGifs() { - gifTasks.removeIf(GifRenderTask::render); + private static boolean guardRender(RenderTask task) { + try { + return task.render(); + } catch (Throwable ex) { + LOGGER.error("Failed to render.", ex); + return true; + } } - private static void takeItemScreenshot(ItemStack stack, int res, Consumer cons) { - Minecraft mc = Minecraft.getInstance(); - RenderTarget mainTarget = mc.getMainRenderTarget(); - PoseStack pStack = RenderSystem.getModelViewStack(); - GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); + private static abstract class RenderTask { + + private static final boolean DEBUG = Boolean.getBoolean("ccl.ItemFileRenderer.debug"); + + protected final ItemStack stack; - if (mainTarget.width < res || mainTarget.height < res) { - // TODO explode instead? - LOGGER.warn("Window is not at least 512x512 make it bigger! Your image is probably cropped a bit."); + protected final int resolution; + protected final Path path; + + private RenderTask(ItemStack stack, int resolution, Path path) { + this.stack = stack; + this.resolution = resolution; + this.path = path; } - Matrix4f ortho = new Matrix4f().setOrtho(0, mainTarget.width * 16F / res, mainTarget.height * 16F / res, 0, -3000, 3000); - RenderSystem.setProjectionMatrix(ortho, VertexSorting.ORTHOGRAPHIC_Z); + /** + * Perform the render operation. + * + * @return If the render operation is complete. + */ + protected abstract boolean render() throws IOException; - pStack.pushPose(); - pStack.setIdentity(); - RenderSystem.applyModelViewMatrix(); + protected NativeImage takeItemScreenshot() { + long start = System.nanoTime(); + Minecraft mc = Minecraft.getInstance(); + PoseStack pStack = RenderSystem.getModelViewStack(); + GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); - mainTarget.bindWrite(true); - GL11.glClearColor(0, 0, 0, 0); - GL11.glClearDepth(1.0); - GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + if (target == null || target.width < resolution || target.height < resolution) { + if (target == null) { + target = new RenderTarget(true) { }; + } + target.resize(resolution, resolution, Minecraft.ON_OSX); + } - Lighting.setupFor3DItems(); - RenderSystem.enableCull(); + Matrix4f ortho = new Matrix4f().setOrtho(0, resolution * 16F / resolution, resolution * 16F / resolution, 0, -3000, 3000); + RenderSystem.setProjectionMatrix(ortho, VertexSorting.ORTHOGRAPHIC_Z); - guiGraphics.renderItem(stack, 0, 0); + pStack.pushPose(); + pStack.setIdentity(); + RenderSystem.applyModelViewMatrix(); + target.bindWrite(true); - try (NativeImage fullScreenshot = new NativeImage(mainTarget.width, mainTarget.height, false); - NativeImage subImage = new NativeImage(res, res, false)) { - RenderSystem.bindTexture(mainTarget.getColorTextureId()); - fullScreenshot.downloadTexture(0, false); - fullScreenshot.flipY(); - fullScreenshot.resizeSubRectTo(0, 0, res, res, subImage); - cons.accept(subImage); - } + GL11.glClearColor(0, 0, 0, 0); + GL11.glClearDepth(1.0); + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + + Lighting.setupFor3DItems(); + RenderSystem.enableCull(); + long preRender = System.nanoTime(); + if (DEBUG) LOGGER.info("Setup: {}ns", preRender - start); + + guiGraphics.renderItem(stack, 0, 0); + + long postRender = System.nanoTime(); + if (DEBUG) LOGGER.info("Render: {}ns", postRender - preRender); + + NativeImage image = new NativeImage(resolution, resolution, false); + target.bindRead(); + image.downloadTexture(0, false); + image.flipY(); + if (DEBUG) LOGGER.info("Screenshot: {}ns", System.nanoTime() - postRender); + + pStack.popPose(); + RenderSystem.applyModelViewMatrix(); - pStack.popPose(); - RenderSystem.applyModelViewMatrix(); - mainTarget.unbindWrite(); + target.unbindWrite(); + return image; + } } - private record RenderTask(ItemStack stack, Path file, int resolution) { + private static class StaticRenderTask extends RenderTask { + + private StaticRenderTask(ItemStack stack, int resolution, Path path) { + super(stack, resolution, path); + } + + @Override + protected boolean render() throws IOException { + try (NativeImage image = takeItemScreenshot()) { + image.flipY(); + image.writeToFile(path); + } + return true; + } } - private static final class GifRenderTask { + private static abstract class AnimatedRenderTask extends RenderTask { - public final ItemStack stack; - public final Path file; - private final int resolution; - public final int fps; - public final long targetDuration; + protected final int fps; + protected final long targetDuration; - public final List frames; - public final long frameDelay; + protected final List frames; + protected final long frameDelay; - public long startTime = -1; - public long lastFrame; + protected long startTime = -1; + protected long lastFrame; - private GifRenderTask(ItemStack stack, Path file, int resolution, int fps, int targetDuration) { - this.stack = stack; - this.file = file; - this.resolution = resolution; + private @Nullable CompletableFuture finalizeTask; + + private AnimatedRenderTask(ItemStack stack, int resolution, Path path, int fps, int duration) { + super(stack, resolution, path); this.fps = fps; - this.targetDuration = TimeUnit.SECONDS.toMillis(targetDuration); + this.targetDuration = TimeUnit.SECONDS.toMillis(duration); - frames = new ArrayList<>(targetDuration * fps); + frames = new ArrayList<>(duration * fps); frameDelay = (long) ((1F / fps) * 1000F); } - public boolean render() { + @Override + protected boolean render() { long currTime = System.currentTimeMillis(); if (startTime == -1) { startTime = currTime; } if (startTime + targetDuration <= currTime) { - CompletableFuture.runAsync(this::finishGif); - return true; + if (finalizeTask == null) { + finalizeTask = CompletableFuture.runAsync(() -> { + try { + serialize(); + } catch (Throwable ex) { + LOGGER.error("Failed to serialize item render task.", ex); + } + }); + } + return finalizeTask.isDone(); } // Wait more for next frame. if (lastFrame + frameDelay > currTime) return false; lastFrame = currTime; - takeItemScreenshot(stack, resolution, SneakyUtils.sneak(e -> frames.add(e.asByteArray()))); - LOGGER.info("Captured gif frame {} / {}", frames.size(), ((targetDuration / 1000) * fps)); + frames.add(takeItemScreenshot()); + LOGGER.info("Captured frame {} / {}", frames.size(), ((targetDuration / 1000) * fps)); return false; } - private void finishGif() { - LOGGER.info("Writing gif.."); - try (OutputStream os = Files.newOutputStream(file)) { + protected abstract void serialize() throws IOException; + } + + private static class GifRenderTask extends AnimatedRenderTask { + + private GifRenderTask(ItemStack stack, int resolution, Path path, int fps, int duration) { + super(stack, resolution, path, fps, duration); + } + + @Override + protected void serialize() throws IOException { + try (OutputStream os = Files.newOutputStream(path)) { AnimatedGifEncoder encoder = new AnimatedGifEncoder(); encoder.start(os); encoder.setDelay((int) frameDelay); encoder.setRepeat(0); // Always repeat. encoder.setQuality(1); // Best quality possible. for (int i = 0; i < frames.size(); i++) { - byte[] frame = frames.get(i); LOGGER.info("Encoding Frame {} / {}", i + 1, frames.size()); - encoder.addFrame(ImageIO.read(new ByteArrayInputStream(frame))); + NativeImage frame = frames.get(i); + try (frame) { + encoder.addFrame(ImageIO.read(new ByteArrayInputStream(frame.asByteArray()))); + } } encoder.finish(); LOGGER.info("Finished writing gif."); + } + } + } + + private static class WebpRenderTask extends AnimatedRenderTask { + + public static final Supplier<@Nullable String> FFMPEG_BINARY = Suppliers.memoize(() -> { + String ffmpeg = System.getProperty("ccl.ffmpeg", "ffmpeg" + (OperatingSystem.current().isWindows() ? ".exe" : "")); + LOGGER.info("Probing for ffmpeg with {}", ffmpeg); + try { + int ret = runFfmpeg(List.of(ffmpeg, "-version"), LOGGER::info); + if (ret == 0) { + LOGGER.info("ffmpeg available via {}", ffmpeg); + return ffmpeg; + } + LOGGER.error("Failed to find working ffmpeg. Got exit code: {}", ret); } catch (IOException ex) { - LOGGER.error("Failed to write gif.", ex); + LOGGER.error("Failed to find ffmpeg. Exception whilst running command.", ex); + } + return null; + }); + + public static boolean isFfmpegAvailable() { + return FFMPEG_BINARY.get() != null; + } + + private WebpRenderTask(ItemStack stack, int resolution, Path path, int fps, int duration) { + super(stack, resolution, path, fps, duration); + } + + @Override + protected void serialize() throws IOException { + Path tempDir = path.getParent().resolve(path.getFileName() + ".tmp"); + Files.createDirectory(tempDir); + LOGGER.info("Dumping frames to temp directory.."); + int i = 0; + List tempFiles = new ArrayList<>(frames.size() + 1); + for (NativeImage frame : frames) { + try (frame) { + Path file = tempDir.resolve(i++ + ".png"); + tempFiles.add(file); + frame.writeToFile(file); + } + } + tempFiles.add(tempDir); + + int ret = runFfmpeg( + List.of( + FFMPEG_BINARY.get(), + "-y", + "-framerate", String.valueOf(fps), + "-i", tempDir.toAbsolutePath() + "/%d.png", + "-loop", "0", + "-lossless", "1", + "-compression_level", "0", + path.toAbsolutePath().toString() + ), + LOGGER::info + ); + if (ret != 0) { + LOGGER.error("ffmpeg exited with exit code {}", ret); + } else { + LOGGER.info("ffmpeg success!"); + } + + for (Path tempFile : tempFiles) { + Files.deleteIfExists(tempFile); + } + } + + private static int runFfmpeg(List args, Consumer out) throws IOException { + ProcessBuilder pb = new ProcessBuilder(args); + pb.redirectErrorStream(true); + Process proc = pb.start(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8))) { + reader.lines().forEach(out); } + proc.onExit().join(); + return proc.exitValue(); } } } diff --git a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java index b08921fd..9a9a747b 100644 --- a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java @@ -13,9 +13,6 @@ import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; -import java.nio.file.Path; -import java.nio.file.Paths; - import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal; @@ -26,7 +23,7 @@ public class RenderItemToFileCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ccl") - .then(literal("render_held_to_file") + .then(literal("render_held") .then(argument("resolution", IntegerArgumentType.integer(16)) .then(argument("name", StringArgumentType.greedyString()) .executes(e -> renderToFile(e, getResolution(e))) @@ -36,16 +33,16 @@ public static void register(CommandDispatcher dispatcher) { .executes(e -> renderToFile(e, ItemFileRenderer.DEFAULT_RES)) ) ) - .then(literal("render_held_to_gif") + .then(literal("render_held_anim") .then(argument("fps", IntegerArgumentType.integer(5, 75)) .then(argument("duration", IntegerArgumentType.integer()) .then(argument("resolution", IntegerArgumentType.integer(16)) .then(argument("name", StringArgumentType.greedyString()) - .executes(e -> renderToGif(e, getResolution(e))) + .executes(e -> renderAnim(e, getResolution(e))) ) ) .then(argument("name", StringArgumentType.greedyString()) - .executes(e -> renderToGif(e, ItemFileRenderer.DEFAULT_RES)) + .executes(e -> renderAnim(e, ItemFileRenderer.DEFAULT_RES)) ) ) ) @@ -54,33 +51,57 @@ public static void register(CommandDispatcher dispatcher) { } private static int renderToFile(CommandContext ctx, int resolution) { - Path path = getPath(ctx, "png"); + String path = getPath(ctx); ItemStack held = getHeldItem(); ctx.getSource().sendSuccess(() -> Component.literal("Queued item render to file: " + path), false); - ItemFileRenderer.addRenderTask(held, path, resolution); + ItemFileRenderer.renderStatic(held, path, resolution); return 0; } - private static int renderToGif(CommandContext ctx, int resolution) { + private static int renderAnim(CommandContext ctx, int resolution) { CommandSourceStack src = ctx.getSource(); int fps = IntegerArgumentType.getInteger(ctx, "fps"); int duration = IntegerArgumentType.getInteger(ctx, "duration"); - Path path = getPath(ctx, "gif"); + String path = getPath(ctx); ItemStack held = getHeldItem(); - src.sendSuccess(() -> Component.literal("Queued item render to gif: " + path), false); - ItemFileRenderer.addGifRenderTask(held, path, resolution, fps, duration); + int lastSlash = path.lastIndexOf('/'); + int lastDot = path.lastIndexOf('.', lastSlash != -1 ? lastSlash : path.length() - 1); + String ext = lastDot != -1 ? path.substring(lastDot + 1) : ""; + + String finalPath; + if (ext.isEmpty()) { + ext = "gif"; + finalPath = path + ".gif"; + } else { + finalPath = path; + } + + switch (ext) { + case "gif" -> { + ItemFileRenderer.addGifRenderTask(held, finalPath, resolution, fps, duration); + src.sendSuccess(() -> Component.literal("Queued item render to gif: " + finalPath), false); + } + case "webp" -> { + if (!ItemFileRenderer.addWebpRenderTask(held, path, resolution, fps, duration)) { + src.sendFailure(Component.literal("Failed to queue render for webp, ffmpeg is not accessible. Either make it accessible on PATH, or set the `ccl.ffmpeg` system property.")); + } else { + src.sendSuccess(() -> Component.literal("Queued item render to webp: " + path), false); + } + } + } + return 0; } - private static Path getPath(CommandContext ctx, String extension) { + private static String getPath(CommandContext ctx) { String str = StringArgumentType.getString(ctx, "name"); if (str.contains("..")) { throw new CommandRuntimeException(Component.literal("'..' is not allowed in name.")); } - return Paths.get("exports", str + "." + extension); + return str; } public static int getResolution(CommandContext ctx) { From 0bf9da4f705dafc43eb830c8c9e4fe4cd1610c78 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Fri, 31 May 2024 16:23:42 +1000 Subject: [PATCH 39/87] A couple minor gui fixes. - Fixed first tick gui element position glitch with some elements. - Fixed inability to manipulate opaque manipulable elements. --- .../lib/gui/modular/elements/GuiElement.java | 1 + .../gui/modular/elements/GuiManipulable.java | 65 ++++++++++--------- 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java index 1282998c..a94c1909 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java @@ -134,6 +134,7 @@ protected void applyQueuedChildUpdates() { if (!addedQueue.isEmpty()) { childElements.addAll(addedQueue); + addedQueue.forEach(ConstrainedGeometry::clearGeometryCache); addedQueue.clear(); } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java index 239ec6e5..336dacdc 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java @@ -86,7 +86,7 @@ public class GuiManipulable extends GuiElement implements Conten public GuiManipulable(@NotNull GuiParent parent) { super(parent); - this.contentElement = new GuiElement<>(this) + this.contentElement = new ContentElement(this) .constrain(LEFT, Constraint.dynamic(() -> (double) xMin)) .constrain(RIGHT, Constraint.dynamic(() -> (double) xMax)) .constrain(TOP, Constraint.dynamic(() -> (double) yMin)) @@ -335,34 +335,6 @@ public void startDragging() { dragPos = true; } - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (super.mouseClicked(mouseX, mouseY, button)) return true; - - boolean posFlag = moveHandle != null && moveHandle.isMouseOver(); - boolean topFlag = topHandle != null && topHandle.isMouseOver(); - boolean leftFlag = leftHandle != null && leftHandle.isMouseOver(); - boolean bottomFlag = bottomHandle != null && bottomHandle.isMouseOver(); - boolean rightFlag = rightHandle != null && rightHandle.isMouseOver(); - - if (posFlag || topFlag || leftFlag || bottomFlag || rightFlag) { - dragXOffset = (int) (mouseX - xMin); - dragYOffset = (int) (mouseY - yMin); - isDragging = true; - if (posFlag) { - dragPos = true; - } else { - dragTop = topFlag; - dragLeft = leftFlag; - dragBottom = bottomFlag; - dragRight = rightFlag; - } - return true; - } - - return false; - } - @Override public void mouseMoved(double mouseX, double mouseY) { if (isDragging) { @@ -454,4 +426,39 @@ public boolean isResizing() { public interface PositionRestraint { void restrainPosition(GuiManipulable draggable); } + + private class ContentElement extends GuiElement { + + public ContentElement(@NotNull GuiParent parent) { + super(parent); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (super.mouseClicked(mouseX, mouseY, button)) return true; + + boolean posFlag = moveHandle != null && moveHandle.isMouseOver(); + boolean topFlag = topHandle != null && topHandle.isMouseOver(); + boolean leftFlag = leftHandle != null && leftHandle.isMouseOver(); + boolean bottomFlag = bottomHandle != null && bottomHandle.isMouseOver(); + boolean rightFlag = rightHandle != null && rightHandle.isMouseOver(); + + if (posFlag || topFlag || leftFlag || bottomFlag || rightFlag) { + dragXOffset = (int) (mouseX - xMin); + dragYOffset = (int) (mouseY - yMin); + isDragging = true; + if (posFlag) { + dragPos = true; + } else { + dragTop = topFlag; + dragLeft = leftFlag; + dragBottom = bottomFlag; + dragRight = rightFlag; + } + return true; + } + + return false; + } + } } From 32f2860577d00fba1090c456b9d59103966f1216 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Wed, 3 Jul 2024 17:41:03 +0930 Subject: [PATCH 40/87] Add helper for registering lang entries. --- src/main/java/codechicken/lib/datagen/LanguageProvider.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/codechicken/lib/datagen/LanguageProvider.java b/src/main/java/codechicken/lib/datagen/LanguageProvider.java index b7862be5..87e232c3 100644 --- a/src/main/java/codechicken/lib/datagen/LanguageProvider.java +++ b/src/main/java/codechicken/lib/datagen/LanguageProvider.java @@ -10,6 +10,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraftforge.data.event.GatherDataEvent; @@ -72,6 +73,7 @@ private void save(CachedOutput cache, Object object, Path target) { //@formatter:off public void add(Block key, String name) { add(key.getDescriptionId(), name); } public void add(Item key, String name) { add(key.getDescriptionId(), name); } + public void add(Supplier key, String name) { add(key.get().asItem(), name); } public void add(ItemStack key, String name) { add(key.getDescriptionId(), name); } public void add(Enchantment key, String name) { add(key.getDescriptionId(), name); } public void add(MobEffect key, String name) { add(key.getDescriptionId(), name); } From 54bca18fc51ba9b7baa35f3c088bfd72df98076e Mon Sep 17 00:00:00 2001 From: covers1624 Date: Wed, 3 Jul 2024 17:53:04 +0930 Subject: [PATCH 41/87] Add autoWidth support to GuiText. --- .../java/codechicken/lib/gui/modular/elements/GuiText.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java index de758c31..ad847e6d 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java @@ -68,6 +68,11 @@ public GuiText autoHeight() { return this; } + public GuiText autoWidth() { + constrain(GeoParam.WIDTH, dynamic(() -> (double) font().width(getText()))); + return this; + } + public GuiText setTextSupplier(@NotNull Supplier<@Nullable Component> textSupplier) { this.text = textSupplier; return this; From d0dedce9252c01f16af5d2388a7488a608eac586 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Wed, 3 Jul 2024 18:00:53 +0930 Subject: [PATCH 42/87] Copy CCGuiTextures into a generic util class. --- .../lib/gui/modular/sprite/CCGuiTextures.java | 3 +- .../lib/gui/modular/sprite/GuiTextures.java | 88 +++++++++++++++++++ .../gui/modular/sprite/ModAtlasHolder.java | 11 +++ .../codechicken/lib/internal/ClientInit.java | 2 +- 4 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java b/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java index a3aaf28d..a59ec2bf 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java @@ -14,6 +14,7 @@ *

* Created by brandon3055 on 21/10/2023 */ +// TODO 1.20.4, use GuiTextures instance. public class CCGuiTextures { private static final ModAtlasHolder ATLAS_HOLDER = new ModAtlasHolder(CodeChickenLib.MOD_ID, "textures/atlas/gui.png", "gui"); private static final Map MATERIAL_CACHE = new HashMap<>(); @@ -56,4 +57,4 @@ public static Supplier getter(Supplier texture) { public static Material getUncached(String texture) { return new Material(ATLAS_HOLDER.atlasLocation(), new ResourceLocation(CodeChickenLib.MOD_ID, "gui/" + texture), ATLAS_HOLDER::getSprite); } -} \ No newline at end of file +} diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java b/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java new file mode 100644 index 00000000..a21cef63 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java @@ -0,0 +1,88 @@ +package codechicken.lib.gui.modular.sprite; + +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; +import net.minecraftforge.data.loading.DatagenModLoader; +import net.minecraftforge.eventbus.api.IEventBus; + +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +import static java.util.Objects.requireNonNull; + +/** + * Gui texture handler implementation. + * This sets up a custom atlas that will be populated with all textures in "modid:textures/gui/" + *

+ * Created by brandon3055 on 21/10/2023 + */ +public class GuiTextures { + + private final String modId; + private final @Nullable ModAtlasHolder atlasHolder; + private final Map materialCache = new HashMap<>(); + + public GuiTextures(String modId) { + this.modId = modId; + if (DatagenModLoader.isRunningDataGen()) { + atlasHolder = null; + } else { + atlasHolder = new ModAtlasHolder(modId, "textures/atlas/gui.png", "gui"); + } + } + + /** + * Called to initialize the {@link GuiTextures} helper + * + * @param bus Your mod event bus. + */ + public void init(IEventBus bus) { + bus.addListener(this::onRegisterReloadListeners); + } + + private void onRegisterReloadListeners(RegisterClientReloadListenersEvent event) { + getAtlasHolder().init(); + event.registerReloadListener(getAtlasHolder()); + } + + /** + * @return The underlying {@link ModAtlasHolder} instance. + */ + public ModAtlasHolder getAtlasHolder() { + return requireNonNull(atlasHolder, "AtlasHolder not available when datagen is running."); + } + + /** + * Returns a cached Material for the specified gui texture. + * Warning: Do not use this if you intend to use the material with multiple render types. + * The material will cache the first render type it is used with. + * Instead use {@link #getUncached(String)} + * + * @param texture The texture path relative to "modid:gui/" + */ + public Material get(String texture) { + return materialCache.computeIfAbsent(modId + ":" + texture, e -> getUncached(texture)); + } + + public Material get(Supplier texture) { + return get(texture.get()); + } + + public Supplier getter(Supplier texture) { + return () -> get(texture.get()); + } + + /** + * Use this to retrieve a new uncached material for the specified gui texture. + * Feel free to hold onto the returned material. + * Storing it somewhere is more efficient than recreating it every render frame. + * + * @param texture The texture path relative to "modid:gui/" + * @return A new Material for the specified gui texture. + */ + public Material getUncached(String texture) { + return new Material(getAtlasHolder().atlasLocation(), new ResourceLocation(modId, "gui/" + texture), getAtlasHolder()::getSprite); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java index 9d361894..d8260d6b 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java @@ -4,6 +4,7 @@ import net.minecraft.client.renderer.texture.SpriteLoader; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.resources.PreparableReloadListener; @@ -22,6 +23,7 @@ * Created by brandon3055 on 20/08/2023 */ public class ModAtlasHolder implements PreparableReloadListener, AutoCloseable { + private final TextureAtlas textureAtlas; private final ResourceLocation atlasLocation; private final ResourceLocation atlasInfoLocation; @@ -42,6 +44,14 @@ public ModAtlasHolder(String modid, String atlasLocation, String atlasInfoLocati this.atlasLocation = new ResourceLocation(modid, atlasLocation); this.textureAtlas = new TextureAtlas(this.atlasLocation); this.modid = modid; + // TODO remove in 1.20.4 + TextureManager textureManager = Minecraft.getInstance().getTextureManager(); + if (textureManager != null) { + textureManager.register(this.textureAtlas.location(), this.textureAtlas); + } + } + + public void init() { Minecraft.getInstance().getTextureManager().register(this.textureAtlas.location(), this.textureAtlas); } @@ -77,6 +87,7 @@ public void close() { } public static class ModResourceManager implements ResourceManager { + private final ResourceManager wrapped; private final String modid; diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java index 1e1eb056..5190476d 100644 --- a/src/main/java/codechicken/lib/internal/ClientInit.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -82,7 +82,7 @@ private static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event.register("class", new ClassModelLoader()); } - public static void onResourceReload(RegisterClientReloadListenersEvent event) { + private static void onResourceReload(RegisterClientReloadListenersEvent event) { event.registerReloadListener(CCGuiTextures.getAtlasHolder()); event.registerReloadListener((ResourceManagerReloadListener) e -> CursorHelper.onResourceReload()); } From f7b963f81999515e1afce2a08472119d60516e60 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Wed, 3 Jul 2024 18:01:45 +0930 Subject: [PATCH 43/87] Move some static helpers from Constraints to ConstrainedGeometry. --- .../lib/gui/modular/lib/Constraints.java | 68 +++-------- .../lib/geometry/ConstrainedGeometry.java | 107 +++++++++++++++++- 2 files changed, 114 insertions(+), 61 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java index 91c84555..6399df5e 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java @@ -2,6 +2,7 @@ import codechicken.lib.gui.modular.lib.geometry.Borders; import codechicken.lib.gui.modular.lib.geometry.ConstrainedGeometry; +import net.covers1624.quack.annotation.ReplaceWithExpr; import java.util.function.Supplier; @@ -64,7 +65,6 @@ public static void bind(ConstrainedGeometry element, ConstrainedGeometry r element.constrain(RIGHT, relative(reference.get(RIGHT), () -> -borders.right())); } - public static void size(ConstrainedGeometry element, double width, double height) { element.constrain(WIDTH, literal(width)); element.constrain(HEIGHT, literal(height)); @@ -104,8 +104,10 @@ public static void center(ConstrainedGeometry element, ConstrainedGeometry * @param reference The reference element, the element that target will be placed inside. * @param position The layout position. */ + @Deprecated + @ReplaceWithExpr ("target.placeInside") public static void placeInside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position) { - placeInside(target, reference, position, 0, 0); + target.placeInside(reference, position); } /** @@ -119,33 +121,10 @@ public static void placeInside(ConstrainedGeometry target, ConstrainedGeometr * @param xOffset Optional X offset to be applied to the final position. * @param yOffset Optional Y offset to be applied to the final position. */ + @Deprecated + @ReplaceWithExpr ("target.placeInside") public static void placeInside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position, double xOffset, double yOffset) { - switch (position) { - case TOP_LEFT -> target - .constrain(TOP, relative(reference.get(TOP), yOffset)) - .constrain(LEFT, relative(reference.get(LEFT), xOffset)); - case TOP_CENTER -> target - .constrain(TOP, relative(reference.get(TOP), yOffset)) - .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); - case TOP_RIGHT -> target - .constrain(TOP, relative(reference.get(TOP), yOffset)) - .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); - case MIDDLE_RIGHT -> target - .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) - .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); - case BOTTOM_RIGHT -> target - .constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) - .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); - case BOTTOM_CENTER -> target - .constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) - .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); - case BOTTOM_LEFT -> target - .constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) - .constrain(LEFT, relative(reference.get(LEFT), xOffset)); - case MIDDLE_LEFT -> target - .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) - .constrain(LEFT, relative(reference.get(LEFT), xOffset)); - } + target.placeInside(reference, position, xOffset, yOffset); } /** @@ -157,8 +136,10 @@ public static void placeInside(ConstrainedGeometry target, ConstrainedGeometr * @param reference The reference element, the element that target will be placed outside of. * @param position The layout position. */ + @Deprecated + @ReplaceWithExpr ("target.placeOutside") public static void placeOutside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position) { - placeOutside(target, reference, position, 0, 0); + target.placeOutside(reference, position); } /** @@ -172,33 +153,10 @@ public static void placeOutside(ConstrainedGeometry target, ConstrainedGeomet * @param xOffset Optional X offset to be applied to the final position. * @param yOffset Optional Y offset to be applied to the final position. */ + @Deprecated + @ReplaceWithExpr ("target.placeOutside") public static void placeOutside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position, double xOffset, double yOffset) { - switch (position) { - case TOP_LEFT -> target - .constrain(BOTTOM, relative(reference.get(TOP), yOffset)) - .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); - case TOP_CENTER -> target - .constrain(BOTTOM, relative(reference.get(TOP), yOffset)) - .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); - case TOP_RIGHT -> target - .constrain(BOTTOM, relative(reference.get(TOP), yOffset)) - .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); - case MIDDLE_RIGHT -> target - .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) - .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); - case BOTTOM_RIGHT -> target - .constrain(TOP, relative(reference.get(BOTTOM), yOffset)) - .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); - case BOTTOM_CENTER -> target - .constrain(TOP, relative(reference.get(BOTTOM), yOffset)) - .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); - case BOTTOM_LEFT -> target - .constrain(TOP, relative(reference.get(BOTTOM), yOffset)) - .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); - case MIDDLE_LEFT -> target - .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) - .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); - } + target.placeOutside(reference, position, xOffset, yOffset); } public enum LayoutPos { diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java index b0c62353..17f5a19a 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java @@ -1,11 +1,14 @@ package codechicken.lib.gui.modular.lib.geometry; import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.Constraints; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.function.Supplier; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.midPoint; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.relative; import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; /** @@ -213,12 +216,16 @@ public GeoRef get(GeoParam param) { return new GeoRef(this, param); } + @SuppressWarnings ("unchecked") + private T self() { + return (T) this; + } + /** * @param param The geometry parameter to be constrained. * @param constraint The constraint to apply * @return This Element. */ - @SuppressWarnings ("unchecked") public T constrain(GeoParam param, @Nullable Constraint constraint) { if (constraint != null && constraint.axis() != null && constraint.axis() != param.axis) { throw new IllegalStateException("Attempted to apply constraint for axis: " + constraint.axis() + ", to Parameter: " + param); @@ -228,7 +235,7 @@ public T constrain(GeoParam param, @Nullable Constraint constraint) { } else if (param.axis == Axis.Y) { constrainY(param, constraint); } - return (T) this; + return self(); } /** @@ -236,11 +243,10 @@ public T constrain(GeoParam param, @Nullable Constraint constraint) { * Convenient when reconfiguring an elements constraints or applying constraints to an element * with an existing, unknown constraint configuration. */ - @SuppressWarnings ("unchecked") public T clearConstraints() { xMin = xMax = xSize = yMin = yMax = ySize = null; xAxis = yAxis = AxisConfig.NONE; - return (T) this; + return self(); } private void constrainX(GeoParam param, @Nullable Constraint constraint) { @@ -279,11 +285,10 @@ private void constrainY(GeoParam param, @Nullable Constraint constraint) { * @param strictMode Enable strict mode. * @return the geometry object. */ - @SuppressWarnings ("unchecked") public T strictMode(boolean strictMode) { this.strictMode = strictMode; //TODO Propagate to children (Will be handled in the base GuiElement) - return (T) this; + return self(); } //TODO This needs to be called from the parent element somewhere. Possibly on tick or render @@ -373,4 +378,94 @@ public Rectangle.Mutable getChildBounds() { if (!set) childBounds.setPos(xMin(), yMin()).setSize(0, 0); return childBounds; } + + //=== Layout Utilities ===// + + /** + * Constrain this element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + */ + public T placeInside(ConstrainedGeometry reference, Constraints.LayoutPos position) { + return placeInside(reference, position, 0, 0); + } + + /** + * Constrain this element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + public T placeInside(ConstrainedGeometry reference, Constraints.LayoutPos position, double xOffset, double yOffset) { + switch (position) { + case TOP_LEFT -> constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + case TOP_CENTER -> constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case TOP_RIGHT -> constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case MIDDLE_RIGHT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_RIGHT -> constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_CENTER -> constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case BOTTOM_LEFT -> constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + case MIDDLE_LEFT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + } + return self(); + } + + /** + * Constrain this element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + */ + public T placeOutside(ConstrainedGeometry reference, Constraints.LayoutPos position) { + return placeOutside(reference, position, 0, 0); + } + + /** + * Constrain this element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + public T placeOutside(ConstrainedGeometry reference, Constraints.LayoutPos position, double xOffset, double yOffset) { + switch (position) { + case TOP_LEFT -> constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + case TOP_CENTER -> constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case TOP_RIGHT -> constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case MIDDLE_RIGHT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_RIGHT -> constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_CENTER -> constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case BOTTOM_LEFT -> constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + case MIDDLE_LEFT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + } + return self(); + } } From 1ab804a294ad95f9937dbd4d7ab69d795938a56e Mon Sep 17 00:00:00 2001 From: covers1624 Date: Mon, 16 Sep 2024 22:16:42 +0930 Subject: [PATCH 44/87] Fix left-handed item rendering of IItemRenderer items. --- src/main/java/codechicken/lib/model/PerspectiveModel.java | 4 ---- src/main/java/codechicken/lib/util/TransformUtils.java | 1 + 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/codechicken/lib/model/PerspectiveModel.java b/src/main/java/codechicken/lib/model/PerspectiveModel.java index 8cf07cf9..993f08b0 100644 --- a/src/main/java/codechicken/lib/model/PerspectiveModel.java +++ b/src/main/java/codechicken/lib/model/PerspectiveModel.java @@ -41,10 +41,6 @@ default BakedModel applyTransform(ItemDisplayContext context, PoseStack pStack, pStack.scale(scale.x(), scale.y(), scale.z()); pStack.mulPose(transform.getRightRotation()); - - if (leftFlip) { - TransformUtils.applyLeftyFlip(pStack); - } return this; } return BakedModel.super.applyTransform(context, pStack, leftFlip); diff --git a/src/main/java/codechicken/lib/util/TransformUtils.java b/src/main/java/codechicken/lib/util/TransformUtils.java index 2fe126d3..2fc32062 100644 --- a/src/main/java/codechicken/lib/util/TransformUtils.java +++ b/src/main/java/codechicken/lib/util/TransformUtils.java @@ -176,6 +176,7 @@ public static ModelState stateFromItemTransforms(ItemTransforms itemTransforms) * * @param pStack The {@link PoseStack} to apply to. */ + @Deprecated (forRemoval = true) public static void applyLeftyFlip(PoseStack pStack) { if (!pStack.clear()) { Matrix4f tMat = pStack.last().pose(); From 2125097ce05943234439f807b2e682ff164b5b0f Mon Sep 17 00:00:00 2001 From: covers1624 Date: Thu, 19 Sep 2024 00:04:57 +0930 Subject: [PATCH 45/87] Fix bug with BakedVertexSource and single-object attributes. --- src/main/java/codechicken/lib/render/BakedVertexSource.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/codechicken/lib/render/BakedVertexSource.java b/src/main/java/codechicken/lib/render/BakedVertexSource.java index 57a017b1..65b6adc0 100644 --- a/src/main/java/codechicken/lib/render/BakedVertexSource.java +++ b/src/main/java/codechicken/lib/render/BakedVertexSource.java @@ -130,10 +130,7 @@ void ensureSpace(int numVertices) { if (attr == null) { attr = key.createDefault(numVertices); } else { - Object newAttr = key.createDefault(numVertices); - //noinspection SuspiciousSystemArraycopy - System.arraycopy(attr, 0, newAttr, 0, prevLen); - attr = newAttr; + attr = key.copy(unsafeCast(attr), numVertices); } attributes[aIdx] = attr; //Fill non primitive vertex attributes with new things. From 83b1a01c96f781eca59ca900caf660e1b83ba29e Mon Sep 17 00:00:00 2001 From: covers1624 Date: Thu, 19 Sep 2024 00:07:58 +0930 Subject: [PATCH 46/87] Make AttributeKey and VertexOperation registration synchronized. --- .../codechicken/lib/render/pipeline/IVertexOperation.java | 6 +++++- .../lib/render/pipeline/attribute/AttributeKey.java | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java b/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java index a8a4c247..00b74a87 100644 --- a/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java +++ b/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java @@ -8,7 +8,7 @@ public interface IVertexOperation { static int registerOperation() { - return VertexOperationRegistry.nextOperationIndex++; + return VertexOperationRegistry.nextOperationIndex(); } static int operationCount() { @@ -35,5 +35,9 @@ static int operationCount() { class VertexOperationRegistry { static int nextOperationIndex; + + private static synchronized int nextOperationIndex() { + return VertexOperationRegistry.nextOperationIndex++; + } } } diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java b/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java index 6c35d681..2cc2a4a3 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java @@ -93,7 +93,7 @@ public static class AttributeKeyRegistry { private static final Map> nameMap = new HashMap<>(); private static final List> attributeKeys = new ArrayList<>(); - private static int registerAttributeKey(AttributeKey attr) { + private static synchronized int registerAttributeKey(AttributeKey attr) { if (nameMap.containsKey(attr.name)) { throw new IllegalArgumentException("Duplicate registration of attribute with name: " + attr.name); } From 10905a968d82598ce4ac5abead1a91c238b4e112 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Thu, 19 Sep 2024 00:22:08 +0930 Subject: [PATCH 47/87] Fix AttributeKey copy for non object arrays. --- .../lib/render/pipeline/attribute/AttributeKey.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java b/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java index 2cc2a4a3..f54b73f3 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java @@ -6,6 +6,7 @@ import codechicken.lib.util.ArrayUtils; import codechicken.lib.util.Copyable; +import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -44,7 +45,7 @@ public T createDefault(int length) { @Override public T copy(T src, int length) { T dst = createDefault(length); - ArrayUtils.arrayCopy(src, 0, dst, 0, ((Object[]) src).length); + ArrayUtils.arrayCopy(src, 0, dst, 0, Array.getLength(src)); return dst; } From e3191fe9df1a6972a96a17f85e4a2038f3e8a979 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 21:45:17 +0930 Subject: [PATCH 48/87] Port to 1.20.4. --- build.gradle | 80 ++--- gradle.properties | 8 +- gradle/wrapper/gradle-wrapper.jar | Bin 62076 -> 43462 bytes gradle/wrapper/gradle-wrapper.properties | 3 +- gradlew | 22 +- gradlew.bat | 20 +- settings.gradle | 2 +- .../java/codechicken/lib/CodeChickenLib.java | 25 +- .../codechicken/lib/block/ModularBlock.java | 2 +- .../component/data/DataGenComponent.java | 8 +- .../component/data/LootTableComponent.java | 30 +- .../block/component/data/TagComponent.java | 2 +- .../block/component/data/package-info.java | 9 +- .../lib/block/component/package-info.java | 9 +- .../block/component/tile/package-info.java | 9 +- .../codechicken/lib/block/package-info.java | 9 +- .../lib/capability/CapabilityCache.java | 233 ++++++--------- .../lib/capability/SimpleCapProvider.java | 34 --- .../lib/capability/package-info.java | 4 + .../java/codechicken/lib/colour/Colour.java | 14 +- .../lib/colour/CustomGradient.java | 2 +- .../codechicken/lib/colour/EnumColour.java | 57 ++-- .../codechicken/lib/colour/package-info.java | 4 + .../lib/config/ConfigCategoryImpl.java | 4 +- .../lib/config/ConfigSyncManager.java | 68 ++++- .../lib/config/ConfigValueListImpl.java | 4 +- .../codechicken/lib/config/package-info.java | 9 +- .../lib/config/parser/package-info.java | 9 +- .../codechicken/lib/data/MCDataByteBuf.java | 2 +- .../codechicken/lib/data/MCDataInput.java | 88 +++--- .../codechicken/lib/data/MCDataOutput.java | 86 +++--- .../codechicken/lib/data/package-info.java | 4 + .../lib/datagen/ConditionalIngredient.java | 274 ++++++++--------- .../lib/datagen/DynamicTextureProvider.java | 4 +- .../lib/datagen/ItemModelProvider.java | 29 +- .../lib/datagen/LanguageProvider.java | 2 +- .../lib/datagen/LootTableProvider.java | 166 ----------- .../NoValidationBLockLootSubProvider.java | 43 +++ .../codechicken/lib/datagen/package-info.java | 4 + .../AbstractItemStackRecipeBuilder.java | 34 +-- .../datagen/recipe/AbstractRecipeBuilder.java | 107 ++----- .../lib/datagen/recipe/ConditionBuilder.java | 11 - .../datagen/recipe/FurnaceRecipeBuilder.java | 94 +++--- .../lib/datagen/recipe/RecipeBuilder.java | 22 +- .../lib/datagen/recipe/RecipeProvider.java | 142 +++++---- .../datagen/recipe/ShapedRecipeBuilder.java | 76 ++--- .../recipe/ShapelessRecipeBuilder.java | 71 ++--- .../recipe/SpecialCraftingRecipeBuilder.java | 57 ++-- .../lib/datagen/recipe/package-info.java | 4 + .../codechicken/lib/fluid/FluidUtils.java | 4 +- .../codechicken/lib/fluid/package-info.java | 4 + .../lib/gui/modular/ModularGui.java | 22 +- .../lib/gui/modular/ModularGuiContainer.java | 6 +- .../lib/gui/modular/ModularGuiScreen.java | 6 +- .../lib/gui/modular/elements/GuiButton.java | 6 +- .../gui/modular/elements/GuiEnergyBar.java | 6 +- .../modular/elements/GuiEntityRenderer.java | 26 +- .../modular/elements/GuiEventProvider.java | 16 +- .../gui/modular/elements/GuiFluidTank.java | 23 +- .../lib/gui/modular/elements/GuiSlider.java | 4 +- .../lib/gui/modular/elements/GuiSlots.java | 4 +- .../lib/gui/modular/lib/ElementEvents.java | 22 +- .../lib/gui/modular/lib/GuiRender.java | 66 ++-- .../lib/gui/modular/sprite/CCGuiTextures.java | 60 ---- .../lib/gui/modular/sprite/GuiTextures.java | 17 +- .../lib/gui/modular/sprite/Material.java | 22 -- .../gui/modular/sprite/ModAtlasHolder.java | 5 - .../codechicken/lib/internal/ClientInit.java | 44 ++- .../lib/internal/DataGenerators.java | 22 +- .../ExceptionMessageEventHandler.java | 19 +- .../lib/internal/HighlightHandler.java | 19 +- .../lib/internal/ItemFileRenderer.java | 4 +- .../TileChunkLoadHook.java | 21 +- .../lib/internal/command/CCLCommands.java | 11 +- .../internal/command/admin/CountCommand.java | 6 +- .../command/admin/KillAllCommand.java | 13 +- .../internal/command/admin/package-info.java | 4 + .../command/client/HighlightCommand.java | 13 +- .../command/client/ItemInfoCommand.java | 4 +- .../client/RenderItemToFileCommand.java | 24 +- .../internal/command/client/package-info.java | 9 +- .../internal/command/dev/package-info.java | 4 + .../lib/internal/compat/JEIPlugin.java | 12 +- .../lib/internal/compat/package-info.java | 4 + .../lib/internal/mixin/CCLMixinPlugin.java | 5 +- .../lib/internal/mixin/ItemRendererMixin.java | 6 +- .../lib/internal/mixin/dev/package-info.java | 4 + .../lib/internal/mixin/package-info.java | 4 + .../lib/internal/network/CCLNetwork.java | 18 +- .../ClientConfigurationPacketHandler.java | 21 ++ .../internal/network/ClientPacketHandler.java | 17 +- .../internal/network/LoginPacketHandler.java | 31 -- .../internal/network/ServerPacketHandler.java | 2 +- .../lib/internal/network/package-info.java | 4 + .../lib/internal/package-info.java | 9 +- .../lib/inventory/InventoryCopy.java | 17 -- .../lib/inventory/InventoryNBT.java | 22 -- .../lib/inventory/InventoryRange.java | 20 +- .../lib/inventory/InventorySimple.java | 17 -- .../lib/inventory/InventoryUtils.java | 23 +- .../lib/inventory/MappedInventoryAccess.java | 4 - .../container/ContainerExtended.java | 18 +- .../lib/inventory/container/SlotDummy.java | 6 +- .../container/data/AbstractDataStore.java | 4 +- .../inventory/container/data/FluidData.java | 3 +- .../container/data/package-info.java | 4 + .../modular/ModularGuiContainerMenu.java | 2 +- .../container/modular/ModularSlot.java | 10 +- .../container/modular/package-info.java | 4 + .../lib/inventory/container/package-info.java | 4 + .../lib/inventory/package-info.java | 4 + .../codechicken/lib/item/SimpleItemTier.java | 124 -------- .../codechicken/lib/item/package-info.java | 4 + .../codechicken/lib/math/InterpHelper.java | 4 +- .../java/codechicken/lib/math/MathHelper.java | 32 +- .../codechicken/lib/math/package-info.java | 4 + .../lib/model/ClassModelLoader.java | 6 +- .../lib/model/CompositeItemModel.java | 10 +- .../lib/model/DummyBakedModel.java | 6 +- .../codechicken/lib/model/ItemQuadBakery.java | 10 +- .../lib/model/ModelRegistryHelper.java | 37 --- src/main/java/codechicken/lib/model/Quad.java | 112 ++++--- .../AbstractBakedPropertiesModel.java | 7 +- .../model/bakedmodels/ModelProperties.java | 26 +- .../model/bakedmodels/OverrideListModel.java | 6 +- .../PerspectiveAwareBakedModel.java | 18 +- .../PerspectiveAwareLayeredModel.java | 8 +- .../model/bakedmodels/WrappedItemModel.java | 13 +- .../lib/model/bakedmodels/package-info.java | 4 + .../codechicken/lib/model/package-info.java | 4 + .../lib/model/pipeline/BakedPipeline.java | 27 +- .../lib/model/pipeline/IPipelineConsumer.java | 3 +- .../lib/model/pipeline/QuadTransformer.java | 13 +- .../lib/model/pipeline/package-info.java | 4 + .../transformers/QuadAlphaOverride.java | 2 +- .../pipeline/transformers/QuadClamper.java | 1 + .../transformers/QuadCornerKicker.java | 13 +- .../transformers/QuadFaceStripper.java | 25 +- .../transformers/QuadReInterpolator.java | 2 + .../pipeline/transformers/QuadTinter.java | 6 +- .../pipeline/transformers/package-info.java | 4 + .../java/codechicken/lib/package-info.java | 4 + .../lib/packet/ICustomPacketHandler.java | 67 ++--- .../codechicken/lib/packet/PacketCustom.java | 152 ++++------ .../lib/packet/PacketCustomChannel.java | 136 +++++++++ .../packet/PacketCustomChannelBuilder.java | 282 ------------------ .../codechicken/lib/packet/PacketSender.java | 277 +++++++++++++++++ .../lib/packet/SimpleClientPacketHandler.java | 4 +- .../lib/packet/SimpleServerPacketHandler.java | 4 +- .../codechicken/lib/packet/package-info.java | 7 + .../lib/raytracer/IndexedVoxelShape.java | 3 +- .../lib/raytracer/MergedVoxelShapeHolder.java | 55 ---- .../lib/raytracer/MultiIndexedVoxelShape.java | 3 +- .../codechicken/lib/raytracer/RayTracer.java | 30 +- .../lib/raytracer/package-info.java | 4 + .../lib/render/BakedVertexSource.java | 8 +- .../java/codechicken/lib/render/CCModel.java | 46 +-- .../lib/render/CCModelLibrary.java | 8 +- .../lib/render/CCRenderEventHandler.java | 36 +-- .../codechicken/lib/render/CCRenderState.java | 36 ++- .../codechicken/lib/render/RenderUtils.java | 10 +- .../render/block/BlockRenderingRegistry.java | 30 +- .../block/CCBlockRendererDispatcher.java | 17 +- .../lib/render/block/ICCBlockRenderer.java | 2 +- .../lib/render/block/package-info.java | 4 + .../render/buffer/BakedQuadVertexBuilder.java | 49 +-- .../lib/render/buffer/DelegateRenderType.java | 3 +- .../lib/render/buffer/VBORenderType.java | 3 +- .../lib/render/buffer/package-info.java | 4 + .../lib/render/item/IItemRenderer.java | 3 +- .../lib/render/item/map/package-info.java | 4 + .../lib/render/item/package-info.java | 4 + .../codechicken/lib/render/lighting/LC.java | 30 +- .../lib/render/lighting/LightMatrix.java | 6 +- .../lib/render/lighting/LightModel.java | 46 +-- .../render/lighting/PlanarLightMatrix.java | 6 +- .../lighting/SimpleBrightnessModel.java | 12 +- .../lib/render/lighting/package-info.java | 4 + .../lib/render/model/OBJWriter.java | 5 +- .../lib/render/model/package-info.java | 9 +- .../codechicken/lib/render/package-info.java | 4 + .../particle/CustomBreakingParticle.java | 12 +- .../particle/CustomParticleHandler.java | 16 +- .../render/particle/ICustomParticleBlock.java | 4 +- .../particle/IModelParticleProvider.java | 5 +- .../lib/render/particle/package-info.java | 4 + .../lib/render/pipeline/CCRenderPipeline.java | 47 +-- .../lib/render/pipeline/IVertexSource.java | 5 +- .../pipeline/attribute/ColourAttribute.java | 5 +- .../attribute/LightCoordAttribute.java | 7 +- .../pipeline/attribute/LightingAttribute.java | 7 +- .../pipeline/attribute/NormalAttribute.java | 5 +- .../pipeline/attribute/SideAttribute.java | 5 +- .../pipeline/attribute/package-info.java | 4 + .../lib/render/pipeline/package-info.java | 4 + .../lib/render/shader/ShaderProgram.java | 5 +- .../lib/render/shader/package-info.java | 9 +- .../lib/texture/AtlasRegistrar.java | 44 --- .../lib/texture/IIconRegister.java | 18 -- .../lib/texture/SpriteRegistryHelper.java | 114 ------- .../codechicken/lib/texture/TextureUtils.java | 84 +----- .../codechicken/lib/texture/package-info.java | 4 + .../java/codechicken/lib/util/ArrayUtils.java | 8 +- .../lib/util/Boolean2ObjectFunction.java | 17 -- .../codechicken/lib/util/ClientUtils.java | 21 +- .../codechicken/lib/util/CommonUtils.java | 14 - .../java/codechicken/lib/util/FormatUtil.java | 20 +- .../java/codechicken/lib/util/ItemUtils.java | 15 +- .../codechicken/lib/util/LambdaUtils.java | 89 ------ .../codechicken/lib/util/LazyValuePair.java | 39 --- .../java/codechicken/lib/util/LogUtils.java | 31 -- .../codechicken/lib/util/RotationUtils.java | 100 +++---- .../codechicken/lib/util/ServerUtils.java | 67 +---- .../lib/util/ThrowingBiConsumer.java | 12 - .../codechicken/lib/util/TransformUtils.java | 24 -- .../codechicken/lib/util/VectorUtils.java | 51 +--- .../codechicken/lib/util/package-info.java | 4 + .../java/codechicken/lib/vec/Cuboid6.java | 21 +- .../lib/vec/TransformationList.java | 5 +- .../java/codechicken/lib/vec/Vector3.java | 21 +- .../codechicken/lib/vec/package-info.java | 9 +- .../lib/vec/uv/IconTransformation.java | 4 +- .../lib/vec/uv/MultiIconTransformation.java | 4 +- .../lib/vec/uv/ScaledIconTransformation.java | 4 +- .../lib/vec/uv/UVTransformation.java | 2 - .../lib/vec/uv/UVTransformationList.java | 5 +- .../codechicken/lib/vec/uv/package-info.java | 9 +- .../codechicken/lib/world/package-info.java | 4 + .../resources/META-INF/accesstransformer.cfg | 150 +++++----- src/main/resources/META-INF/mods.toml | 10 +- src/main/resources/mixins.codechickenlib.json | 1 - .../lib/render/BakedVertexSourceTests.java | 4 + 232 files changed, 2497 insertions(+), 3463 deletions(-) delete mode 100644 src/main/java/codechicken/lib/capability/SimpleCapProvider.java create mode 100644 src/main/java/codechicken/lib/capability/package-info.java create mode 100644 src/main/java/codechicken/lib/colour/package-info.java create mode 100644 src/main/java/codechicken/lib/data/package-info.java delete mode 100644 src/main/java/codechicken/lib/datagen/LootTableProvider.java create mode 100644 src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java create mode 100644 src/main/java/codechicken/lib/datagen/package-info.java delete mode 100644 src/main/java/codechicken/lib/datagen/recipe/ConditionBuilder.java create mode 100644 src/main/java/codechicken/lib/datagen/recipe/package-info.java create mode 100644 src/main/java/codechicken/lib/fluid/package-info.java delete mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java rename src/main/java/codechicken/lib/{world => internal}/TileChunkLoadHook.java (64%) create mode 100644 src/main/java/codechicken/lib/internal/command/admin/package-info.java create mode 100644 src/main/java/codechicken/lib/internal/command/dev/package-info.java create mode 100644 src/main/java/codechicken/lib/internal/compat/package-info.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/dev/package-info.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/package-info.java create mode 100644 src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java delete mode 100644 src/main/java/codechicken/lib/internal/network/LoginPacketHandler.java create mode 100644 src/main/java/codechicken/lib/internal/network/package-info.java create mode 100644 src/main/java/codechicken/lib/inventory/container/data/package-info.java create mode 100644 src/main/java/codechicken/lib/inventory/container/modular/package-info.java create mode 100644 src/main/java/codechicken/lib/inventory/container/package-info.java create mode 100644 src/main/java/codechicken/lib/inventory/package-info.java delete mode 100644 src/main/java/codechicken/lib/item/SimpleItemTier.java create mode 100644 src/main/java/codechicken/lib/item/package-info.java create mode 100644 src/main/java/codechicken/lib/math/package-info.java delete mode 100644 src/main/java/codechicken/lib/model/ModelRegistryHelper.java create mode 100644 src/main/java/codechicken/lib/model/bakedmodels/package-info.java create mode 100644 src/main/java/codechicken/lib/model/package-info.java create mode 100644 src/main/java/codechicken/lib/model/pipeline/package-info.java create mode 100644 src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java create mode 100644 src/main/java/codechicken/lib/package-info.java create mode 100644 src/main/java/codechicken/lib/packet/PacketCustomChannel.java delete mode 100644 src/main/java/codechicken/lib/packet/PacketCustomChannelBuilder.java create mode 100644 src/main/java/codechicken/lib/packet/PacketSender.java create mode 100644 src/main/java/codechicken/lib/packet/package-info.java delete mode 100644 src/main/java/codechicken/lib/raytracer/MergedVoxelShapeHolder.java create mode 100644 src/main/java/codechicken/lib/raytracer/package-info.java create mode 100644 src/main/java/codechicken/lib/render/block/package-info.java create mode 100644 src/main/java/codechicken/lib/render/buffer/package-info.java create mode 100644 src/main/java/codechicken/lib/render/item/map/package-info.java create mode 100644 src/main/java/codechicken/lib/render/item/package-info.java create mode 100644 src/main/java/codechicken/lib/render/lighting/package-info.java create mode 100644 src/main/java/codechicken/lib/render/package-info.java create mode 100644 src/main/java/codechicken/lib/render/particle/package-info.java create mode 100644 src/main/java/codechicken/lib/render/pipeline/attribute/package-info.java create mode 100644 src/main/java/codechicken/lib/render/pipeline/package-info.java delete mode 100644 src/main/java/codechicken/lib/texture/AtlasRegistrar.java delete mode 100644 src/main/java/codechicken/lib/texture/IIconRegister.java delete mode 100644 src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java create mode 100644 src/main/java/codechicken/lib/texture/package-info.java delete mode 100644 src/main/java/codechicken/lib/util/Boolean2ObjectFunction.java delete mode 100644 src/main/java/codechicken/lib/util/CommonUtils.java delete mode 100644 src/main/java/codechicken/lib/util/LambdaUtils.java delete mode 100644 src/main/java/codechicken/lib/util/LazyValuePair.java delete mode 100644 src/main/java/codechicken/lib/util/LogUtils.java delete mode 100644 src/main/java/codechicken/lib/util/ThrowingBiConsumer.java create mode 100644 src/main/java/codechicken/lib/util/package-info.java create mode 100644 src/main/java/codechicken/lib/world/package-info.java diff --git a/build.gradle b/build.gradle index 5b1e73bb..f00ca8e1 100644 --- a/build.gradle +++ b/build.gradle @@ -5,8 +5,7 @@ plugins { id 'maven-publish' id 'signing' id 'com.github.johnrengelman.shadow' version '7.1.2' - id 'net.neoforged.gradle' version '[6.0.18,6.2)' - id 'org.spongepowered.mixin' version '0.7.+' + id 'net.neoforged.gradle.userdev' version '7.0.97' } java { @@ -18,7 +17,9 @@ java { } group = 'io.codechicken' -archivesBaseName = 'CodeChickenLib' +base { + archivesName = 'CodeChickenLib' +} sourceSets.main.resources.srcDirs += "src/main/generated" @@ -28,27 +29,20 @@ println "Starting build of ${archivesBaseName}, Version: ${mod_version}" println "Using Forge: ${forge_version}, for Minecraft: ${mc_version}" minecraft { - mappings channel: 'official', version: mc_version - accessTransformer = file("src/main/resources/META-INF/accesstransformer.cfg") - runs { - client { - workingDirectory file('run') - mods { codechickenlib { source sourceSets.main } } - } - server { - workingDirectory file('run') - mods { codechickenlib { source sourceSets.main } } - } - data { - workingDirectory file('run') - args '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated"), '--existing', file("src/main/resources") - mods { codechickenlib { source sourceSets.main } } - } - } + accessTransformers.file file("src/main/resources/META-INF/accesstransformer.cfg") } -mixin { - add(sourceSets.main, "mixins.codechickenlib.refmap.json") +runs { + client { + workingDirectory file('run') + } + server { + workingDirectory file('run') + } + data { + workingDirectory file('run') + programArguments.addAll '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated").absolutePath, '--existing', file("src/main/resources").absolutePath + } } processResources { @@ -66,7 +60,6 @@ processResources { configurations { shadow implementation.extendsFrom shadow - annotationProcessor.extendsFrom minecraft } repositories { @@ -76,39 +69,34 @@ repositories { } dependencies { - minecraft "net.neoforged:forge:${mc_version}-${forge_version}" + implementation "net.neoforged:neoforge:${forge_version}" - shadow 'net.covers1624:Quack:0.4.7.72' + shadow 'net.covers1624:Quack:0.4.10.105' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' - compileOnly(fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")) - compileOnly(fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")) - runtimeOnly(fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")) + implementation("mezz.jei:jei-${mc_version}-neoforge:${jei_version}") { + transitive false + } } test { useJUnitPlatform() } -reobf { - shadowJar {} - jar { enabled = false } // Disable jar. -} - def commonManifest = { - attributes 'Specification-Title': archivesBaseName + attributes 'Specification-Title': base.archivesName.get() attributes 'Specification-Vendor': 'covers1624' attributes 'Specification-Version': "1" - attributes 'Implementation-Title': archivesBaseName + attributes 'Implementation-Title': base.archivesName.get() attributes 'Implementation-Vendor': 'covers1624' attributes 'Implementation-Version': mod_version attributes 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") attributes 'MixinConfigs': 'mixins.codechickenlib.json' } -def publishingMetadata = project.layout.buildDirectory.file("libs/$archivesBaseName-$version-publishing.json") +def publishingMetadata = project.layout.buildDirectory.file("libs/${base.archivesName.get()}-$version-publishing.json") def publishingMetadataTask = tasks.register("publishingMetadata") { outputs.file(publishingMetadata) doFirst { @@ -117,7 +105,7 @@ def publishingMetadataTask = tasks.register("publishingMetadata") { 'displayName' : "CodeChicken Lib ${version}", 'mcVersion' : "${mc_version}", 'version' : "${mod_version}", - 'classifier' : 'universal', + 'classifier' : null, 'modLoader' : ['neoforge', 'forge'], 'curseforgeId': '242818', 'modrinthId' : '2gq0ALnz' @@ -128,9 +116,8 @@ def publishingMetadataTask = tasks.register("publishingMetadata") { jar.enabled = false shadowJar { - finalizedBy 'reobfShadowJar' finalizedBy 'signShadowJar' - archiveClassifier = 'universal' + archiveClassifier = '' manifest commonManifest configurations = [project.configurations.shadow] @@ -139,7 +126,6 @@ shadowJar { tasks.register("signShadowJar") { dependsOn("shadowJar") - dependsOn("reobfShadowJar") doFirst { def args = [:] @@ -185,7 +171,7 @@ publishing { publications { CodeChickenLib(MavenPublication) { groupId project.group - artifactId project.archivesBaseName + artifactId project.base.archivesName.get() version project.version artifact shadowJar artifact sourcesJar @@ -196,17 +182,17 @@ publishing { } pom { - name = archivesBaseName - description = archivesBaseName - url = "https://github.com/TheCBProject/${archivesBaseName}" + name = base.archivesName.get() + description = base.archivesName.get() + url = "https://github.com/TheCBProject/${base.archivesName.get()}" scm { - url = "https://github.com/TheCBProject/${archivesBaseName}" - connection = "scm:git:git@github.com:TheCBProject/${archivesBaseName}.git" + url = "https://github.com/TheCBProject/${base.archivesName.get()}" + connection = "scm:git:git@github.com:TheCBProject/${base.archivesName.get()}.git" } issueManagement { system = 'github' - url = "https://github.com/TheCBProject/${archivesBaseName}/issues" + url = "https://github.com/TheCBProject/${base.archivesName.get()}/issues" } licenses { license { diff --git a/gradle.properties b/gradle.properties index 6f3ff3aa..c135b61f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ org.gradle.daemon=false -mc_version=1.20.1 -forge_version=47.1.65 -mod_version=4.4.0 -jei_version=15.2.0.27 +mc_version=1.20.4 +forge_version=20.4.237 +mod_version=4.5.0 +jei_version=17.3.0.56 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index c1962a79e29d3e0ab67b14947c167a862655af9b..d64cd4917707c1f8861d8cb53dd15194d4248596 100644 GIT binary patch literal 43462 zcma&NWl&^owk(X(xVyW%ySuwf;qI=D6|RlDJ2cR^yEKh!@I- zp9QeisK*rlxC>+~7Dk4IxIRsKBHqdR9b3+fyL=ynHmIDe&|>O*VlvO+%z5;9Z$|DJ zb4dO}-R=MKr^6EKJiOrJdLnCJn>np?~vU-1sSFgPu;pthGwf}bG z(1db%xwr#x)r+`4AGu$j7~u2MpVs3VpLp|mx&;>`0p0vH6kF+D2CY0fVdQOZ@h;A` z{infNyvmFUiu*XG}RNMNwXrbec_*a3N=2zJ|Wh5z* z5rAX$JJR{#zP>KY**>xHTuw?|-Rg|o24V)74HcfVT;WtQHXlE+_4iPE8QE#DUm%x0 zEKr75ur~W%w#-My3Tj`hH6EuEW+8K-^5P62$7Sc5OK+22qj&Pd1;)1#4tKihi=~8C zHiQSst0cpri6%OeaR`PY>HH_;CPaRNty%WTm4{wDK8V6gCZlG@U3$~JQZ;HPvDJcT1V{ z?>H@13MJcCNe#5z+MecYNi@VT5|&UiN1D4ATT+%M+h4c$t;C#UAs3O_q=GxK0}8%8 z8J(_M9bayxN}69ex4dzM_P3oh@ZGREjVvn%%r7=xjkqxJP4kj}5tlf;QosR=%4L5y zWhgejO=vao5oX%mOHbhJ8V+SG&K5dABn6!WiKl{|oPkq(9z8l&Mm%(=qGcFzI=eLu z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qHM zt)fE#6jTSyZ^E8y0INaIf!omWjvS=@15`O%V2CKg+}z=M9##kLKRN0uJuK250bXVU zwzT&n@30^dzKnlL^us;wClg?CKWEtiEb#zhPVx{PxFQiwEPp^C53zN21EdZAz?3D& zC6fK|_!S5Mq&0z;xWGLEv}!zjfpRg_orp7|fXMx=uP!@X`yT@5(N_Hza}p5fBk&|)J7fZ`NQ9Nz@5xT? zi?iV$q+bG!2LZUpF)>Yl!u;DEHV3!i{ipcJm_8Gj@Dac%N3|SQVGqRhrJ;WOR|CtrwzPTW^&$A6!A$E)h7xohm>hA8p{PUZ~ z_&zeg@OL3PxPtzkfsNZAqXCZ8Is7yQ+plm~8;}|~DEkv&f@?q5hB*OGQYXuwVQOp0 z?QQ`6qyp|-$47wjuV74IE_x2I17$+grwMBE^25d<5!lYhnszuh|5Yk;RB+Uk*hk=m zu73=E^7ul{40{A^?Rg^fq0ZfZO@C1HupR*_d;J>lkFv6&x&}4N;t}1T@2}~AC^<3b zA}RxFPPZe5R{_6dIN9N-GT29Oa}RzA2ekKuEVZbuMOB?Xf**`N5&m}?)TjigdY(rF z?~+a=`0);TlDa1j)1G`AfW? zRl883QPq=w zbB|bHEx%_u*$t@Yl#Vc;y*?2W^|^NJ)DmioQFr~1&>MSBL_b(YIpGWdDm3bT=Mgm1 e+h0K+-~H6qzyuy}`;+tYAZFmzUSVSYum1yJqxCBQ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0c85a1f7..a80b22ce 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ 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.6-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index aeb74cbb..1aa94a42 100755 --- a/gradlew +++ b/gradlew @@ -83,7 +83,8 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -130,10 +131,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -141,7 +145,7 @@ 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 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -198,11 +202,11 @@ fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, 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. +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 93e3f59f..25da30db 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -43,11 +43,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail diff --git a/settings.gradle b/settings.gradle index 5141985a..d6eca52a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -7,7 +7,7 @@ pluginManagement { } plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' } rootProject.name = 'CodeChickenLib' diff --git a/src/main/java/codechicken/lib/CodeChickenLib.java b/src/main/java/codechicken/lib/CodeChickenLib.java index f2eaed20..da06f1ed 100644 --- a/src/main/java/codechicken/lib/CodeChickenLib.java +++ b/src/main/java/codechicken/lib/CodeChickenLib.java @@ -2,14 +2,16 @@ import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigFile; -import codechicken.lib.datagen.ConditionalIngredient; +import codechicken.lib.config.ConfigSyncManager; import codechicken.lib.internal.ClientInit; +import codechicken.lib.internal.DataGenerators; +import codechicken.lib.internal.TileChunkLoadHook; import codechicken.lib.internal.command.CCLCommands; import codechicken.lib.internal.network.CCLNetwork; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.loading.FMLConfig; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.loading.FMLConfig; +import net.neoforged.fml.loading.FMLEnvironment; import java.nio.file.Paths; @@ -29,15 +31,20 @@ public class CodeChickenLib { public static ConfigCategory config; - public CodeChickenLib() { + public CodeChickenLib(IEventBus modBus) { config = new ConfigFile(MOD_ID) .path(Paths.get("config/ccl.cfg")) .load(); + if (FMLEnvironment.dist.isClient()) { + ClientInit.init(modBus); + } - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> ClientInit::init); + ConfigSyncManager.init(modBus); CCLCommands.init(); - CCLNetwork.init(); - ConditionalIngredient.Serializer.init(); + CCLNetwork.init(modBus); + TileChunkLoadHook.init(); +// ConditionalIngredient.Serializer.init(); + DataGenerators.init(modBus); } } diff --git a/src/main/java/codechicken/lib/block/ModularBlock.java b/src/main/java/codechicken/lib/block/ModularBlock.java index 5a43f801..26e7fe99 100644 --- a/src/main/java/codechicken/lib/block/ModularBlock.java +++ b/src/main/java/codechicken/lib/block/ModularBlock.java @@ -8,7 +8,7 @@ import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.data.loading.DatagenModLoader; +import net.neoforged.neoforge.data.loading.DatagenModLoader; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java b/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java index 7928d732..6bf82a8b 100644 --- a/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java @@ -3,8 +3,8 @@ import codechicken.lib.block.ModularBlock; import net.minecraft.data.DataProvider; import net.minecraft.world.level.block.Block; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; import org.jetbrains.annotations.ApiStatus; /** @@ -14,7 +14,7 @@ * to each {@link DataProvider} *

* You can either add each block manually via {@link #addToProvider(ModularBlock, DataProvider)}. Or you - * can register your entire {@link DeferredRegister} via {@link #addAllToProvider(DeferredRegister, DataProvider)} + * can register your entire {@link DeferredRegister } via {@link #addAllToProvider(DeferredRegister, DataProvider)} *

* Created by covers1624 on 22/7/22. */ @@ -51,7 +51,7 @@ public static void addToProvider(ModularBlock block, DataProvider provider) { * @param provider The {@link DataProvider} to add things to. */ public static void addAllToProvider(DeferredRegister blocks, DataProvider provider) { - for (RegistryObject entry : blocks.getEntries()) { + for (DeferredHolder entry : blocks.getEntries()) { if (entry.get() instanceof ModularBlock block) { addToProvider(block, provider); } diff --git a/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java b/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java index 3cee2f73..60818162 100644 --- a/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java @@ -1,16 +1,22 @@ package codechicken.lib.block.component.data; import codechicken.lib.block.ModularBlock; -import codechicken.lib.datagen.LootTableProvider; +import codechicken.lib.datagen.NoValidationBLockLootSubProvider; import net.minecraft.data.DataProvider; +import net.minecraft.data.loot.BlockLootSubProvider; +import net.minecraft.data.loot.LootTableProvider; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.storage.loot.LootPool; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.entries.LootItem; +import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; +import java.util.Set; import java.util.function.Consumer; /** @@ -29,10 +35,24 @@ public LootTableComponent(Consumer configure) { } @Override - protected void addToProvider(DataProvider provider) { - if (provider instanceof LootTableProvider.BlockLootProvider loot) { + protected void addToProvider(DataProvider p) { + if (p instanceof LootTableProvider provider) { + if (!(provider.subProviders instanceof ArrayList)) { + provider.subProviders = new ArrayList<>(provider.subProviders); + } + provider.subProviders.add( + new LootTableProvider.SubProviderEntry( + () -> new NoValidationBLockLootSubProvider() { + @Override + protected void generate() { + add(getBlock(), table); + } + }, + LootContextParamSets.BLOCK + ) + ); + configure.accept(this); - loot.register(getBlock(), table); } } diff --git a/src/main/java/codechicken/lib/block/component/data/TagComponent.java b/src/main/java/codechicken/lib/block/component/data/TagComponent.java index dc98c281..ad4caca7 100644 --- a/src/main/java/codechicken/lib/block/component/data/TagComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/TagComponent.java @@ -3,7 +3,7 @@ import net.minecraft.data.DataProvider; import net.minecraft.tags.TagKey; import net.minecraft.world.level.block.Block; -import net.minecraftforge.common.data.BlockTagsProvider; +import net.neoforged.neoforge.common.data.BlockTagsProvider; import org.jetbrains.annotations.ApiStatus; /** diff --git a/src/main/java/codechicken/lib/block/component/data/package-info.java b/src/main/java/codechicken/lib/block/component/data/package-info.java index 03be7414..d64bcf22 100644 --- a/src/main/java/codechicken/lib/block/component/data/package-info.java +++ b/src/main/java/codechicken/lib/block/component/data/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block.component.data; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/block/component/package-info.java b/src/main/java/codechicken/lib/block/component/package-info.java index 6efe124d..8e81d8a4 100644 --- a/src/main/java/codechicken/lib/block/component/package-info.java +++ b/src/main/java/codechicken/lib/block/component/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block.component; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/block/component/tile/package-info.java b/src/main/java/codechicken/lib/block/component/tile/package-info.java index 41dcaf33..6f27633e 100644 --- a/src/main/java/codechicken/lib/block/component/tile/package-info.java +++ b/src/main/java/codechicken/lib/block/component/tile/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block.component.tile; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/block/package-info.java b/src/main/java/codechicken/lib/block/package-info.java index 74498270..0c8f7368 100644 --- a/src/main/java/codechicken/lib/block/package-info.java +++ b/src/main/java/codechicken/lib/block/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/capability/CapabilityCache.java b/src/main/java/codechicken/lib/capability/CapabilityCache.java index d6b5c151..2de066b5 100644 --- a/src/main/java/codechicken/lib/capability/CapabilityCache.java +++ b/src/main/java/codechicken/lib/capability/CapabilityCache.java @@ -1,30 +1,26 @@ package codechicken.lib.capability; -import codechicken.lib.math.MathHelper; -import com.google.common.collect.Iterables; -import net.covers1624.quack.collection.Object2IntPair; +import net.covers1624.quack.util.SneakyUtils; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.common.util.NonNullSupplier; +import net.minecraft.server.level.ServerLevel; +import net.neoforged.neoforge.capabilities.BlockCapability; +import net.neoforged.neoforge.capabilities.BlockCapabilityCache; +import net.neoforged.neoforge.capabilities.ICapabilityInvalidationListener; +import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; /** * A simple cache for capabilities as viewed from a specific world position. *

- * Several things need to be implemented depending on your usage, if you wish to have a time-out - * based cache, meaning if a capability for a block is 'empty', it will wait {@link #setWaitTicks} - * number of ticks to check again, if you are using this class in that mode, you must call - * {@link #tick()} each game tick otherwise nothing will ever re-cache.
- * You can also call {@link #onNeighborChanged}, doing so will force a re-cache of all empty capabilities - * from the block that notified us of a change, on the next query.
- * For Support of API's that notify you when your host was moved, you should probably call {@link #setWorldPos} - * to clear the entire cache and notify of world and/or position change. + * Provides a cleaner api to the Neo provided {@link BlockCapabilityCache}. The Neo cache requires you know, up-front, + * what capabilities you wish to receive, this is not always the case and not always easily computable. + *

+ * For Support of API's that notify you when your host was moved, you should call {@link #setLevelPos} + * to ensure the capability cache *

* It is also possible to create {@link CapabilityCache} without a world and position. Doing so, will * cause all getters to return 'empty' until one is assigned. @@ -33,181 +29,136 @@ */ public class CapabilityCache { - private final Map, Object2IntPair>> selfCache = new HashMap<>(); - private final EnumMap, Object2IntPair>>> sideCache = new EnumMap<>(Direction.class); - - private Level world; - private BlockPos pos; + private final SideCache[] cache; - private int ticks; - private int waitTicks = 5 * 20; + private @Nullable ServerLevel level; + private @Nullable BlockPos pos; + private int moveCookie; public CapabilityCache() { + cache = new SideCache[7]; + for (int i = 0; i < cache.length; i++) { + cache[i] = new SideCache(); + } } - public CapabilityCache(Level world, BlockPos pos) { - this.world = world; - this.pos = pos; - } - - /** - * Sets the number of ticks to wait between re-caching an 'empty' capability.
- * The default is to wait 5 seconds. - * - * @param ticks The number of game ticks to wait. - */ - public void setWaitTicks(int ticks) { - this.waitTicks = ticks; - } - - /** - * Call this to notify of a new game tick. - */ - public void tick() { - ticks++; + public CapabilityCache(ServerLevel level, BlockPos pos) { + this(); + setLevelPos(level, pos); } /** * Call this when {@link CapabilityCache}'s host has been moved.
* Clears all internal state and sets a new world / pos. * - * @param world The new world. + * @param level The new world. * @param pos The new pos. */ - public void setWorldPos(Level world, BlockPos pos) { + public void setLevelPos(ServerLevel level, BlockPos pos) { clear(); - this.world = world; + this.level = level; this.pos = pos; + this.moveCookie++; } /** * Clears all internal state. Everything will be re-cached. */ public void clear() { - selfCache.clear(); - Arrays.stream(Direction.BY_3D_DATA).map(this::getCacheForSide).forEach(Map::clear); - } - - /** - * Notifies {@link CapabilityCache} of a {@link Block#onNeighborChange} event.
- * Marks all empty capabilities provided by from block, to be re-cached - * next query. - * - * @param from The from position. - */ - public void onNeighborChanged(BlockPos from) { - if (world == null || pos == null) { - return; - } - BlockPos offset = from.subtract(pos); - int diff = MathHelper.absSum(offset); - int side = MathHelper.toSide(offset); - if (side < 0 || diff != 1) { - return; + for (SideCache sideCache : cache) { + sideCache.cache.clear(); + sideCache.listener = null; } - Direction sideChanged = Direction.BY_3D_DATA[side]; - - Iterables.concat(selfCache.entrySet(), getCacheForSide(sideChanged).entrySet()).forEach(entry -> { - Object2IntPair> pair = entry.getValue(); - if (pair.getKey() != null && !pair.getKey().isPresent()) { - pair.setKey(null); - pair.setValue(ticks); - } - }); } /** - * Overload of {@link #getCapability} with support for evaluating a {@link NonNullSupplier} - * when empty. + * Overload of {@link #getCapability} with support for returning another object when empty. * * @param capability The capability to get. * @param to The direction to ask. - * @param default_ The supplier to evaluate when empty. - * @return The instance, either the capability at to or what default_ supplies. + * @param default_ The object to return when empty. + * @return The instance, either the capability at to or default_ */ - public T getCapabilityOr(Capability capability, Direction to, NonNullSupplier default_) { - return getCapability(capability, to).orElseGet(default_); + public T getCapabilityOr(BlockCapability capability, Direction to, T default_) { + T ret = getCapability(capability, to); + if (ret == null) return default_; + + return ret; } /** - * Overload of {@link #getCapability} with support for returning another object when empty. + * Gets a capability from the block in to direction from {@link CapabilityCache}'s + * position. For example, calling this with NORTH, will get a capability from the block + * IN NORTH direction on ITS SOUTH face. * * @param capability The capability to get. * @param to The direction to ask. - * @param default_ The object to return when empty. - * @return The instance, either the capability at to or default_ + * @return The capability instance or {@code null}. */ - public T getCapabilityOr(Capability capability, Direction to, T default_) { - return getCapability(capability, to).orElse(default_); + public @Nullable T getCapability(BlockCapability capability, Direction to) { + return getCapability(capability, to, to.getOpposite()); } /** * Gets a capability from the block in to direction from {@link CapabilityCache}'s - * position. For example, calling this with NORTH, will get a capability from the block - * IN NORTH direction on ITS SOUTH face. + * position. * * @param capability The capability to get. * @param to The direction to ask. - * @return A {@link LazyOptional} of the capability, may be empty. + * @param ctx The context, usually the face. + * @return The capability instance or {@code null}. */ - public LazyOptional getCapability(Capability capability, Direction to) { + public @Nullable T getCapability(BlockCapability capability, Direction to, C ctx) { Objects.requireNonNull(capability, "Null capability."); - if (world == null || pos == null) { - return LazyOptional.empty().cast(); - } - Map, Object2IntPair>> sideCache = getCacheForSide(to); - Object2IntPair> cache = sideCache.get(capability); - if (cache == null) { - cache = new Object2IntPair<>(null, ticks); - sideCache.put(capability, cache); - return tryReCache(capability, to, cache).cast(); - } - LazyOptional lookup = cache.getKey(); - if (lookup == null || !lookup.isPresent()) { - return tryReCache(capability, to, cache).cast(); + if (level == null || pos == null) return null; + + SideCache sideCache = cache[idxForDir(to)]; + CacheKey key = new CacheKey(capability, ctx); + CacheValue val = SneakyUtils.unsafeCast(sideCache.cache.get(key)); + if (val != null) return val.obj; + + BlockPos there = pos.relative(to); + T obj; + if (level.isLoaded(there)) { + obj = level.getCapability(capability, there, ctx); + sideCache.addListener(there); + } else { + obj = null; } - return lookup.cast(); + sideCache.cache.put(key, new CacheValue<>(obj)); + return obj; } - //TODO this logic should be unified and merged with above, There is a potential case where we could leak the Object2IntPair - //TODO instance if a mod does weird things with their invalidations of LazyOptionals - private LazyOptional tryReCache(Capability capability, Direction to, Object2IntPair> cache) { - boolean isFirst = cache.getKey() == null; - if (isFirst || !cache.getKey().isPresent()) { - if (isFirst || cache.getValue() + waitTicks <= ticks) { - LazyOptional lookup = requestCapability(capability, to); - if (lookup.isPresent()) { - cache.setKey(lookup); - cache.setValue(ticks); - lookup.addListener(l -> {//TODO, probably not needed? we check every lookup anyway.. - //When the LazyOptional notifies us that its gone, - //set the cache to empty, and mark ticks. - cache.setKey(LazyOptional.empty()); - cache.setValue(ticks); - }); - } else { - cache.setKey(LazyOptional.empty()); - cache.setValue(ticks); - } - } - } - return cache.getKey(); + private static int idxForDir(@Nullable Direction dir) { + return dir == null ? 6 : dir.ordinal(); } - private LazyOptional requestCapability(Capability capability, Direction to) { - BlockEntity tile = world.getBlockEntity(pos.relative(to)); - Direction inverse = to == null ? null : to.getOpposite(); - if (tile != null) { - return tile.getCapability(capability, inverse); - } - return LazyOptional.empty(); - } + private final class SideCache { + + private final Map> cache = new HashMap<>(); + private @Nullable ICapabilityInvalidationListener listener; + + public void addListener(BlockPos pos) { + if (listener != null) return; + if (level == null) throw new RuntimeException("Level is null?? What?"); - private Map, Object2IntPair>> getCacheForSide(Direction side) { - if (side == null) { - return selfCache; + listener = new ICapabilityInvalidationListener() { + private final int cookie = moveCookie; + + @Override + public boolean onInvalidate() { + if (cookie != moveCookie) return false; + + cache.clear(); + return true; + } + }; + level.registerCapabilityListener(pos, listener); } - return sideCache.computeIfAbsent(side, s -> new HashMap<>()); } + private record CacheKey(BlockCapability capability, @Nullable Object context) { } + + private record CacheValue(@Nullable T obj) { } + } diff --git a/src/main/java/codechicken/lib/capability/SimpleCapProvider.java b/src/main/java/codechicken/lib/capability/SimpleCapProvider.java deleted file mode 100644 index 6272878c..00000000 --- a/src/main/java/codechicken/lib/capability/SimpleCapProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.capability; - -import net.minecraft.core.Direction; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.common.util.LazyOptional; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -/** - * Created by covers1624 on 17/5/20. - */ -public class SimpleCapProvider implements ICapabilityProvider { - - protected final Capability capability; - protected final T instance; - protected final LazyOptional instanceOpt; - - public SimpleCapProvider(Capability capability, T instance) { - this.capability = capability; - this.instance = instance; - instanceOpt = LazyOptional.of(() -> this.instance); - } - - @Nonnull - @Override - public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { - if (capability == cap) { - return instanceOpt.cast(); - } - return LazyOptional.empty(); - } -} diff --git a/src/main/java/codechicken/lib/capability/package-info.java b/src/main/java/codechicken/lib/capability/package-info.java new file mode 100644 index 00000000..926eb037 --- /dev/null +++ b/src/main/java/codechicken/lib/capability/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.capability; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/colour/Colour.java b/src/main/java/codechicken/lib/colour/Colour.java index ca083a8a..07f1c9e9 100644 --- a/src/main/java/codechicken/lib/colour/Colour.java +++ b/src/main/java/codechicken/lib/colour/Colour.java @@ -2,6 +2,7 @@ import codechicken.lib.math.MathHelper; import codechicken.lib.util.Copyable; +import org.jetbrains.annotations.Nullable; import static java.lang.Math.max; @@ -268,8 +269,12 @@ public static int packARGB(float[] data) { return packARGB(data[0], data[1], data[2], data[3]); } - public boolean equals(Colour colour) { - return colour != null && rgba() == colour.rgba(); + public boolean equals(@Nullable Colour other) { + if (other == null) return false; + if (r != other.r) return false; + if (g != other.g) return false; + if (b != other.b) return false; + return a == other.a; } @Override @@ -277,10 +282,7 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Colour colour)) return false; - if (r != colour.r) return false; - if (g != colour.g) return false; - if (b != colour.b) return false; - return a == colour.a; + return equals(colour); } @Override diff --git a/src/main/java/codechicken/lib/colour/CustomGradient.java b/src/main/java/codechicken/lib/colour/CustomGradient.java index 222b1e33..85bc6af7 100644 --- a/src/main/java/codechicken/lib/colour/CustomGradient.java +++ b/src/main/java/codechicken/lib/colour/CustomGradient.java @@ -13,7 +13,7 @@ public class CustomGradient { public CustomGradient(ResourceLocation textureFile) { BufferedImage img = TextureUtils.loadBufferedImage(textureFile); if (img == null) { - throw new RuntimeException("File not found: " + textureFile.toString()); + throw new RuntimeException("File not found: " + textureFile); } int[] data = new int[img.getWidth()]; diff --git a/src/main/java/codechicken/lib/colour/EnumColour.java b/src/main/java/codechicken/lib/colour/EnumColour.java index c653d2d1..5467d349 100644 --- a/src/main/java/codechicken/lib/colour/EnumColour.java +++ b/src/main/java/codechicken/lib/colour/EnumColour.java @@ -3,18 +3,17 @@ import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; +import net.covers1624.quack.collection.FastStream; import net.minecraft.client.resources.language.I18n; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.registries.ForgeRegistries; +import org.jetbrains.annotations.Nullable; -import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.function.Function; -import java.util.stream.Collectors; /** * Created by covers1624 on 16/09/2016. @@ -48,14 +47,14 @@ public enum EnumColour implements StringRepresentable { private static final ImmutableTable mixMap; - private static final Map nameLookup = Arrays.stream(values())// - .collect(Collectors.toMap(e -> e.name, Function.identity())); + private static final Map nameLookup = FastStream.of(values()) + .toMap(e -> e.name, Function.identity()); - private static final Map dyeTagLookup = Arrays.stream(values())// - .collect(Collectors.toMap(e -> e.dyeTagName, Function.identity())); + private static final Map dyeTagLookup = FastStream.of(values()) + .toMap(e -> e.dyeTagName, Function.identity()); - private static final Map woolTagLookup = Arrays.stream(values())// - .collect(Collectors.toMap(e -> e.woolTagName, Function.identity())); + private static final Map woolTagLookup = FastStream.of(values()) + .toMap(e -> e.woolTagName, Function.identity()); static { Table tmp = HashBasedTable.create(); @@ -163,11 +162,11 @@ public ColourRGBA getColour(int alpha) { return new ColourRGBA(rgba(alpha)); } - public EnumColour mix(EnumColour b) { + public @Nullable EnumColour mix(EnumColour b) { return mix(this, b); } - public static EnumColour mix(EnumColour a, EnumColour b) { + public static @Nullable EnumColour mix(EnumColour a, EnumColour b) { if (a == b) { return a; } @@ -182,37 +181,31 @@ public static EnumColour fromDyeMeta(int id) { return values()[15 - id]; } - public static EnumColour fromDyeTag(ResourceLocation tag) { + public static @Nullable EnumColour fromDyeTag(ResourceLocation tag) { return dyeTagLookup.get(tag); } - public static EnumColour fromWoolTag(ResourceLocation tag) { + public static @Nullable EnumColour fromWoolTag(ResourceLocation tag) { return woolTagLookup.get(tag); } - public static EnumColour fromDyeStack(ItemStack stack) { - return ForgeRegistries.ITEMS.getHolder(stack.getItem()) - .flatMap(e -> e.getTagKeys() - .map(TagKey::location) - .map(dyeTagLookup::get) - .filter(Objects::nonNull) - .findFirst() - ) - .orElse(null); + public static @Nullable EnumColour fromDyeStack(ItemStack stack) { + return FastStream.of(stack.getTags()) + .map(TagKey::location) + .map(dyeTagLookup::get) + .filter(Objects::nonNull) + .firstOrDefault(); } - public static EnumColour fromWoolStack(ItemStack stack) { - return ForgeRegistries.ITEMS.getHolder(stack.getItem()) - .flatMap(e -> e.getTagKeys() - .map(TagKey::location) - .map(woolTagLookup::get) - .filter(Objects::nonNull) - .findFirst() - ) - .orElse(null); + public static @Nullable EnumColour fromWoolStack(ItemStack stack) { + return FastStream.of(stack.getTags()) + .map(TagKey::location) + .map(woolTagLookup::get) + .filter(Objects::nonNull) + .firstOrDefault(); } - public static EnumColour fromName(String name) { + public static @Nullable EnumColour fromName(String name) { return nameLookup.get(name); } } diff --git a/src/main/java/codechicken/lib/colour/package-info.java b/src/main/java/codechicken/lib/colour/package-info.java new file mode 100644 index 00000000..e2b8353a --- /dev/null +++ b/src/main/java/codechicken/lib/colour/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.colour; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java b/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java index 6185c64a..5d027359 100644 --- a/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java @@ -2,7 +2,7 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; -import net.covers1624.quack.collection.StreamableIterable; +import net.covers1624.quack.collection.ColUtils; import org.jetbrains.annotations.Nullable; import java.util.*; @@ -157,7 +157,7 @@ public void runSync(ConfigCallback.Reason reason) { @Override public boolean isDirty() { - return super.isDirty() || StreamableIterable.of(getChildren()).anyMatch(ConfigTag::isDirty); + return super.isDirty() || ColUtils.anyMatch(getChildren(), ConfigTag::isDirty); } @Override diff --git a/src/main/java/codechicken/lib/config/ConfigSyncManager.java b/src/main/java/codechicken/lib/config/ConfigSyncManager.java index b9cc961c..80233aec 100644 --- a/src/main/java/codechicken/lib/config/ConfigSyncManager.java +++ b/src/main/java/codechicken/lib/config/ConfigSyncManager.java @@ -2,15 +2,28 @@ import codechicken.lib.packet.PacketCustom; import com.google.common.base.Joiner; +import net.covers1624.quack.util.CrashLock; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.configuration.ServerConfigurationPacketListener; import net.minecraft.resources.ResourceLocation; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.network.configuration.ICustomConfigurationTask; +import net.neoforged.neoforge.network.event.OnGameConfigurationEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.Consumer; import java.util.function.Supplier; +import static codechicken.lib.CodeChickenLib.MOD_ID; import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; import static codechicken.lib.internal.network.CCLNetwork.NET_CHANNEL; @@ -20,6 +33,7 @@ public class ConfigSyncManager { private static final Logger LOGGER = LogManager.getLogger(); + private static final CrashLock LOCK = new CrashLock("Already Initialized."); private static final Map SYNC_MAP = new HashMap<>(); @@ -38,23 +52,18 @@ public static void registerSync(ResourceLocation key, ConfigTag tag) { } } - public static void handleLogin(BiConsumer> consumer) { - if (SYNC_MAP.isEmpty()) return; + @ApiStatus.Internal + public static void init(IEventBus modBus) { + LOCK.lock(); - consumer.accept("config_sync", () -> { - PacketCustom packet = new PacketCustom(NET_CHANNEL, L_CONFIG_SYNC); - packet.writeVarInt(SYNC_MAP.size()); - for (Map.Entry entry : SYNC_MAP.entrySet()) { - packet.writeResourceLocation(entry.getKey()); - entry.getValue().write(packet); - } + if (FMLEnvironment.dist.isClient()) { + NeoForge.EVENT_BUS.addListener(ConfigSyncManager::onClientDisconnected); + } - String mods = Joiner.on(", ").join(SYNC_MAP.keySet()); - LOGGER.info("Sending config sync packet for {} to connecting player.", mods); - return packet; - }); + modBus.addListener(ConfigSyncManager::onGameConfigurationEvent); } + @ApiStatus.Internal public static void readSyncPacket(PacketCustom packet) { int numPackets = packet.readVarInt(); for (int i = 0; i < numPackets; i++) { @@ -70,7 +79,7 @@ public static void readSyncPacket(PacketCustom packet) { } } - public static void onClientDisconnected() { + private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut event) { for (Map.Entry entry : SYNC_MAP.entrySet()) { LOGGER.info("Client disconnected, rolling back config for {}.", entry.getKey()); ConfigTag config = entry.getValue(); @@ -78,4 +87,35 @@ public static void onClientDisconnected() { config.runSync(ConfigCallback.Reason.ROLLBACK); } } + + private static void onGameConfigurationEvent(OnGameConfigurationEvent event) { + event.register(new ConfigSyncConfigurationTask(event.getListener())); + } + + private record ConfigSyncConfigurationTask(ServerConfigurationPacketListener listener) implements ICustomConfigurationTask { + + private static final Type TYPE = new Type(new ResourceLocation(MOD_ID, "config_sync")); + + @Override + public void run(Consumer sender) { + if (!SYNC_MAP.isEmpty()) { + PacketCustom packet = new PacketCustom(NET_CHANNEL, L_CONFIG_SYNC); + packet.writeVarInt(SYNC_MAP.size()); + for (Map.Entry entry : SYNC_MAP.entrySet()) { + packet.writeResourceLocation(entry.getKey()); + entry.getValue().write(packet); + } + + String mods = Joiner.on(", ").join(SYNC_MAP.keySet()); + LOGGER.info("Sending config sync packet for {} to connecting player.", mods); + sender.accept(packet.toCustomPayload()); + } + listener.finishCurrentTask(TYPE); + } + + @Override + public Type type() { + return TYPE; + } + } } diff --git a/src/main/java/codechicken/lib/config/ConfigValueListImpl.java b/src/main/java/codechicken/lib/config/ConfigValueListImpl.java index e2505ed1..66005a77 100644 --- a/src/main/java/codechicken/lib/config/ConfigValueListImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigValueListImpl.java @@ -15,7 +15,7 @@ import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongList; import it.unimi.dsi.fastutil.longs.LongLists; -import net.covers1624.quack.collection.StreamableIterable; +import net.covers1624.quack.collection.FastStream; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -503,7 +503,7 @@ private static BooleanList convertToBooleans(List list) { private static List convertToStrings(List list) { if (list instanceof StringList sList) return sList; - return new StringList(StreamableIterable.of(list).map(Object::toString).toList()); + return new StringList(FastStream.of(list).map(Object::toString).toList()); } private static IntList convertToInts(List list) { diff --git a/src/main/java/codechicken/lib/config/package-info.java b/src/main/java/codechicken/lib/config/package-info.java index 3defeddf..32627ba9 100644 --- a/src/main/java/codechicken/lib/config/package-info.java +++ b/src/main/java/codechicken/lib/config/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.config; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/config/parser/package-info.java b/src/main/java/codechicken/lib/config/parser/package-info.java index ddb4e618..8ecda292 100644 --- a/src/main/java/codechicken/lib/config/parser/package-info.java +++ b/src/main/java/codechicken/lib/config/parser/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.config.parser; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/data/MCDataByteBuf.java b/src/main/java/codechicken/lib/data/MCDataByteBuf.java index eb8169ae..6d690d9d 100644 --- a/src/main/java/codechicken/lib/data/MCDataByteBuf.java +++ b/src/main/java/codechicken/lib/data/MCDataByteBuf.java @@ -30,7 +30,7 @@ public MCDataByteBuf(ByteBuf buf) { * * @return The {@link FriendlyByteBuf}. */ - public FriendlyByteBuf toPacketBuffer() { + public FriendlyByteBuf toFriendlyByteBuf() { return buf instanceof FriendlyByteBuf ? (FriendlyByteBuf) buf : new FriendlyByteBuf(buf); } diff --git a/src/main/java/codechicken/lib/data/MCDataInput.java b/src/main/java/codechicken/lib/data/MCDataInput.java index 299dac94..b0d0c3d9 100644 --- a/src/main/java/codechicken/lib/data/MCDataInput.java +++ b/src/main/java/codechicken/lib/data/MCDataInput.java @@ -7,7 +7,9 @@ import io.netty.handler.codec.EncoderException; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; import net.minecraft.core.Vec3i; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; @@ -19,14 +21,10 @@ import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.IForgeRegistry; -import net.minecraftforge.registries.RegistryManager; +import net.neoforged.neoforge.fluids.FluidStack; +import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; -import javax.annotation.Nullable; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; @@ -35,6 +33,7 @@ import java.nio.charset.StandardCharsets; import java.util.UUID; +import static java.util.Objects.requireNonNull; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; /** @@ -586,19 +585,25 @@ default Vector3f readVec3f() { * * @return The {@link CompoundTag}. */ - @Nullable default CompoundTag readCompoundNBT() { - if (!readBoolean()) { - return null; - } else { - try { - return NbtIo.read(toDataInput(), new NbtAccounter(2097152L)); - } catch (IOException e) { - throw new EncoderException("Failed to read CompoundNBT from stream.", e); - } + try { + return NbtIo.read(toDataInput(), NbtAccounter.create(2097152L)); + } catch (IOException e) { + throw new EncoderException("Failed to read CompoundNBT from stream.", e); } } + /** + * Reads a {@link CompoundTag} from the stream. + * + * @return The {@link CompoundTag} or {@code null}. + */ + default @Nullable CompoundTag readNullableCompoundNBT() { + if (!readBoolean()) return null; + + return readCompoundNBT(); + } + /** * Reads an {@link ItemStack} from the stream. * It should also be noted that this implementation reads the {@link ItemStack#getCount()} @@ -607,15 +612,14 @@ default CompoundTag readCompoundNBT() { * @return The {@link ItemStack}. */ default ItemStack readItemStack() { - if (!readBoolean()) { - return ItemStack.EMPTY; - } else { - Item item = readRegistryIdDirect(ForgeRegistries.ITEMS); - int count = readVarInt(); - ItemStack stack = new ItemStack(item, count); - stack.readShareTag(readCompoundNBT()); - return stack; - } + if (!readBoolean()) return ItemStack.EMPTY; + + Item item = readRegistryIdDirect(BuiltInRegistries.ITEM); + int count = readVarInt(); + CompoundTag attachments = readNullableCompoundNBT(); + ItemStack stack = new ItemStack(item, count, attachments); + stack.setTag(readNullableCompoundNBT()); + return stack; } /** @@ -624,17 +628,15 @@ default ItemStack readItemStack() { * @return The {@link FluidStack}. */ default FluidStack readFluidStack() { - if (!readBoolean()) { + if (!readBoolean()) return FluidStack.EMPTY; + + Fluid fluid = readRegistryIdDirect(BuiltInRegistries.FLUID); + int amount = readVarInt(); + CompoundTag tag = readNullableCompoundNBT(); + if (fluid == Fluids.EMPTY) { return FluidStack.EMPTY; - } else { - Fluid fluid = readRegistryIdDirect(ForgeRegistries.FLUIDS); - int amount = readVarInt(); - CompoundTag tag = readCompoundNBT(); - if (fluid == Fluids.EMPTY) { - return FluidStack.EMPTY; - } - return new FluidStack(fluid, amount, tag); } + return new FluidStack(fluid, amount, tag); } /** @@ -643,33 +645,31 @@ default FluidStack readFluidStack() { * @return The {@link Component}. */ default MutableComponent readTextComponent() { - return Component.Serializer.fromJson(readString()); + return requireNonNull(Component.Serializer.fromJson(readString())); } /** * Reads a registry object from the stream. * - * @param registry The {@link IForgeRegistry} to load the entry from. + * @param registry The {@link Registry} to load the entry from. * @return The registry object.. - * @see MCDataOutput#writeRegistryIdDirect(IForgeRegistry, Object) - * @see MCDataOutput#writeRegistryIdDirect(IForgeRegistry, ResourceLocation) + * @see MCDataOutput#writeRegistryIdDirect(Registry, Object) + * @see MCDataOutput#writeRegistryIdDirect(Registry, ResourceLocation) */ - default T readRegistryIdDirect(IForgeRegistry registry) { - ForgeRegistry _registry = unsafeCast(registry); - return _registry.getValue(readVarInt()); + default T readRegistryIdDirect(Registry registry) { + return requireNonNull(registry.byId(readVarInt()), "Registry entry did not exist."); } /** * Reads a registry object from the stream. * * @return The registry object. - * @see MCDataOutput#writeRegistryId(IForgeRegistry, Object) - * @see MCDataOutput#writeRegistryId(IForgeRegistry, ResourceLocation) + * @see MCDataOutput#writeRegistryId(Registry, Object) + * @see MCDataOutput#writeRegistryId(Registry, ResourceLocation) */ default T readRegistryId() { ResourceLocation rName = readResourceLocation(); - ForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(rName); - return readRegistryIdDirect(registry); + return readRegistryIdDirect(unsafeCast(requireNonNull(BuiltInRegistries.REGISTRY.get(rName), "Registry " + rName + " not found."))); } //endregion diff --git a/src/main/java/codechicken/lib/data/MCDataOutput.java b/src/main/java/codechicken/lib/data/MCDataOutput.java index 89bcb3b6..96f1b64c 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutput.java +++ b/src/main/java/codechicken/lib/data/MCDataOutput.java @@ -6,7 +6,9 @@ import io.netty.handler.codec.EncoderException; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; import net.minecraft.core.Vec3i; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; import net.minecraft.network.chat.Component; @@ -14,10 +16,8 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.IForgeRegistry; +import net.neoforged.neoforge.fluids.FluidStack; +import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; import java.io.DataOutput; @@ -30,8 +30,6 @@ import java.util.UUID; import static codechicken.lib.data.DataUtils.checkLen; -import static java.text.MessageFormat.format; -import static net.covers1624.quack.util.SneakyUtils.unsafeCast; /** * Provides the ability to write various datas to some sort of data stream. @@ -837,59 +835,53 @@ default MCDataOutput writeVec3d(Vec3 vec) { * @return The same stream. */ default MCDataOutput writeCompoundNBT(CompoundTag tag) { - if (tag == null) { - writeBoolean(false); - } else { - try { - writeBoolean(true); - NbtIo.write(tag, toDataOutput()); - } catch (IOException e) { - throw new EncoderException("Failed to write CompoundNBT to stream.", e); - } + try { + NbtIo.write(tag, toDataOutput()); + } catch (IOException e) { + throw new EncoderException("Failed to write CompoundNBT to stream.", e); } return this; } /** - * Writes an {@link ItemStack} to the stream. - * Overload for {@link #writeItemStack(ItemStack, boolean)} passing true. + * Writes a Nullable {@link CompoundTag} to the stream. * - * @param stack The {@link ItemStack}. + * @param tag The {@link CompoundTag} or {@code null}. * @return The same stream. */ - default MCDataOutput writeItemStack(ItemStack stack) { - return writeItemStack(stack, true); + default MCDataOutput writeNullableCompoundNBT(@Nullable CompoundTag tag) { + if (tag == null) { + writeBoolean(false); + } else { + writeBoolean(true); + writeCompoundNBT(tag); + } + return this; } /** * Writes an {@link ItemStack} to the stream. - * The limitedTag parameter, can be used to force the use of - * the stack {@link ItemStack#getShareTag()} instead of its {@link ItemStack#getTag()}. - * Under normal circumstances in Server -> Client sync, not all NBT tags are required, - * to be sent to the client. For Example, the inventory of a pouch / bag(Containers sync it). - * However, in Client -> Server sync, the entire tag may be required, modders can choose, - * if they want a stacks full tag or not. The default is to use {@link ItemStack#getShareTag()}. *

* It should also be noted that this implementation writes the {@link ItemStack#getCount()} * as a varInt opposed to a byte, as that is favourable in some cases. * - * @param stack The {@link ItemStack}. - * @param limitedTag Weather to use the stacks {@link ItemStack#getShareTag()} instead. + * @param stack The {@link ItemStack}. * @return The same stream. */ - default MCDataOutput writeItemStack(ItemStack stack, boolean limitedTag) { + default MCDataOutput writeItemStack(ItemStack stack) { if (stack.isEmpty()) { writeBoolean(false); } else { writeBoolean(true); Item item = stack.getItem(); - writeRegistryIdDirect(ForgeRegistries.ITEMS, item); + writeRegistryIdDirect(BuiltInRegistries.ITEM, item); writeVarInt(stack.getCount()); + writeNullableCompoundNBT(stack.serializeAttachments()); CompoundTag nbt = null; if (item.canBeDepleted() || item.shouldOverrideMultiplayerNbt()) { - nbt = limitedTag ? stack.getShareTag() : stack.getTag(); + nbt = stack.getTag(); } - writeCompoundNBT(nbt); + writeNullableCompoundNBT(nbt); } return this; } @@ -905,9 +897,9 @@ default MCDataOutput writeFluidStack(FluidStack stack) { writeBoolean(false); } else { writeBoolean(true); - writeRegistryIdDirect(ForgeRegistries.FLUIDS, stack.getFluid()); + writeRegistryIdDirect(BuiltInRegistries.FLUID, stack.getFluid()); writeVarInt(stack.getAmount()); - writeCompoundNBT(stack.getTag()); + writeNullableCompoundNBT(stack.getTag()); } return this; } @@ -931,9 +923,8 @@ default MCDataOutput writeTextComponent(Component component) { * @param entry The object to write to the stream. * @return The same stream. */ - default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, T entry) { - ForgeRegistry r = unsafeCast(Objects.requireNonNull(registry)); - writeVarInt(r.getID(entry)); + default MCDataOutput writeRegistryIdDirect(Registry registry, T entry) { + writeVarInt(registry.getId(entry)); return this; } @@ -946,9 +937,8 @@ default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, T ent * @param entry The name of the registry object to write. * @return The same stream. */ - default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, ResourceLocation entry) { - ForgeRegistry r = unsafeCast(Objects.requireNonNull(registry)); - writeVarInt(r.getID(entry)); + default MCDataOutput writeRegistryIdDirect(Registry registry, ResourceLocation entry) { + writeVarInt(registry.getId(entry)); return this; } @@ -960,14 +950,14 @@ default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, Resou * @param entry The object to write to the stream. * @return The same stream. */ - default MCDataOutput writeRegistryId(IForgeRegistry registry, T entry) { - ResourceLocation rName = registry.getRegistryName(); + default MCDataOutput writeRegistryId(Registry registry, T entry) { + ResourceLocation rName = registry.key().location(); if (!registry.containsValue(entry)) { - throw new IllegalArgumentException(format("Registry '{0}' does not contain entry '{1}'", rName, entry)); + throw new IllegalArgumentException(String.format("Registry '%s' does not contain entry '%s'", rName, entry)); } writeResourceLocation(rName); writeRegistryIdDirect(registry, entry); - return null; + return this; } /** @@ -978,14 +968,14 @@ default MCDataOutput writeRegistryId(IForgeRegistry registry, T entry) { * @param entry The name of the registry object to write. * @return The same stream. */ - default MCDataOutput writeRegistryId(IForgeRegistry registry, ResourceLocation entry) { - ResourceLocation rName = registry.getRegistryName(); + default MCDataOutput writeRegistryId(Registry registry, ResourceLocation entry) { + ResourceLocation rName = registry.key().location(); if (!registry.containsKey(entry)) { - throw new IllegalArgumentException(format("Registry '{0}' does not contain entry '{1}'", rName, entry)); + throw new IllegalArgumentException(String.format("Registry '%s' does not contain entry '%s'", rName, entry)); } writeResourceLocation(rName); writeRegistryIdDirect(registry, entry); - return null; + return this; } //endregion diff --git a/src/main/java/codechicken/lib/data/package-info.java b/src/main/java/codechicken/lib/data/package-info.java new file mode 100644 index 00000000..ab241486 --- /dev/null +++ b/src/main/java/codechicken/lib/data/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.data; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java b/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java index b83d7588..2f419b2f 100644 --- a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java +++ b/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java @@ -1,137 +1,137 @@ -package codechicken.lib.datagen; - -import codechicken.lib.datagen.recipe.ConditionBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import net.covers1624.quack.util.CrashLock; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.crafting.AbstractIngredient; -import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.common.crafting.IIngredientSerializer; -import net.minecraftforge.common.crafting.conditions.ICondition; -import net.minecraftforge.event.AddReloadListenerEvent; -import org.jetbrains.annotations.Nullable; - -import java.util.LinkedList; -import java.util.List; -import java.util.function.Function; - -import static codechicken.lib.CodeChickenLib.MOD_ID; - -/** - * Created by covers1624 on 24/9/22. - */ -public class ConditionalIngredient extends AbstractIngredient { - - private static final ResourceLocation TYPE = new ResourceLocation(MOD_ID, "conditional"); - - private final List conditions; - private final Ingredient pass; - @Nullable - private final Ingredient fail; - - private ConditionalIngredient(List conditions, Ingredient pass, @Nullable Ingredient fail) { - this.conditions = conditions; - this.pass = pass; - this.fail = fail; - } - - public static ConditionalIngredient.Builder builder() { - return new ConditionalIngredient.Builder(); - } - - @Override - public JsonElement toJson() { - JsonObject obj = new JsonObject(); - obj.addProperty("type", TYPE.toString()); - JsonArray conditions = new JsonArray(); - for (ICondition condition : this.conditions) { - conditions.add(CraftingHelper.serialize(condition)); - } - obj.add("conditions", conditions); - obj.add("pass", pass.toJson()); - if (fail != null) { - obj.add("fail", fail.toJson()); - } - return obj; - } - - // @formatter:off - @Override public ItemStack[] getItems() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } - @Override public boolean isSimple() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } - @Override public IIngredientSerializer getSerializer() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } - // @formatter:on - - public static class Builder { - - private List conditions = new LinkedList<>(); - private Ingredient pass = null; - private Ingredient fail = null; - - private Builder() { - } - - public Builder withCondition(Function func) { - conditions.add(func.apply(ConditionBuilder.INSTANCE)); - return this; - } - - public Builder withPass(Ingredient ing) { - if (pass != null) throw new IllegalStateException("Pass Ingredient already specified."); - this.pass = ing; - return this; - } - - public Builder withFail(Ingredient ing) { - if (fail != null) throw new IllegalStateException("Pass Ingredient already specified."); - this.fail = ing; - return this; - } - - public ConditionalIngredient build() { - if (conditions.isEmpty()) throw new IllegalStateException("No conditions specified."); - if (pass == null) throw new IllegalStateException("Pass Ingredient is required."); - - return new ConditionalIngredient(conditions, pass, fail); - } - } - - public static class Serializer implements IIngredientSerializer { - - private static final CrashLock LOCK = new CrashLock("Already Initialized"); - private static ICondition.IContext conditionContext = ICondition.IContext.EMPTY; - - public static void init() { - LOCK.lock(); - MinecraftForge.EVENT_BUS.addListener(Serializer::onAddReloadListenerEvent); - CraftingHelper.register(TYPE, new Serializer()); - } - - private static void onAddReloadListenerEvent(AddReloadListenerEvent event) { - conditionContext = event.getConditionContext(); - } - - @Override - public Ingredient parse(JsonObject json) { - if (!CraftingHelper.processConditions(json, "conditions", conditionContext)) { - if (json.has("fail")) { - return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "fail"), true); - } - return Ingredient.EMPTY; - } - return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "pass"), false); - } - - // We don't operate like this, we always return a different ingredient. - // @formatter:off - @Override public Ingredient parse(FriendlyByteBuf buffer) { throw new UnsupportedOperationException(); } - @Override public void write(FriendlyByteBuf buffer, Ingredient ingredient) { throw new UnsupportedOperationException(); } - // @formatter:on - } -} +//package codechicken.lib.datagen; +// +//import codechicken.lib.datagen.recipe.ConditionBuilder; +//import com.google.gson.JsonArray; +//import com.google.gson.JsonElement; +//import com.google.gson.JsonObject; +//import net.covers1624.quack.util.CrashLock; +//import net.minecraft.network.FriendlyByteBuf; +//import net.minecraft.resources.ResourceLocation; +//import net.minecraft.util.GsonHelper; +//import net.minecraft.world.item.ItemStack; +//import net.minecraft.world.item.crafting.Ingredient; +//import net.minecraftforge.common.MinecraftForge; +//import net.minecraftforge.common.crafting.AbstractIngredient; +//import net.minecraftforge.common.crafting.CraftingHelper; +//import net.minecraftforge.common.crafting.IIngredientSerializer; +//import net.minecraftforge.common.crafting.conditions.ICondition; +//import net.minecraftforge.event.AddReloadListenerEvent; +//import org.jetbrains.annotations.Nullable; +// +//import java.util.LinkedList; +//import java.util.List; +//import java.util.function.Function; +// +//import static codechicken.lib.CodeChickenLib.MOD_ID; +// +///** +// * Created by covers1624 on 24/9/22. +// */ +//public class ConditionalIngredient extends AbstractIngredient { +// +// private static final ResourceLocation TYPE = new ResourceLocation(MOD_ID, "conditional"); +// +// private final List conditions; +// private final Ingredient pass; +// @Nullable +// private final Ingredient fail; +// +// private ConditionalIngredient(List conditions, Ingredient pass, @Nullable Ingredient fail) { +// this.conditions = conditions; +// this.pass = pass; +// this.fail = fail; +// } +// +// public static ConditionalIngredient.Builder builder() { +// return new ConditionalIngredient.Builder(); +// } +// +// @Override +// public JsonElement toJson() { +// JsonObject obj = new JsonObject(); +// obj.addProperty("type", TYPE.toString()); +// JsonArray conditions = new JsonArray(); +// for (ICondition condition : this.conditions) { +// conditions.add(CraftingHelper.serialize(condition)); +// } +// obj.add("conditions", conditions); +// obj.add("pass", pass.toJson()); +// if (fail != null) { +// obj.add("fail", fail.toJson()); +// } +// return obj; +// } +// +// // @formatter:off +// @Override public ItemStack[] getItems() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } +// @Override public boolean isSimple() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } +// @Override public IIngredientSerializer getSerializer() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } +// // @formatter:on +// +// public static class Builder { +// +// private List conditions = new LinkedList<>(); +// private Ingredient pass = null; +// private Ingredient fail = null; +// +// private Builder() { +// } +// +// public Builder withCondition(Function func) { +// conditions.add(func.apply(ConditionBuilder.INSTANCE)); +// return this; +// } +// +// public Builder withPass(Ingredient ing) { +// if (pass != null) throw new IllegalStateException("Pass Ingredient already specified."); +// this.pass = ing; +// return this; +// } +// +// public Builder withFail(Ingredient ing) { +// if (fail != null) throw new IllegalStateException("Pass Ingredient already specified."); +// this.fail = ing; +// return this; +// } +// +// public ConditionalIngredient build() { +// if (conditions.isEmpty()) throw new IllegalStateException("No conditions specified."); +// if (pass == null) throw new IllegalStateException("Pass Ingredient is required."); +// +// return new ConditionalIngredient(conditions, pass, fail); +// } +// } +// +// public static class Serializer implements IIngredientSerializer { +// +// private static final CrashLock LOCK = new CrashLock("Already Initialized"); +// private static ICondition.IContext conditionContext = ICondition.IContext.EMPTY; +// +// public static void init() { +// LOCK.lock(); +// MinecraftForge.EVENT_BUS.addListener(Serializer::onAddReloadListenerEvent); +// CraftingHelper.register(TYPE, new Serializer()); +// } +// +// private static void onAddReloadListenerEvent(AddReloadListenerEvent event) { +// conditionContext = event.getConditionContext(); +// } +// +// @Override +// public Ingredient parse(JsonObject json) { +// if (!CraftingHelper.processConditions(json, "conditions", conditionContext)) { +// if (json.has("fail")) { +// return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "fail"), true); +// } +// return Ingredient.EMPTY; +// } +// return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "pass"), false); +// } +// +// // We don't operate like this, we always return a different ingredient. +// // @formatter:off +// @Override public Ingredient parse(FriendlyByteBuf buffer) { throw new UnsupportedOperationException(); } +// @Override public void write(FriendlyByteBuf buffer, Ingredient ingredient) { throw new UnsupportedOperationException(); } +// // @formatter:on +// } +//} diff --git a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java index b251e4c0..1d135291 100644 --- a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java +++ b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java @@ -11,7 +11,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.resources.Resource; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import javax.imageio.ImageIO; import java.awt.*; @@ -30,6 +30,7 @@ * Created by brandon3055 on 07/09/2023 */ public class DynamicTextureProvider implements DataProvider { + private final DataGenerator gen; private final ExistingFileHelper fileHelper; private final String modid; @@ -174,6 +175,7 @@ public String getName() { } private static class GeneratorResult { + private final byte[] fileBytes; private final Path path; diff --git a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java index 20b17f49..ca153916 100644 --- a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java +++ b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java @@ -3,16 +3,16 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.model.generators.ItemModelBuilder; -import net.minecraftforge.client.model.generators.ModelFile; -import net.minecraftforge.client.model.generators.ModelProvider; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.client.model.generators.ItemModelBuilder; +import net.neoforged.neoforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.client.model.generators.ModelProvider; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -26,6 +26,7 @@ import java.util.function.Supplier; import static codechicken.lib.CodeChickenLib.MOD_ID; +import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 15/10/20. @@ -43,7 +44,7 @@ public ItemModelProvider(PackOutput output, String modid, ExistingFileHelper exi //region Location helpers protected String name(ItemLike item) { - return ForgeRegistries.ITEMS.getKey(item.asItem()).getPath(); + return BuiltInRegistries.ITEM.getKey(item.asItem()).getPath(); } protected ResourceLocation itemTexture(ItemLike item) { @@ -176,7 +177,7 @@ public static class SimpleItemModelBuilder { private final ItemModelBuilder builder; private final Item item; private final Map layers = new HashMap<>(); - private ModelFile parent; + private @Nullable ModelFile parent; private boolean noTexture = false; private String folder = ""; @@ -192,11 +193,11 @@ private SimpleItemModelBuilder(ItemModelProvider provider, ItemModelBuilder buil } public SimpleItemModelBuilder parent(ModelFile parent) { - this.parent = Objects.requireNonNull(parent); + this.parent = requireNonNull(parent); return this; } - public SimpleItemModelBuilder texture(ResourceLocation texture) { + public SimpleItemModelBuilder texture(@Nullable ResourceLocation texture) { if (texture == null) throw new IllegalStateException("Use '.noTexture()' instead of '.texture(null)'"); return texture("layer0", texture); } @@ -205,7 +206,7 @@ public SimpleItemModelBuilder texture(String layer, ResourceLocation texture) { if (noTexture) throw new IllegalStateException("Unable to set texture. NoTexture set."); if (!StringUtils.isEmpty(folder)) throw new IllegalArgumentException("Adding texture would ignore existing folder."); - ResourceLocation existing = layers.put(layer, Objects.requireNonNull(texture)); + ResourceLocation existing = layers.put(layer, requireNonNull(texture)); if (existing != null) { LOGGER.warn("Overwriting layer '{}' texture '{}' with '{}'", layer, existing, texture); } @@ -216,7 +217,7 @@ public SimpleItemModelBuilder folder(String folder) { if (!layers.isEmpty()) throw new IllegalStateException("Textures set, folder would be ignored."); if (noTexture) throw new IllegalStateException("No Texture set, folder would be ignored."); - this.folder = Objects.requireNonNull(folder); + this.folder = requireNonNull(folder); return this; } @@ -248,7 +249,7 @@ public ModelFile getModel() { private void build() { if (!built) { - builder.parent(parent); + builder.parent(requireNonNull(parent, "Model requires a parent.")); if (!noTexture) { if (layers.isEmpty()) { builder.texture("layer0", provider.itemTexture(item, folder)); @@ -266,7 +267,7 @@ private void build() { private static class WrappedItemModelBuilder extends ItemModelBuilder { - private SimpleItemModelBuilder simpleBuilder; + private @Nullable SimpleItemModelBuilder simpleBuilder; public WrappedItemModelBuilder(ResourceLocation outputLocation, ExistingFileHelper existingFileHelper) { super(outputLocation, existingFileHelper); @@ -372,7 +373,7 @@ public ClassCustomLoaderBuilder clazz(Class clazz) { @Override protected JsonObject toJson(JsonObject json) { super.toJson(json); - json.addProperty("class", Objects.requireNonNull(clazz).getName()); + json.addProperty("class", requireNonNull(clazz).getName()); return json; } } diff --git a/src/main/java/codechicken/lib/datagen/LanguageProvider.java b/src/main/java/codechicken/lib/datagen/LanguageProvider.java index 87e232c3..bc404c24 100644 --- a/src/main/java/codechicken/lib/datagen/LanguageProvider.java +++ b/src/main/java/codechicken/lib/datagen/LanguageProvider.java @@ -12,7 +12,7 @@ import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.data.event.GatherDataEvent; +import net.neoforged.neoforge.data.event.GatherDataEvent; import java.nio.file.Path; import java.util.LinkedList; diff --git a/src/main/java/codechicken/lib/datagen/LootTableProvider.java b/src/main/java/codechicken/lib/datagen/LootTableProvider.java deleted file mode 100644 index 458a4bad..00000000 --- a/src/main/java/codechicken/lib/datagen/LootTableProvider.java +++ /dev/null @@ -1,166 +0,0 @@ -package codechicken.lib.datagen; - -import com.google.common.collect.Multimap; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import net.minecraft.advancements.critereon.EnchantmentPredicate; -import net.minecraft.advancements.critereon.ItemPredicate; -import net.minecraft.advancements.critereon.MinMaxBounds; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataProvider; -import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.storage.loot.*; -import net.minecraft.world.level.storage.loot.entries.LootItem; -import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; -import net.minecraft.world.level.storage.loot.functions.ApplyBonusCount; -import net.minecraft.world.level.storage.loot.functions.SetItemCountFunction; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; -import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraft.world.level.storage.loot.predicates.MatchTool; -import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; -import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator; -import net.minecraftforge.registries.ForgeRegistries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.nio.file.Path; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -/** - * Created by covers1624 on 7/10/20. - */ -public abstract class LootTableProvider implements DataProvider { - - private static final Logger logger = LogManager.getLogger(); - - private final PackOutput.PathProvider output; - protected final String modId; - private final Map tables = new HashMap<>(); - - protected LootTableProvider(PackOutput output, String modId) { - this.output = output.createPathProvider(PackOutput.Target.DATA_PACK, "loot_tables"); - this.modId = modId; - } - - @Override - public CompletableFuture run(CachedOutput cache) { - tables.clear(); - - registerTables(); - - ValidationContext validator = new ValidationContext(LootContextParamSets.ALL_PARAMS, new LootDataResolver() { - @Override - public T getElement(LootDataId pId) { - return null; - } - }); - - tables.forEach((name, table) -> table.validate(validator)); - - Multimap problems = validator.getProblems(); - if (!problems.isEmpty()) { - logger.warn("Problems detected for LootTableGenerator: " + getName()); - problems.forEach((name, table) -> { - logger.warn("Found validation problem in {}: {}", name, table); - }); - throw new IllegalStateException("Failed to validate loot tables, see logs."); - } - List> futures = new LinkedList<>(); - tables.forEach((name, table) -> { - Path output = this.output.json(name); - futures.add(DataProvider.saveStable(cache, LootDataType.TABLE.parser().toJsonTree(table), output)); - }); - return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); - } - - protected abstract void registerTables(); - - protected void registerTable(ResourceLocation name, LootTable table) { - if (tables.put(name, table) != null) { - throw new IllegalArgumentException("Duplicate loot table registered: " + name); - } - } - - public static abstract class BlockLootProvider extends LootTableProvider { - - protected static final LootItemCondition.Builder SILK_TOUCH = MatchTool.toolMatches(ItemPredicate.Builder.item() - .hasEnchantment(new EnchantmentPredicate(Enchantments.SILK_TOUCH, MinMaxBounds.Ints.atLeast(1))) - ); - protected static final LootItemCondition.Builder NO_SILK_TOUCH = SILK_TOUCH.invert(); - - protected BlockLootProvider(PackOutput output, String modId) { - super(output, modId); - } - - protected LootPool.Builder singleItem(ItemLike item) { - return LootPool.lootPool() - .setRolls(ConstantValue.exactly(1)) - .add(LootItem.lootTableItem(item)); - } - - protected LootPool.Builder singleItemOr(ItemLike failDrop, LootItemCondition.Builder condition, LootPoolEntryContainer.Builder passDrop) { - return LootPool.lootPool() - .setRolls(ConstantValue.exactly(1)) - .add(LootItem.lootTableItem(failDrop) - .when(condition) - .otherwise(passDrop) - ); - } - - protected LootPool.Builder singleItemOrSilk(ItemLike silk, LootItem.Builder drop) { - return singleItemOr(silk, SILK_TOUCH, drop); - } - - protected LootPool.Builder singleItemOrSilk(ItemLike silk, ItemLike drop) { - return singleItemOrSilk(silk, LootItem.lootTableItem(drop)); - } - - protected LootPool.Builder valueRange(ItemLike item, int min, int max) { - return LootPool.lootPool() - .setRolls(ConstantValue.exactly(1)) - .add(LootItem.lootTableItem(item) - .apply(SetItemCountFunction.setCount(UniformGenerator.between(min, max))) - ); - } - - protected LootPool.Builder valueRangeOrSilk(ItemLike silk, ItemLike drop, int min, int max) { - return singleItemOr(silk, SILK_TOUCH, LootItem.lootTableItem(drop).apply(SetItemCountFunction.setCount(UniformGenerator.between(min, max)))); - } - - protected LootPool.Builder valueRangeOrSilkWithFortune(ItemLike silk, ItemLike drop, int min, int max) { - return singleItemOr(silk, SILK_TOUCH, LootItem.lootTableItem(drop) - .apply(SetItemCountFunction.setCount(UniformGenerator.between(min, max))) - .apply(ApplyBonusCount.addOreBonusCount(Enchantments.BLOCK_FORTUNE)) - ); - } - - protected void register(Block block, LootPool.Builder... pools) { - LootTable.Builder builder = LootTable.lootTable(); - for (LootPool.Builder pool : pools) { - builder.withPool(pool); - } - register(block, builder); - } - - public void register(Block block, LootTable.Builder builder) { - register(ForgeRegistries.BLOCKS.getKey(block), builder); - } - - protected void register(ResourceLocation name, LootTable.Builder builder) { - registerTable(new ResourceLocation(name.getNamespace(), "blocks/" + name.getPath()), builder.setParamSet(LootContextParamSets.BLOCK).build()); - } - - @Override - public String getName() { - return modId + " Block Loot Tables"; - } - } -} diff --git a/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java new file mode 100644 index 00000000..38f9eaca --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java @@ -0,0 +1,43 @@ +package codechicken.lib.datagen; + +import net.minecraft.data.loot.BlockLootSubProvider; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.storage.loot.LootTable; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; + +/** + * Created by covers1624 on 16/9/24. + */ +public abstract class NoValidationBLockLootSubProvider extends BlockLootSubProvider { + + private final Map map; + + protected NoValidationBLockLootSubProvider() { + this(Set.of()); + } + + protected NoValidationBLockLootSubProvider(Set explosionResistant) { + this(explosionResistant, FeatureFlagSet.of()); + } + + protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags) { + this(explosionResistant, flags, new HashMap<>()); + } + + protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags, Map map) { + super(explosionResistant, flags, map); + this.map = map; + } + + @Override + public void generate(BiConsumer cons) { + generate(); + map.forEach(cons); + } +} diff --git a/src/main/java/codechicken/lib/datagen/package-info.java b/src/main/java/codechicken/lib/datagen/package-info.java new file mode 100644 index 00000000..40e9603d --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.datagen; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java index 24c8b1e2..d9cbf8cb 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java @@ -1,44 +1,18 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonObject; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.world.item.crafting.Recipe; /** * Created by covers1624 on 28/12/20. */ public abstract class AbstractItemStackRecipeBuilder> extends AbstractRecipeBuilder { - protected AbstractItemStackRecipeBuilder(RecipeSerializer serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + protected AbstractItemStackRecipeBuilder(ResourceLocation id, ItemStack result) { + super(id, result); } @Override - protected ResourceLocation getAdvancementId() { - return new ResourceLocation(id.getNamespace(), "recipes/__advancement/" + id.getPath()); - } - - @Override - public abstract AbstractItemStackFinishedRecipe _build(); - - public abstract class AbstractItemStackFinishedRecipe extends AbstractFinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); - JsonObject result = new JsonObject(); - ItemStack resultStack = AbstractItemStackRecipeBuilder.this.result; - result.addProperty("item", ForgeRegistries.ITEMS.getKey(resultStack.getItem()).toString()); - if (resultStack.getCount() > 1) { - result.addProperty("count", resultStack.getCount()); - } - //TODO, caps? - if (resultStack.hasTag()) { - result.addProperty("nbt", resultStack.getTag().toString()); - } - json.add("result", result); - } - } + public abstract Recipe _build(); } diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java index c65b2a52..73b779a6 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java @@ -1,28 +1,17 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import net.minecraft.advancements.Advancement; -import net.minecraft.advancements.AdvancementRewards; -import net.minecraft.advancements.CriterionTriggerInstance; -import net.minecraft.advancements.RequirementsStrategy; -import net.minecraft.advancements.critereon.*; -import net.minecraft.data.recipes.FinishedRecipe; +import net.minecraft.advancements.*; +import net.minecraft.advancements.critereon.InventoryChangeTrigger; +import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.advancements.critereon.RecipeUnlockedTrigger; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.common.crafting.conditions.ICondition; -import org.apache.commons.lang3.StringUtils; +import net.neoforged.neoforge.common.conditions.ICondition; -import javax.annotation.Nullable; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.function.Function; +import java.util.*; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; @@ -34,7 +23,6 @@ public abstract class AbstractRecipeBuilder conditions = new LinkedList<>(); - protected final RecipeSerializer serializer; protected final ResourceLocation id; protected final R result; private final Set criteriaItems = new HashSet<>(); @@ -42,10 +30,9 @@ public abstract class AbstractRecipeBuilder serializer, ResourceLocation id, R result) { - this.serializer = serializer; + protected AbstractRecipeBuilder(ResourceLocation id, R result) { this.id = id; this.result = result; } @@ -54,10 +41,8 @@ protected T getThis() { return unsafeCast(this); } - protected abstract ResourceLocation getAdvancementId(); - - public T withCondition(Function f) { - conditions.add(f.apply(ConditionBuilder.INSTANCE)); + public T withCondition(ICondition cond) { + conditions.add(cond); return getThis(); } @@ -77,7 +62,7 @@ public T setGroup(String group) { return getThis(); } - public T addCriterion(String name, CriterionTriggerInstance criterion) { + public T addCriterion(String name, Criterion criterion) { if (!enableUnlocking) { throw new IllegalStateException("Recipe unlocking must be enabled with 'enableUnlocking'"); } @@ -91,24 +76,25 @@ public final ResourceLocation getId() { } @Override - public final FinishedRecipe build() { + public final BuiltRecipe build() { validate(); if (enableUnlocking) { advancementBuilder.parent(new ResourceLocation("recipes/root")) .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(id)) .rewards(AdvancementRewards.Builder.recipe(id)) - .requirements(RequirementsStrategy.OR); + .requirements(AdvancementRequirements.Strategy.OR); + } + AdvancementHolder advancement = advancementBuilder.build(id.withPrefix("recipes")); + if (advancement.value().criteria().isEmpty()) { + advancement = null; } - return _build(); + return new BuiltRecipe(_build(), advancement, conditions); } protected void validate() { - if (enableUnlocking && advancementBuilder.getCriteria().isEmpty()) { - throw new IllegalStateException("No way of obtaining recipe " + id, created); - } } - protected abstract AbstractFinishedRecipe _build(); + protected abstract Recipe _build(); protected void addAutoCriteria(ItemLike item) { if (generateCriteria && criteriaItems.add(item)) { @@ -122,54 +108,21 @@ protected void addAutoCriteria(TagKey tag) { } } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemLike itemIn) { + protected Criterion hasItem(ItemLike itemIn) { return this.hasItem(ItemPredicate.Builder.item().of(itemIn).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { + protected Criterion hasItem(TagKey tagIn) { return this.hasItem(ItemPredicate.Builder.item().of(tagIn).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemPredicate... predicates) { - return new InventoryChangeTrigger.TriggerInstance(ContextAwarePredicate.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); - } - - public abstract class AbstractFinishedRecipe implements FinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - if (!conditions.isEmpty()) { - JsonArray conditionArray = new JsonArray(); - for (ICondition condition : conditions) { - conditionArray.add(CraftingHelper.serialize(condition)); - } - json.add("conditions", conditionArray); - } - if (StringUtils.isNotEmpty(group)) { - json.addProperty("group", group); - } - } - - @Override - public RecipeSerializer getType() { - return serializer; - } - - @Override - public ResourceLocation getId() { - return id; - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return enableUnlocking ? advancementBuilder.serializeToJson() : null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return AbstractRecipeBuilder.this.getAdvancementId(); - } + protected Criterion hasItem(ItemPredicate... predicates) { + return CriteriaTriggers.INVENTORY_CHANGED.createCriterion( + new InventoryChangeTrigger.TriggerInstance( + Optional.empty(), + InventoryChangeTrigger.TriggerInstance.Slots.ANY, + List.of(predicates) + ) + ); } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/ConditionBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ConditionBuilder.java deleted file mode 100644 index 2566c47e..00000000 --- a/src/main/java/codechicken/lib/datagen/recipe/ConditionBuilder.java +++ /dev/null @@ -1,11 +0,0 @@ -package codechicken.lib.datagen.recipe; - -import net.minecraftforge.common.crafting.conditions.IConditionBuilder; - -/** - * Created by covers1624 on 23/9/22. - */ -public interface ConditionBuilder extends IConditionBuilder { - - ConditionBuilder INSTANCE = new ConditionBuilder() { }; -} diff --git a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java index fe46f8a3..b6f887be 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java @@ -1,19 +1,20 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonObject; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.*; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; import java.util.function.Supplier; +import static java.util.Objects.requireNonNull; + /** * Created by covers1624 on 28/12/20. */ @@ -21,12 +22,16 @@ public class FurnaceRecipeBuilder extends AbstractItemStackRecipeBuilder serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + protected FurnaceRecipeBuilder(ResourceLocation id, ItemStack result, Factory factory) { + super(id, result); + this.factory = factory; } //region Smelting @@ -55,11 +60,11 @@ public static FurnaceRecipeBuilder smelting(Supplier result, } public static FurnaceRecipeBuilder smelting(ItemStack result) { - return smelting(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + return smelting(result, BuiltInRegistries.ITEM.getKey(result.getItem())); } public static FurnaceRecipeBuilder smelting(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.SMELTING_RECIPE, id, result) + return new FurnaceRecipeBuilder(id, result, SmeltingRecipe::new) .cookingTime(200); } //endregion @@ -90,11 +95,11 @@ public static FurnaceRecipeBuilder blasting(Supplier result, } public static FurnaceRecipeBuilder blasting(ItemStack result) { - return blasting(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + return blasting(result, BuiltInRegistries.ITEM.getKey(result.getItem())); } public static FurnaceRecipeBuilder blasting(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.BLASTING_RECIPE, id, result) + return new FurnaceRecipeBuilder(id, result, BlastingRecipe::new) .cookingTime(100); } //endregion @@ -125,11 +130,11 @@ public static FurnaceRecipeBuilder smoking(Supplier result, } public static FurnaceRecipeBuilder smoking(ItemStack result) { - return smoking(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + return smoking(result, BuiltInRegistries.ITEM.getKey(result.getItem())); } public static FurnaceRecipeBuilder smoking(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.SMOKING_RECIPE, id, result) + return new FurnaceRecipeBuilder(id, result, SmokingRecipe::new) .cookingTime(100); } //endregion @@ -160,49 +165,54 @@ public static FurnaceRecipeBuilder campfire(Supplier result, } public static FurnaceRecipeBuilder campfire(ItemStack result) { - return campfire(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + return campfire(result, BuiltInRegistries.ITEM.getKey(result.getItem())); } public static FurnaceRecipeBuilder campfire(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.CAMPFIRE_COOKING_RECIPE, id, result) + return new FurnaceRecipeBuilder(id, result, CampfireCookingRecipe::new) .cookingTime(600); } //endregion //region Custom - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemLike result) { - return custom(serializer, result, 1); + public static FurnaceRecipeBuilder custom(ItemLike result, Factory factory) { + return custom(result, 1, factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count) { - return custom(serializer, new ItemStack(result, count)); + public static FurnaceRecipeBuilder custom(ItemLike result, int count, Factory factory) { + return custom(new ItemStack(result, count), factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { - return custom(serializer, new ItemStack(result, count), id); + public static FurnaceRecipeBuilder custom(ItemLike result, int count, ResourceLocation id, Factory factory) { + return custom(new ItemStack(result, count), id, factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, Supplier result) { - return custom(serializer, result.get(), 1); + public static FurnaceRecipeBuilder custom(Supplier result, Factory factory) { + return custom(result.get(), 1, factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, Supplier result, int count) { - return custom(serializer, new ItemStack(result.get(), count)); + public static FurnaceRecipeBuilder custom(Supplier result, int count, Factory factory) { + return custom(new ItemStack(result.get(), count), factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { - return custom(serializer, new ItemStack(result.get(), count), id); + public static FurnaceRecipeBuilder custom(Supplier result, int count, ResourceLocation id, Factory factory) { + return custom(new ItemStack(result.get(), count), id, factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemStack result) { - return custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static FurnaceRecipeBuilder custom(ItemStack result, Factory factory) { + return custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(serializer, id, result); + public static FurnaceRecipeBuilder custom(ItemStack result, ResourceLocation id, Factory factory) { + return new FurnaceRecipeBuilder(id, result, factory); } //endregion + public FurnaceRecipeBuilder category(CookingBookCategory category) { + this.category = category; + return this; + } + public FurnaceRecipeBuilder ingredient(TagKey tag) { addAutoCriteria(tag); this.ingredient = Ingredient.of(tag); @@ -240,18 +250,20 @@ public FurnaceRecipeBuilder cookingTime(int cookingTime) { } @Override - public AbstractItemStackFinishedRecipe _build() { - return new FinishedFurnaceRecipe(); + public Recipe _build() { + return factory.build(group, category, requireNonNull(ingredient), result, experience, cookingTime); } - public class FinishedFurnaceRecipe extends AbstractItemStackFinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); - json.add("ingredient", ingredient.toJson()); - json.addProperty("experience", experience); - json.addProperty("cookingtime", cookingTime); + @Override + protected void validate() { + super.validate(); + if (ingredient == null) { + throw new IllegalStateException("No ingredient set."); } } + + public interface Factory { + + Recipe build(String group, CookingBookCategory category, Ingredient ingredient, ItemStack result, float experience, int cookingTime); + } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java index 0c94ef1c..e2a9594c 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java @@ -1,9 +1,13 @@ package codechicken.lib.datagen.recipe; -import net.minecraft.data.recipes.FinishedRecipe; +import net.minecraft.advancements.AdvancementHolder; +import net.minecraft.data.recipes.RecipeOutput; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.crafting.Recipe; +import net.neoforged.neoforge.common.conditions.ICondition; +import org.jetbrains.annotations.Nullable; -import java.util.function.Consumer; +import java.util.List; /** * Created by covers1624 on 27/12/20. @@ -12,11 +16,17 @@ public interface RecipeBuilder { ResourceLocation getId(); - FinishedRecipe build(); + BuiltRecipe build(); - //Compat with vanilla's Recipe Provider. - default void build(Consumer consumer) { - consumer.accept(build()); + // Compat with vanilla's Recipe Provider. + default void build(RecipeOutput output) { + BuiltRecipe built = build(); + output.accept(getId(), built.recipe, built.advancement, built.conditions.toArray(ICondition[]::new)); } + record BuiltRecipe( + Recipe recipe, + @Nullable AdvancementHolder advancement, + List conditions + ) { } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java index d1098c45..4de6e13f 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java @@ -1,26 +1,26 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonObject; -import net.minecraft.advancements.critereon.*; +import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.advancements.Criterion; +import net.minecraft.advancements.critereon.EnterBlockTrigger; +import net.minecraft.advancements.critereon.InventoryChangeTrigger; +import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.data.CachedOutput; import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; -import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer; +import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.conditions.WithConditions; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; @@ -30,27 +30,38 @@ public abstract class RecipeProvider implements DataProvider { private final Map recipes = new HashMap<>(); - private final PackOutput output; + private final PackOutput.PathProvider recipePath; + private final PackOutput.PathProvider advancementPath; protected final String modId; public RecipeProvider(PackOutput output, String modId) { - this.output = output; this.modId = modId; + recipePath = output.createPathProvider(PackOutput.Target.DATA_PACK, "recipes"); + advancementPath = output.createPathProvider(PackOutput.Target.DATA_PACK, "advancements"); } @Override public final CompletableFuture run(CachedOutput cache) { - Path path = output.getOutputFolder(); registerRecipes(); List> futures = new LinkedList<>(); for (Map.Entry entry : recipes.entrySet()) { ResourceLocation id = entry.getKey(); - FinishedRecipe finishedRecipe = entry.getValue().build(); - futures.add(DataProvider.saveStable(cache, finishedRecipe.serializeRecipe(), path.resolve("data/" + id.getNamespace() + "/recipes/" + id.getPath() + ".json"))); - - JsonObject advancement = finishedRecipe.serializeAdvancement(); + RecipeBuilder.BuiltRecipe builtRecipe = entry.getValue().build(); + futures.add(DataProvider.saveStable( + cache, + Recipe.CONDITIONAL_CODEC, + Optional.of(new WithConditions<>(builtRecipe.conditions(), builtRecipe.recipe())), + recipePath.json(id) + )); + + AdvancementHolder advancement = builtRecipe.advancement(); if (advancement != null) { - futures.add(DataProvider.saveStable(cache, advancement, path.resolve("data/" + id.getNamespace() + "/advancements/" + id.getPath() + ".json"))); + futures.add(DataProvider.saveStable( + cache, + Advancement.CONDITIONAL_CODEC, + Optional.of(new WithConditions<>(builtRecipe.conditions(), advancement.value())), + advancementPath.json(id) + )); } } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); @@ -73,7 +84,7 @@ protected T builder(T builder) { protected ShapedRecipeBuilder shapedRecipe(Supplier result) { return builder(ShapedRecipeBuilder.builder(result.get(), 1)); } protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result.get(), count))); } protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result.get(), count), id)); } - protected ShapedRecipeBuilder shapedRecipe(ItemStack result) { return builder(ShapedRecipeBuilder.builder(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } + protected ShapedRecipeBuilder shapedRecipe(ItemStack result) { return builder(ShapedRecipeBuilder.builder(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } protected ShapedRecipeBuilder shapedRecipe(ItemStack result, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(result, id)); } protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result) { return builder(ShapelessRecipeBuilder.builder(result, 1)); } @@ -82,7 +93,7 @@ protected T builder(T builder) { protected ShapelessRecipeBuilder shapelessRecipe(Supplier result) { return builder(ShapelessRecipeBuilder.builder(result.get(), 1)); } protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result.get(), count))); } protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result.get(), count), id)); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result) { return builder(ShapelessRecipeBuilder.builder(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result) { return builder(ShapelessRecipeBuilder.builder(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(result, id)); } protected FurnaceRecipeBuilder smelting(ItemLike result) { return builder(FurnaceRecipeBuilder.smelting(result, 1)); } @@ -91,7 +102,7 @@ protected T builder(T builder) { protected FurnaceRecipeBuilder smelting(Supplier result) { return builder(FurnaceRecipeBuilder.smelting(result.get(), 1)); } protected FurnaceRecipeBuilder smelting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result.get(), count))); } protected FurnaceRecipeBuilder smelting(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder smelting(ItemStack result) { return builder(FurnaceRecipeBuilder.smelting(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder smelting(ItemStack result) { return builder(FurnaceRecipeBuilder.smelting(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } protected FurnaceRecipeBuilder smelting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(result, id)); } protected FurnaceRecipeBuilder blasting(ItemLike result) { return builder(FurnaceRecipeBuilder.blasting(result, 1)); } @@ -100,7 +111,7 @@ protected T builder(T builder) { protected FurnaceRecipeBuilder blasting(Supplier result) { return builder(FurnaceRecipeBuilder.blasting(result.get(), 1)); } protected FurnaceRecipeBuilder blasting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result.get(), count))); } protected FurnaceRecipeBuilder blasting(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder blasting(ItemStack result) { return builder(FurnaceRecipeBuilder.blasting(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder blasting(ItemStack result) { return builder(FurnaceRecipeBuilder.blasting(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } protected FurnaceRecipeBuilder blasting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(result, id)); } protected FurnaceRecipeBuilder smoking(ItemLike result) { return builder(FurnaceRecipeBuilder.smoking(result, 1)); } @@ -109,7 +120,7 @@ protected T builder(T builder) { protected FurnaceRecipeBuilder smoking(Supplier result) { return builder(FurnaceRecipeBuilder.smoking(result.get(), 1)); } protected FurnaceRecipeBuilder smoking(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result.get(), count))); } protected FurnaceRecipeBuilder smoking(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder smoking(ItemStack result) { return builder(FurnaceRecipeBuilder.smoking(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder smoking(ItemStack result) { return builder(FurnaceRecipeBuilder.smoking(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } protected FurnaceRecipeBuilder smoking(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(result, id)); } protected FurnaceRecipeBuilder campfire(ItemLike result) { return builder(FurnaceRecipeBuilder.campfire(result, 1)); } @@ -118,58 +129,67 @@ protected T builder(T builder) { protected FurnaceRecipeBuilder campfire(Supplier result) { return builder(FurnaceRecipeBuilder.campfire(result.get(), 1)); } protected FurnaceRecipeBuilder campfire(Supplier result, int count) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result.get(), count))); } protected FurnaceRecipeBuilder campfire(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder campfire(ItemStack result) { return builder(FurnaceRecipeBuilder.campfire(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder campfire(ItemStack result) { return builder(FurnaceRecipeBuilder.campfire(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } protected FurnaceRecipeBuilder campfire(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(result, id)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result) { return builder(ShapedRecipeBuilder.custom(serializer, result, 1)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result, int count) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result, count))); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, Supplier result) { return builder(ShapedRecipeBuilder.custom(serializer, result.get(), 1)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, Supplier result, int count) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result.get(), count))); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result.get(), count), id)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemStack result) { return builder(ShapedRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, result, id)); } - - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result) { return builder(ShapelessRecipeBuilder.custom(serializer, result, 1)); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result, int count) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result, count))); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, Supplier result) { return builder(ShapelessRecipeBuilder.custom(serializer, result.get(), 1)); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, Supplier result, int count) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result.get(), count))); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result.get(), count), id)); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemStack result) { return builder(ShapelessRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, result, id)); } - - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result) { return builder(FurnaceRecipeBuilder.custom(serializer, result, 1)); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result, int count) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result, count))); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, Supplier result) { return builder(FurnaceRecipeBuilder.custom(serializer, result.get(), 1)); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, Supplier result, int count) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result.get(), count))); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result) { return builder(FurnaceRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, result, id)); } - - protected SpecialCraftingRecipeBuilder special(SimpleCraftingRecipeSerializer serializer, String id) { return builder(SpecialCraftingRecipeBuilder.builder(serializer, id)); } - protected SpecialCraftingRecipeBuilder special(SimpleCraftingRecipeSerializer serializer, ResourceLocation id) { return builder(SpecialCraftingRecipeBuilder.builder(serializer, id)); } + protected ShapedRecipeBuilder customShaped(ItemLike result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result, 1, factory)); } + protected ShapedRecipeBuilder customShaped(ItemLike result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result, count), factory)); } + protected ShapedRecipeBuilder customShaped(ItemLike result, int count, ResourceLocation id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result, count), id, factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result.get(), 1, factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result.get(), count), factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, int count, ResourceLocation id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result.get(), count), id, factory)); } + protected ShapedRecipeBuilder customShaped(ItemStack result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected ShapedRecipeBuilder customShaped(ItemStack result, ResourceLocation id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result, id, factory)); } + + protected ShapelessRecipeBuilder customShapeless(ItemLike result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result, 1, factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result, count), factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, ResourceLocation id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result, count), id, factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result.get(), 1, factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result.get(), count), factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, ResourceLocation id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result.get(), count), id, factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemStack result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemStack result, ResourceLocation id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result, id, factory)); } + + protected FurnaceRecipeBuilder customFurnace(ItemLike result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result, 1, factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result, count), factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, ResourceLocation id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result, count), id, factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result.get(), 1, factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result.get(), count), factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, ResourceLocation id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result.get(), count), id, factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemStack result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemStack result, ResourceLocation id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result, id, factory)); } + + protected SpecialCraftingRecipeBuilder special(ItemLike id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + protected SpecialCraftingRecipeBuilder special(Supplier id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id.get(), factory)); } + protected SpecialCraftingRecipeBuilder special(ItemStack id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + protected SpecialCraftingRecipeBuilder special(String id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + protected SpecialCraftingRecipeBuilder special(ResourceLocation id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } //@formatter:on - protected EnterBlockTrigger.TriggerInstance enteredBlock(Block blockIn) { - return new EnterBlockTrigger.TriggerInstance(ContextAwarePredicate.ANY, blockIn, StatePropertiesPredicate.ANY); + protected Criterion enteredBlock(Block blockIn) { + return CriteriaTriggers.ENTER_BLOCK.createCriterion(new EnterBlockTrigger.TriggerInstance(Optional.empty(), Optional.of(blockIn.builtInRegistryHolder()), Optional.empty())); } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemLike itemIn) { + protected Criterion hasItem(ItemLike itemIn) { return hasItem(ItemPredicate.Builder.item().of(itemIn).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(Supplier itemIn) { + protected Criterion hasItem(Supplier itemIn) { return hasItem(ItemPredicate.Builder.item().of(itemIn.get()).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { + protected Criterion hasItem(TagKey tagIn) { return hasItem(ItemPredicate.Builder.item().of(tagIn).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemPredicate... predicates) { - return new InventoryChangeTrigger.TriggerInstance(ContextAwarePredicate.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); + protected Criterion hasItem(ItemPredicate... predicates) { + return CriteriaTriggers.INVENTORY_CHANGED.createCriterion( + new InventoryChangeTrigger.TriggerInstance( + Optional.empty(), + InventoryChangeTrigger.TriggerInstance.Slots.ANY, + List.of(predicates) + ) + ); } @Override diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java index 6b9ae66e..33a6ef37 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java @@ -1,19 +1,16 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; import it.unimi.dsi.fastutil.chars.Char2ObjectMap; import it.unimi.dsi.fastutil.chars.Char2ObjectOpenHashMap; import it.unimi.dsi.fastutil.chars.CharOpenHashSet; import it.unimi.dsi.fastutil.chars.CharSet; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.*; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -28,11 +25,16 @@ public class ShapedRecipeBuilder extends AbstractItemStackRecipeBuilder patternLines = new ArrayList<>(); private final Char2ObjectMap keys = new Char2ObjectOpenHashMap<>(); - protected ShapedRecipeBuilder(RecipeSerializer serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + private CraftingBookCategory category = CraftingBookCategory.MISC; + private boolean showNotification = true; + + protected ShapedRecipeBuilder(ResourceLocation id, ItemStack result, Factory factory) { + super(id, result); + this.factory = factory; } public static ShapedRecipeBuilder builder(ItemLike result) { @@ -60,32 +62,32 @@ public static ShapedRecipeBuilder builder(Supplier result, i } public static ShapedRecipeBuilder builder(ItemStack result) { - return builder(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + return builder(result, BuiltInRegistries.ITEM.getKey(result.getItem())); } public static ShapedRecipeBuilder builder(ItemStack result, ResourceLocation id) { - return new ShapedRecipeBuilder(RecipeSerializer.SHAPED_RECIPE, id, result); + return new ShapedRecipeBuilder(id, result, ShapedRecipe::new); } // region Custom - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemLike result) { - return custom(serializer, result, 1); + public static ShapedRecipeBuilder custom(ItemLike result, Factory factory) { + return custom(result, 1, factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count) { - return custom(serializer, new ItemStack(result, count)); + public static ShapedRecipeBuilder custom(ItemLike result, int count, Factory factory) { + return custom(new ItemStack(result, count), factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { - return custom(serializer, new ItemStack(result, count), id); + public static ShapedRecipeBuilder custom(ItemLike result, int count, ResourceLocation id, Factory factory) { + return custom(new ItemStack(result, count), id, factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemStack result) { - return custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static ShapedRecipeBuilder custom(ItemStack result, Factory factory) { + return custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { - return new ShapedRecipeBuilder(serializer, id, result); + public static ShapedRecipeBuilder custom(ItemStack result, ResourceLocation id, Factory factory) { + return new ShapedRecipeBuilder(id, result, factory); } // endregion @@ -130,9 +132,25 @@ public ShapedRecipeBuilder patternLine(String patternIn) { return this; } + public ShapedRecipeBuilder category(CraftingBookCategory category) { + this.category = category; + return this; + } + + public ShapedRecipeBuilder showNotifications(boolean showNotification) { + this.showNotification = showNotification; + return this; + } + @Override - public AbstractItemStackFinishedRecipe _build() { - return new FinishedShapedRecipe(); + public Recipe _build() { + return factory.build( + group, + category, + ShapedRecipePattern.of(keys, patternLines), + result, + showNotification + ); } @Override @@ -163,20 +181,8 @@ protected void validate() { } } - public class FinishedShapedRecipe extends AbstractItemStackFinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); - JsonArray pattern = new JsonArray(); - patternLines.forEach(pattern::add); - json.add("pattern", pattern); + public interface Factory { - JsonObject key = new JsonObject(); - for (Char2ObjectMap.Entry entry : keys.char2ObjectEntrySet()) { - key.add(String.valueOf(entry.getCharKey()), entry.getValue().toJson()); - } - json.add("key", key); - } + Recipe build(String group, CraftingBookCategory category, ShapedRecipePattern pattern, ItemStack result, boolean showNotification); } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java index 9569e51f..915a4a6e 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java @@ -1,20 +1,16 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; +import net.minecraft.core.NonNullList; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.*; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.util.ArrayList; -import java.util.List; import java.util.function.Supplier; /** @@ -24,10 +20,14 @@ public class ShapelessRecipeBuilder extends AbstractItemStackRecipeBuilder ingredients = new ArrayList<>(); + private final Factory factory; + private final NonNullList ingredients = NonNullList.create(); - protected ShapelessRecipeBuilder(RecipeSerializer serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + private CraftingBookCategory category = CraftingBookCategory.MISC; + + protected ShapelessRecipeBuilder(ResourceLocation id, ItemStack result, Factory factory) { + super(id, result); + this.factory = factory; } public static ShapelessRecipeBuilder builder(ItemLike result) { @@ -55,32 +55,32 @@ public static ShapelessRecipeBuilder builder(Supplier result } public static ShapelessRecipeBuilder builder(ItemStack result) { - return builder(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + return builder(result, BuiltInRegistries.ITEM.getKey(result.getItem())); } public static ShapelessRecipeBuilder builder(ItemStack result, ResourceLocation id) { - return new ShapelessRecipeBuilder(RecipeSerializer.SHAPELESS_RECIPE, id, result); + return new ShapelessRecipeBuilder(id, result, ShapelessRecipe::new); } // region Custom - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemLike result) { - return custom(serializer, result, 1); + public static ShapelessRecipeBuilder custom(ItemLike result, Factory factory) { + return custom(result, 1, factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count) { - return custom(serializer, new ItemStack(result, count)); + public static ShapelessRecipeBuilder custom(ItemLike result, int count, Factory factory) { + return custom(new ItemStack(result, count), factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { - return custom(serializer, new ItemStack(result, count), id); + public static ShapelessRecipeBuilder custom(ItemLike result, int count, ResourceLocation id, Factory factory) { + return custom(new ItemStack(result, count), id, factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemStack result) { - return custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static ShapelessRecipeBuilder custom(ItemStack result, Factory factory) { + return custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { - return new ShapelessRecipeBuilder(serializer, id, result); + public static ShapelessRecipeBuilder custom(ItemStack result, ResourceLocation id, Factory factory) { + return new ShapelessRecipeBuilder(id, result, factory); } // endregion @@ -138,22 +138,23 @@ public ShapelessRecipeBuilder addIngredient(Ingredient ingredient, int quantity) return this; } - @Override - public AbstractItemStackFinishedRecipe _build() { - return new FinishedShapelessRecipe(); + public ShapelessRecipeBuilder category(CraftingBookCategory category) { + this.category = category; + return this; } - public class FinishedShapelessRecipe extends AbstractItemStackFinishedRecipe { + @Override + public Recipe _build() { + return factory.build( + group, + category, + result, + ingredients + ); + } - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); + public interface Factory { - JsonArray ingredients = new JsonArray(); - for (Ingredient ingredient : ShapelessRecipeBuilder.this.ingredients) { - ingredients.add(ingredient.toJson()); - } - json.add("ingredients", ingredients); - } + Recipe build(String group, CraftingBookCategory category, ItemStack result, NonNullList ingredients); } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java index 17a29d61..130cdd32 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java @@ -1,30 +1,46 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonObject; -import net.minecraft.data.recipes.FinishedRecipe; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.level.ItemLike; + +import java.util.List; +import java.util.function.Supplier; /** * Created by covers1624 on 25/3/21. */ public class SpecialCraftingRecipeBuilder implements RecipeBuilder { - protected final SimpleCraftingRecipeSerializer serializer; protected final ResourceLocation id; - public SpecialCraftingRecipeBuilder(SimpleCraftingRecipeSerializer serializer, ResourceLocation id) { - this.serializer = serializer; + private final Factory factory; + + public SpecialCraftingRecipeBuilder(ResourceLocation id, Factory factory) { this.id = id; + this.factory = factory; } - public static SpecialCraftingRecipeBuilder builder(SimpleCraftingRecipeSerializer serializer, String id) { - return builder(serializer, new ResourceLocation(id)); + public static SpecialCraftingRecipeBuilder builder(ItemLike id, Factory factory) { + return builder(BuiltInRegistries.ITEM.getKey(id.asItem()), factory); } - public static SpecialCraftingRecipeBuilder builder(SimpleCraftingRecipeSerializer serializer, ResourceLocation id) { - return new SpecialCraftingRecipeBuilder(serializer, id); + public static SpecialCraftingRecipeBuilder builder(Supplier id, Factory factory) { + return builder(id.get(), factory); + } + + public static SpecialCraftingRecipeBuilder builder(ItemStack id, Factory factory) { + return builder(id.getItem(), factory); + } + + public static SpecialCraftingRecipeBuilder builder(String id, Factory factory) { + return builder(new ResourceLocation(id), factory); + } + + public static SpecialCraftingRecipeBuilder builder(ResourceLocation id, Factory factory) { + return new SpecialCraftingRecipeBuilder(id, factory); } @Override @@ -33,17 +49,16 @@ public ResourceLocation getId() { } @Override - public FinishedRecipe build() { - return new SpecialFinishedRecipe(); + public BuiltRecipe build() { + return new BuiltRecipe( + factory.build(), + null, + List.of() + ); } - //@formatter:off - protected class SpecialFinishedRecipe implements FinishedRecipe { - @Override public void serializeRecipeData(JsonObject p_218610_1_) { } - @Override public ResourceLocation getId() { return id; } - @Override public RecipeSerializer getType() { return serializer; } - @Override public JsonObject serializeAdvancement() { return null; } - @Override public ResourceLocation getAdvancementId() { return null; } + public interface Factory { + + Recipe build(); } - //@formatter:on } diff --git a/src/main/java/codechicken/lib/datagen/recipe/package-info.java b/src/main/java/codechicken/lib/datagen/recipe/package-info.java new file mode 100644 index 00000000..e7fc155b --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/recipe/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.datagen.recipe; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/fluid/FluidUtils.java b/src/main/java/codechicken/lib/fluid/FluidUtils.java index e1fef24d..77844424 100644 --- a/src/main/java/codechicken/lib/fluid/FluidUtils.java +++ b/src/main/java/codechicken/lib/fluid/FluidUtils.java @@ -2,8 +2,8 @@ import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; public class FluidUtils { diff --git a/src/main/java/codechicken/lib/fluid/package-info.java b/src/main/java/codechicken/lib/fluid/package-info.java new file mode 100644 index 00000000..b7b2ffd3 --- /dev/null +++ b/src/main/java/codechicken/lib/fluid/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.fluid; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGui.java b/src/main/java/codechicken/lib/gui/modular/ModularGui.java index 8955970c..3ad8fb93 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGui.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGui.java @@ -6,7 +6,6 @@ import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GeoParam; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import net.covers1624.quack.collection.FastStream; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; @@ -15,14 +14,16 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.Slot; -import net.minecraft.world.item.ItemStack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.util.TriConsumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.function.Consumer; /** @@ -35,6 +36,7 @@ * @see ContainerGuiProvider */ public class ModularGui implements GuiParent { + private static final Logger LOGGER = LogManager.getLogger(); private final GuiProvider provider; @@ -344,13 +346,14 @@ public boolean charTyped(char character, int modifiers) { /** * Pass through for the mouseScrolled event. Any screen implementing {@link ModularGui} must pass through this event. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param scroll Scroll direction and amount + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scrollX Scroll direction and amount + * @param scrollY Scroll direction and amount * @return true if this event has been consumed. */ - public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { - return root.mouseScrolled(mouseX, mouseY, scroll, false); + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return root.mouseScrolled(mouseX, mouseY, scrollX, scrollY, false); } /** @@ -519,7 +522,7 @@ public GuiElement getSlotHandler(Slot slot) { /** * Sets the current mouse cursor. * The cursor is reset at the end of each UI tick so this must be set every tick for as long as you want your custom cursor to be active. - * */ + */ public void setCursor(ResourceLocation cursor) { this.newCursor = cursor; } @@ -584,7 +587,6 @@ public void onMouseClickPost(TriConsumer onClick) { postClickListeners.add(onClick); } - /** * Allows you to attach a callback that will be fired on key press, before the is handled by the rest of the gui. */ diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java index f1dbb21b..7caeec3f 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -76,7 +76,7 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float imageHeight = (int) root.getValue(GeoParam.HEIGHT); if (modularGui.renderBackground()) { - renderBackground(graphics); + renderBackground(graphics, mouseX, mouseY, partialTicks); } GuiRender render = GuiRender.convert(graphics);//modularGui.createRender(graphics.bufferSource()); modularGui.render(render, partialTicks); @@ -168,8 +168,8 @@ public boolean mouseReleased(double mouseX, double mouseY, int button) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { - return modularGui.mouseScrolled(mouseX, mouseY, scroll) || super.mouseScrolled(mouseX, mouseY, scroll); + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return modularGui.mouseScrolled(mouseX, mouseY, scrollX, scrollY) || super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } @Override diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java index 2e6251fd..337bb5aa 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java @@ -65,7 +65,7 @@ public void resize(@NotNull Minecraft minecraft, int width, int height) { @Override public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { if (modularGui.renderBackground()) { - renderBackground(graphics); + renderBackground(graphics, mouseX, mouseY, partialTicks); } GuiRender render = GuiRender.convert(graphics); modularGui.render(render, partialTicks); @@ -100,8 +100,8 @@ public boolean mouseReleased(double mouseX, double mouseY, int button) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { - return modularGui.mouseScrolled(mouseX, mouseY, scroll) || super.mouseScrolled(mouseX, mouseY, scroll); + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return modularGui.mouseScrolled(mouseX, mouseY, scrollX, scrollY) || super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } @Override diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java index 2f291833..f4434224 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java @@ -3,7 +3,7 @@ import codechicken.lib.gui.modular.lib.Constraints; import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import codechicken.lib.gui.modular.sprite.GuiTextures; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.core.Holder; import net.minecraft.network.chat.Component; @@ -60,7 +60,7 @@ public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Componen */ public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Component label) { GuiButton button = new GuiButton(parent); - GuiTexture texture = new GuiTexture(button, CCGuiTextures.getter(() -> button.toggleState() ? "dynamic/button_highlight" : "dynamic/button_vanilla")); + GuiTexture texture = new GuiTexture(button, GuiTextures.CCL.getter(() -> button.toggleState() ? "dynamic/button_highlight" : "dynamic/button_vanilla")); texture.dynamicTexture(); GuiRectangle highlight = new GuiRectangle(button).border(() -> button.hoverTime() > 0 ? 0xFFFFFFFF : 0); @@ -103,7 +103,7 @@ public static GuiButton vanillaAnimated(@NotNull GuiParent parent, Component */ public static GuiButton vanillaAnimated(@NotNull GuiParent parent, @Nullable Supplier label) { GuiButton button = new GuiButton(parent); - GuiTexture texture = new GuiTexture(button, CCGuiTextures.getter(() -> button.toggleState() || button.isPressed() ? "dynamic/button_pressed" : "dynamic/button_vanilla")); + GuiTexture texture = new GuiTexture(button, GuiTextures.CCL.getter(() -> button.toggleState() || button.isPressed() ? "dynamic/button_pressed" : "dynamic/button_vanilla")); texture.dynamicTexture(); GuiRectangle highlight = new GuiRectangle(button).border(() -> button.isMouseOver() ? 0xFFFFFFFF : 0); diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java index f91ce143..907885b0 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java @@ -4,7 +4,7 @@ import codechicken.lib.gui.modular.lib.Constraints; import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import codechicken.lib.gui.modular.sprite.GuiTextures; import codechicken.lib.gui.modular.sprite.Material; import codechicken.lib.util.FormatUtil; import net.minecraft.client.gui.screens.Screen; @@ -26,8 +26,8 @@ */ public class GuiEnergyBar extends GuiElement implements BackgroundRender { public static final DecimalFormat COMMA_FORMAT = new DecimalFormat("###,###,###,###,###", DecimalFormatSymbols.getInstance(Locale.ROOT)); - public static final Material EMPTY = CCGuiTextures.getUncached("widgets/energy_empty"); - public static final Material FULL = CCGuiTextures.getUncached("widgets/energy_full"); + public static final Material EMPTY = GuiTextures.CCL.getUncached("widgets/energy_empty"); + public static final Material FULL = GuiTextures.CCL.getUncached("widgets/energy_full"); private Supplier energy = () -> 0L; private Supplier capacity = () -> 0L; diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java index b7b502cb..2334b94f 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java @@ -7,19 +7,14 @@ import codechicken.lib.render.CCRenderEventHandler; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.inventory.InventoryScreen; -import net.minecraft.client.player.RemotePlayer; -import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; @@ -37,6 +32,7 @@ * Created by brandon3055 on 15/11/2023 */ public class GuiEntityRenderer extends GuiElement implements BackgroundRender { + public static final Logger LOGGER = LogManager.getLogger(); private static final Map entityCache = new HashMap<>(); private static final List invalidEntities = new ArrayList<>(); @@ -62,7 +58,7 @@ public GuiEntityRenderer setEntity(Entity entity) { return this; } - this.entityName = ForgeRegistries.ENTITY_TYPES.getKey(entity.getType()); + this.entityName = BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()); invalidEntity = invalidEntities.contains(entityName); return this; } @@ -70,7 +66,7 @@ public GuiEntityRenderer setEntity(Entity entity) { public GuiEntityRenderer setEntity(ResourceLocation entity) { this.entityName = entity; this.entity = entityCache.computeIfAbsent(entity, resourceLocation -> { - EntityType type = ForgeRegistries.ENTITY_TYPES.getValue(entity); + EntityType type = BuiltInRegistries.ENTITY_TYPE.getOptional(entity).orElse(null); return type == null ? null : type.create(mc().level); }); @@ -185,7 +181,7 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo renderEntityInInventoryWithRotation(render, xPos, yPos, scale, force2dSize, rotation, living); } } else { - Quaternionf quaternionf = new Quaternionf().rotateZ((float)Math.PI); + Quaternionf quaternionf = new Quaternionf().rotateZ((float) Math.PI); Quaternionf quaternionf1 = Axis.YP.rotationDegrees(rotation); quaternionf.mul(quaternionf1); renderEntityInInventory(render, xPos, yPos, scale, force2dSize, quaternionf, quaternionf1, entity); @@ -204,8 +200,8 @@ public static void renderEntityInInventoryFollowsMouse(GuiRender render, double } public static void renderEntityInInventoryFollowsMouse(GuiRender render, double pX, double pY, double pScale, boolean flat, float offsetX, float offsetY, LivingEntity pEntity) { - float xAngle = (float)Math.atan(offsetX / 40.0F); - float yAngle = (float)Math.atan(offsetY / 40.0F); + float xAngle = (float) Math.atan(offsetX / 40.0F); + float yAngle = (float) Math.atan(offsetY / 40.0F); renderEntityInInventoryFollowsAngle(render, pX, pY, pScale, flat, xAngle, yAngle, pEntity); } @@ -214,8 +210,8 @@ public static void renderEntityInInventoryFollowsAngle(GuiRender render, double } public static void renderEntityInInventoryFollowsAngle(GuiRender render, double pX, double pY, double pScale, boolean flat, float angleX, float angleY, LivingEntity pEntity) { - Quaternionf quaternionf = (new Quaternionf()).rotateZ((float)Math.PI); - Quaternionf quaternionf1 = (new Quaternionf()).rotateX(angleY * 20.0F * ((float)Math.PI / 180F)); + Quaternionf quaternionf = (new Quaternionf()).rotateZ((float) Math.PI); + Quaternionf quaternionf1 = (new Quaternionf()).rotateX(angleY * 20.0F * ((float) Math.PI / 180F)); quaternionf.mul(quaternionf1); float f2 = pEntity.yBodyRot; float f3 = pEntity.getYRot(); @@ -240,7 +236,7 @@ public static void renderEntityInInventoryWithRotation(GuiRender render, double } public static void renderEntityInInventoryWithRotation(GuiRender render, double xPos, double yPos, double scale, boolean flat, double rotation, LivingEntity living) { - Quaternionf quaternionf = new Quaternionf().rotateZ((float)Math.PI); + Quaternionf quaternionf = new Quaternionf().rotateZ((float) Math.PI); Quaternionf quaternionf1 = Axis.YP.rotationDegrees((float) rotation); quaternionf.mul(quaternionf1); float f2 = living.yBodyRot; @@ -268,7 +264,7 @@ public static void renderEntityInInventory(GuiRender render, double pX, double p public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, boolean flat, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, Entity pEntity) { render.pose().pushPose(); render.pose().translate(pX, pY, 50.0D); - render.pose().mulPoseMatrix((new Matrix4f()).scaling((float)pScale, (float)pScale, flat ? -1 : (float)(-pScale))); + render.pose().mulPoseMatrix((new Matrix4f()).scaling((float) pScale, (float) pScale, flat ? -1 : (float) (-pScale))); render.pose().mulPose(quat); Lighting.setupForEntityInInventory(); EntityRenderDispatcher entityrenderdispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java index 393ba6c3..9ff6c5d2 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java @@ -11,13 +11,14 @@ /** * Created by brandon3055 on 15/11/2023 */ +// TODO Replace TriConsumer. public class GuiEventProvider extends GuiElement { private boolean ignoreConsumed = false; private final List> clickListeners = new ArrayList<>(); private final List> releaseListeners = new ArrayList<>(); private final List> movedListeners = new ArrayList<>(); - private final List> scrollListeners = new ArrayList<>(); + private final List scrollListeners = new ArrayList<>(); private final List> keyPressListeners = new ArrayList<>(); private final List> keyReleaseListeners = new ArrayList<>(); private final List> charTypedListeners = new ArrayList<>(); @@ -46,7 +47,7 @@ public GuiEventProvider onMouseMove(BiConsumer listener) { return this; } - public GuiEventProvider onScroll(TriConsumer listener) { + public GuiEventProvider onScroll(ScrollListener listener) { scrollListeners.add(listener); return this; } @@ -89,11 +90,11 @@ public void mouseMoved(double mouseX, double mouseY) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double scroll, boolean consumed) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY, boolean consumed) { if (ignoreConsumed || !consumed) { - scrollListeners.forEach(e -> e.accept(mouseX, mouseY, scroll)); + scrollListeners.forEach(e -> e.onScrolled(mouseX, mouseY, scrollX, scrollY)); } - return super.mouseScrolled(mouseX, mouseY, scroll, consumed); + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY, consumed); } @Override @@ -119,4 +120,9 @@ public boolean charTyped(char character, int modifiers, boolean consumed) { } return super.charTyped(character, modifiers, consumed); } + + public interface ScrollListener { + + void onScrolled(double mouseX, double mouseY, double scrollX, double scrollY); + } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java index 12ce2600..f880bf02 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java @@ -4,7 +4,7 @@ import codechicken.lib.gui.modular.lib.Constraints; import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import codechicken.lib.gui.modular.sprite.GuiTextures; import codechicken.lib.gui.modular.sprite.Material; import codechicken.lib.util.FormatUtil; import net.minecraft.client.Minecraft; @@ -15,8 +15,8 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -36,8 +36,9 @@ * Created by brandon3055 on 11/09/2023 */ public class GuiFluidTank extends GuiElement implements BackgroundRender { + //TODO make a better texture, This feels a little too.. cluttered. - public static final Material DEFAULT_WINDOW = CCGuiTextures.getUncached("widgets/tank_window"); + public static final Material DEFAULT_WINDOW = GuiTextures.CCL.getUncached("widgets/tank_window"); private int gaugeColour = 0xFF909090; private boolean drawGauge = true; @@ -170,12 +171,12 @@ private double computeGaugeSpacing() { double ySize = ySize(); double capacity = getCapacity(); if (ySize / (capacity / 100D) > 3) return ySize / (capacity / 100D); - else if (ySize / (capacity / 500D) > 3) return ySize / (capacity / 500D); - else if (ySize / (capacity / 1000D) > 3) return ySize / (capacity / 1000D); - else if (ySize / (capacity / 5000D) > 3) return ySize / (capacity / 5000D); - else if (ySize / (capacity / 10000D) > 3) return ySize / (capacity / 10000D); - else if (ySize / (capacity / 50000D) > 3) return ySize / (capacity / 50000D); - else if (ySize / (capacity / 100000D) > 3) return ySize / (capacity / 100000D); + if (ySize / (capacity / 500D) > 3) return ySize / (capacity / 500D); + if (ySize / (capacity / 1000D) > 3) return ySize / (capacity / 1000D); + if (ySize / (capacity / 5000D) > 3) return ySize / (capacity / 5000D); + if (ySize / (capacity / 10000D) > 3) return ySize / (capacity / 10000D); + if (ySize / (capacity / 50000D) > 3) return ySize / (capacity / 50000D); + if (ySize / (capacity / 100000D) > 3) return ySize / (capacity / 100000D); return 0; } @@ -248,5 +249,5 @@ public static TextureAtlasSprite getStillTexture(Fluid fluid) { return Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(texture); } - public record FluidTank(GuiRectangle container, GuiFluidTank tank) {} + public record FluidTank(GuiRectangle container, GuiFluidTank tank) { } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java index 2157ccf8..23f24d46 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java @@ -253,10 +253,10 @@ private void handleDrag(double mouseX, double mouseY) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { if (isMouseOver() || (scrollableElement != null && scrollableElement.isMouseOver())) { if (!state.canScroll(axis)) return false; - state.setPos(MathHelper.clip(state.getPos() + (state.scrollSpeed() * -scroll), 0, 1)); + state.setPos(MathHelper.clip(state.getPos() + (state.scrollSpeed() * -scrollX), 0, 1)); return true; } return false; diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java index 4fb97fdb..93384352 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -8,7 +8,7 @@ import codechicken.lib.gui.modular.lib.geometry.GeoParam; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.gui.modular.lib.geometry.Position; -import codechicken.lib.gui.modular.sprite.CCGuiTextures; +import codechicken.lib.gui.modular.sprite.GuiTextures; import codechicken.lib.gui.modular.sprite.Material; import net.covers1624.quack.collection.FastStream; import net.minecraft.world.inventory.Slot; @@ -41,7 +41,7 @@ public class GuiSlots extends GuiElement implements BackgroundRender { private final SlotGroup slots; private final ContainerScreenAccess screenAccess; - private Function slotTexture = slot -> CCGuiTextures.getUncached("widgets/slot"); + private Function slotTexture = slot -> GuiTextures.CCL.getUncached("widgets/slot"); private Function slotIcons = slot -> null; private Function highlightColour = slot -> 0x80ffffff; private TriConsumer slotOverlay = null; diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java index d4edcbe1..85eb7502 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java @@ -1,7 +1,7 @@ package codechicken.lib.gui.modular.lib; -import com.google.common.collect.Lists; import codechicken.lib.gui.modular.elements.GuiElement; +import com.google.common.collect.Lists; import java.util.List; @@ -121,12 +121,13 @@ default boolean mouseReleased(double mouseX, double mouseY, int button, boolean *

* Note: You do not need to call super when overriding this interface method. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param scroll Scroll direction and amount + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scrollX Scroll direction and amount + * @param scrollY Scroll direction and amount * @return true to consume event. */ - default boolean mouseScrolled(double mouseX, double mouseY, double scroll) { + default boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { return false; } @@ -138,17 +139,18 @@ default boolean mouseScrolled(double mouseX, double mouseY, double scroll) { * * @param mouseX Mouse X position * @param mouseY Mouse Y position - * @param scroll Scroll direction and amount + * @param scrollX Scroll direction and amount + * @param scrollY Scroll direction and amount * @param consumed Will be true if this action has already been consumed. * @return true if this event has been consumed. */ - default boolean mouseScrolled(double mouseX, double mouseY, double scroll, boolean consumed) { + default boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY, boolean consumed) { for (GuiElement child : Lists.reverse(getChildren())) { if (child.isEnabled()) { - consumed |= child.mouseScrolled(mouseX, mouseY, scroll, consumed); + consumed |= child.mouseScrolled(mouseX, mouseY, scrollX, scrollY, consumed); } } - return consumed || mouseScrolled(mouseX, mouseY, scroll) || blockMouseEvents(); + return consumed || mouseScrolled(mouseX, mouseY, scrollX, scrollY) || blockMouseEvents(); } /** @@ -269,4 +271,4 @@ default boolean charTyped(char character, int modifiers, boolean consumed) { return consumed || charTyped(character, modifiers); } -} \ No newline at end of file +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java index bcae9359..ce117c56 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java @@ -42,9 +42,10 @@ import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.client.event.RenderTooltipEvent; -import net.minecraftforge.common.MinecraftForge; +import net.neoforged.neoforge.client.ClientHooks; +import net.neoforged.neoforge.client.ItemDecoratorHandler; +import net.neoforged.neoforge.client.event.RenderTooltipEvent; +import net.neoforged.neoforge.common.NeoForge; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.joml.Vector2ic; @@ -63,6 +64,7 @@ * Created by brandon3055 on 29/06/2023 */ public class GuiRender { + public static final RenderType SOLID = RenderType.gui(); //Used for things like events that require the vanilla GuiGraphics @@ -330,8 +332,9 @@ private void borderFillInternal(RenderType type, double xMin, double yMin, doubl fill(type, xMin, yMin + borderWidth, xMin + borderWidth, yMax - borderWidth, borderColour); //Left fill(type, xMin, yMax - borderWidth, xMax, yMax, borderColour); //Bottom fill(type, xMax - borderWidth, yMin + borderWidth, xMax, yMax - borderWidth, borderColour); //Right - if (fillColour != 0) //No point rendering fill if there is no fill colour + if (fillColour != 0) { //No point rendering fill if there is no fill colour fill(type, xMin + borderWidth, yMin + borderWidth, xMax - borderWidth, yMax - borderWidth, fillColour); //Fill + } } /** @@ -418,8 +421,9 @@ public void shadedFillInternal(RenderType type, double xMin, double yMin, double fill(type, xMax - borderWidth, yMin, xMax, yMin + borderWidth, cornerMixColour); //Top Right Corner fill(type, xMin, yMax - borderWidth, xMin + borderWidth, yMax, cornerMixColour); //Bottom Left Corner - if (fillColour != 0) //No point rendering fill if there is no fill colour + if (fillColour != 0) { //No point rendering fill if there is no fill colour fill(type, xMin + borderWidth, yMin + borderWidth, xMax - borderWidth, yMax - borderWidth, fillColour); //Fill + } } //=== Generic Backgrounds ===// @@ -634,8 +638,8 @@ public void sprite(RenderType type, double xMin, double yMin, double xMax, doubl * @param rotation Rotates sprite clockwise in 90 degree steps. */ public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - float[] u = {sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0()}; - float[] v = {sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0()}; + float[] u = { sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0() }; + float[] v = { sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0() }; VertexConsumer buffer = buffers().getBuffer(type); Matrix4f mat = pose.last().pose(); buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B @@ -813,9 +817,11 @@ public void tileSprite(RenderType type, double xMin, double yMin, double xMax, d double vWidth = sectionHeight / textureHeight; partialSprite(type, xPos, yPos, xPos + sectionWidth, yPos + sectionHeight, sprite, 0, 0, (float) uWidth, (float) vWidth, red, green, blue, alpha); yPos += textureHeight; - } while (yPos < yMax); + } + while (yPos < yMax); xPos += textureWidth; - } while (xPos < xMax); + } + while (xPos < xMax); }; if (batchDraw) { draw.run(); @@ -995,8 +1001,8 @@ public void tex(Material material, double xMin, double yMin, double xMax, double public void tex(Material material, double xMin, double yMin, double xMax, double yMax, int rotation, float red, float green, float blue, float alpha) { TextureAtlasSprite sprite = material.sprite(); VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); - float[] u = {sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0()}; - float[] v = {sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0()}; + float[] u = { sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0() }; + float[] v = { sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0() }; Matrix4f mat = pose.last().pose(); buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).endVertex(); //R-T @@ -1128,14 +1134,14 @@ private void dynamicTexInternal(Material material, int xPos, int yPos, int xSize } } - private void bufferDynamic(VertexConsumer builder, Matrix4f mat, TextureAtlasSprite tex, int x, int y, double textureX, double textureY, int width, int height, float red, float green, float blue, float alpha) { + private void bufferDynamic(VertexConsumer builder, Matrix4f mat, TextureAtlasSprite tex, int x, int y, float textureX, float textureY, int width, int height, float red, float green, float blue, float alpha) { int w = tex.contents().width(); int h = tex.contents().height(); //@formatter:off - builder.vertex(mat, x, y + height, 0).color(red, green, blue, alpha).uv(tex.getU((textureX / w) * 16D), tex.getV(((textureY + height) / h) * 16)).endVertex(); - builder.vertex(mat, x + width, y + height, 0).color(red, green, blue, alpha).uv(tex.getU(((textureX + width) / w) * 16), tex.getV(((textureY + height) / h) * 16)).endVertex(); - builder.vertex(mat, x + width, y, 0).color(red, green, blue, alpha).uv(tex.getU(((textureX + width) / w) * 16), tex.getV(((textureY) / h) * 16)).endVertex(); - builder.vertex(mat, x, y, 0).color(red, green, blue, alpha).uv(tex.getU((textureX / w) * 16), tex.getV(((textureY) / h) * 16)).endVertex(); + builder.vertex(mat, x, y + height, 0).color(red, green, blue, alpha).uv(tex.getU(textureX / w), tex.getV((textureY + height) / h)).endVertex(); + builder.vertex(mat, x + width, y + height, 0).color(red, green, blue, alpha).uv(tex.getU((textureX + width) / w), tex.getV((textureY + height) / h)).endVertex(); + builder.vertex(mat, x + width, y, 0).color(red, green, blue, alpha).uv(tex.getU((textureX + width) / w), tex.getV((textureY / h))).endVertex(); + builder.vertex(mat, x, y, 0).color(red, green, blue, alpha).uv(tex.getU(textureX / w), tex.getV((textureY / h))).endVertex(); //@formatter:on } @@ -1293,7 +1299,7 @@ public void toolTipWithImage(List tooltip, Optional } public void toolTipWithImage(List tooltip, Optional tooltipImage, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, tooltip, tooltipImage, (int) mouseX, guiWidth(), guiHeight(), font()); + List list = ClientHooks.gatherTooltipComponents(tooltipStack, tooltip, tooltipImage, (int) mouseX, guiWidth(), guiHeight(), font()); this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); } @@ -1302,12 +1308,12 @@ public void renderTooltip(Component message, double mouseX, double mouseY) { } public void renderTooltip(Component message, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, List.of(message), Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); + List list = ClientHooks.gatherTooltipComponents(tooltipStack, List.of(message), Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); } public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); + List list = ClientHooks.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); } @@ -1321,7 +1327,7 @@ public void componentTooltip(List tooltips, double mous public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ItemStack stack) { this.tooltipStack = stack; - List list = ForgeHooksClient.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); + List list = ClientHooks.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); this.tooltipStack = ItemStack.EMPTY; } @@ -1349,10 +1355,9 @@ public void renderTooltip(List tooltips, ClientTooltipPos private void renderTooltipInternal(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ClientTooltipPositioner positioner) { if (!tooltips.isEmpty()) { - RenderTooltipEvent.Pre event = ForgeHooksClient.onRenderTooltipPre(tooltipStack, guiGraphicsWrapper(), (int) mouseX, (int) mouseY, guiWidth(), guiHeight(), tooltips, font(), positioner); + RenderTooltipEvent.Pre event = ClientHooks.onRenderTooltipPre(tooltipStack, guiGraphicsWrapper(), (int) mouseX, (int) mouseY, guiWidth(), guiHeight(), tooltips, font(), positioner); if (event.isCanceled()) return; - int width = 0; int height = tooltips.size() == 1 ? -2 : 0; for (ClientTooltipComponent line : tooltips) { @@ -1366,7 +1371,7 @@ private void renderTooltipInternal(List tooltips, double RenderTooltipEvent.Color colorEvent = new RenderTooltipEvent.Color(tooltipStack, guiGraphicsWrapper(), (int) mouseX, (int) mouseY, font(), backgroundTop, borderTop, borderBottom, tooltips); colorEvent.setBackgroundEnd(backgroundBottom); - MinecraftForge.EVENT_BUS.post(colorEvent); + NeoForge.EVENT_BUS.post(colorEvent); toolTipBackground(xPos - 3, yPos - 3, width + 6, height + 6, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd(), false); int linePos = yPos; @@ -1572,15 +1577,13 @@ public void renderItemDecorations(ItemStack stack, double x, double y, double si pose.popPose(); if (size == 16) { - net.minecraftforge.client.ItemDecoratorHandler.of(stack).render(guiGraphicsWrapper(), font(), stack, (int) x, (int) y); + ItemDecoratorHandler.of(stack).render(guiGraphicsWrapper(), font(), stack, (int) x, (int) y); } } } - //=== Entity? ===// - //=== Render Utils ===// public void pushScissorRect(Rectangle rectangle) { @@ -1708,6 +1711,7 @@ public static RenderType texColType(ResourceLocation location) { * This exists to allow thing like the Tooltip events to still function correctly, hopefully without exploding... */ public static class RenderWrapper extends GuiGraphics { + private final GuiRender wrapped; private RenderWrapper(GuiRender wrapped) { @@ -1724,15 +1728,5 @@ public void drawManaged(Runnable runnable) { public void flush() { wrapped.flush(); } - - @Override - public void flushIfManaged() { - wrapped.flushIfBatched(); - } - - @Override - public void flushIfUnmanaged() { - wrapped.flushIfUnBatched(); - } } } diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java b/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java deleted file mode 100644 index a59ec2bf..00000000 --- a/src/main/java/codechicken/lib/gui/modular/sprite/CCGuiTextures.java +++ /dev/null @@ -1,60 +0,0 @@ -package codechicken.lib.gui.modular.sprite; - -import codechicken.lib.CodeChickenLib; -import net.minecraft.resources.ResourceLocation; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Supplier; - -/** - * Gui texture handler implementation. - * This sets up a custom atlas that will be populated with all textures in "modid:textures/gui/" - * To use your own textures you can just create a carbon copy of this class with that uses your own modid. - *

- * Created by brandon3055 on 21/10/2023 - */ -// TODO 1.20.4, use GuiTextures instance. -public class CCGuiTextures { - private static final ModAtlasHolder ATLAS_HOLDER = new ModAtlasHolder(CodeChickenLib.MOD_ID, "textures/atlas/gui.png", "gui"); - private static final Map MATERIAL_CACHE = new HashMap<>(); - - /** - * The returned AtlasLoader needs to be registered as a resource reload listener using the appropriate NeoForge / Fabric event. - */ - public static ModAtlasHolder getAtlasHolder() { - return ATLAS_HOLDER; - } - - /** - * Returns a cached Material for the specified gui texture. - * Warning: Do not use this if you intend to use the material with multiple render types. - * The material will cache the first render type it is used with. - * Instead use {@link #getUncached(String)} - * - * @param texture The texture path relative to "modid:gui/" - */ - public static Material get(String texture) { - return MATERIAL_CACHE.computeIfAbsent(CodeChickenLib.MOD_ID + ":" + texture, e -> getUncached(texture)); - } - - public static Material get(Supplier texture) { - return get(texture.get()); - } - - public static Supplier getter(Supplier texture) { - return () -> get(texture.get()); - } - - /** - * Use this to retrieve a new uncached material for the specified gui texture. - * Feel free to hold onto the returned material. - * Storing it somewhere is more efficient than recreating it every render frame. - * - * @param texture The texture path relative to "modid:gui/" - * @return A new Material for the specified gui texture. - */ - public static Material getUncached(String texture) { - return new Material(ATLAS_HOLDER.atlasLocation(), new ResourceLocation(CodeChickenLib.MOD_ID, "gui/" + texture), ATLAS_HOLDER::getSprite); - } -} diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java b/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java index a21cef63..8b1fa0b5 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java @@ -1,15 +1,16 @@ package codechicken.lib.gui.modular.sprite; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; -import net.minecraftforge.data.loading.DatagenModLoader; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; +import net.neoforged.neoforge.data.loading.DatagenModLoader; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; +import static codechicken.lib.CodeChickenLib.MOD_ID; import static java.util.Objects.requireNonNull; /** @@ -20,6 +21,8 @@ */ public class GuiTextures { + public static final GuiTextures CCL = new GuiTextures(MOD_ID); + private final String modId; private final @Nullable ModAtlasHolder atlasHolder; private final Map materialCache = new HashMap<>(); @@ -36,10 +39,10 @@ public GuiTextures(String modId) { /** * Called to initialize the {@link GuiTextures} helper * - * @param bus Your mod event bus. + * @param modBus Your mod event bus. */ - public void init(IEventBus bus) { - bus.addListener(this::onRegisterReloadListeners); + public void init(IEventBus modBus) { + modBus.addListener(this::onRegisterReloadListeners); } private void onRegisterReloadListeners(RegisterClientReloadListenersEvent event) { diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/Material.java b/src/main/java/codechicken/lib/gui/modular/sprite/Material.java index 888b45b3..741c7999 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/Material.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/Material.java @@ -101,26 +101,4 @@ public static Material fromSprite(@Nullable TextureAtlasSprite sprite) { if (sprite == null) return null; return new Material(sprite.atlasLocation(), sprite.contents().name(), e -> Minecraft.getInstance().getTextureAtlas(sprite.atlasLocation()).apply(e)); } - - public static Material fromRawTexture(ResourceLocation texture) { - return new Material(texture, texture, FullSprite::new); - } - - private static class FullSprite extends TextureAtlasSprite { - private FullSprite(ResourceLocation location) { - super(location, new SpriteContents(location, new FrameSize(1, 1), new NativeImage(1, 1, false), AnimationMetadataSection.EMPTY), 1, 1, 0, 0); - } - - @Override - public float getU(double u) - { - return (float) u / 16; - } - - @Override - public float getV(double v) - { - return (float) v / 16; - } - } } diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java index d8260d6b..3f2a4cd1 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java @@ -44,11 +44,6 @@ public ModAtlasHolder(String modid, String atlasLocation, String atlasInfoLocati this.atlasLocation = new ResourceLocation(modid, atlasLocation); this.textureAtlas = new TextureAtlas(this.atlasLocation); this.modid = modid; - // TODO remove in 1.20.4 - TextureManager textureManager = Minecraft.getInstance().getTextureManager(); - if (textureManager != null) { - textureManager.register(this.textureAtlas.location(), this.textureAtlas); - } } public void init() { diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java index 5190476d..f16dfd95 100644 --- a/src/main/java/codechicken/lib/internal/ClientInit.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -4,22 +4,22 @@ import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigSyncManager; import codechicken.lib.gui.modular.lib.CursorHelper; -import codechicken.lib.gui.modular.sprite.CCGuiTextures; -import codechicken.lib.model.CompositeItemModel; +import codechicken.lib.gui.modular.sprite.GuiTextures; import codechicken.lib.model.ClassModelLoader; +import codechicken.lib.model.CompositeItemModel; import codechicken.lib.render.CCRenderEventHandler; import codechicken.lib.render.block.BlockRenderingRegistry; import net.covers1624.quack.util.CrashLock; -import net.minecraft.client.Minecraft; -import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import net.minecraftforge.client.event.ClientPlayerNetworkEvent; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; +import net.neoforged.neoforge.client.event.ModelEvent; +import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; +import net.neoforged.neoforge.common.NeoForge; + +import static codechicken.lib.CodeChickenLib.MOD_ID; /** * Created by covers1624 on 8/9/23. @@ -31,18 +31,19 @@ public class ClientInit { public static boolean catchBlockRenderExceptions; public static boolean messagePlayerOnRenderExceptionCaught; - public static void init() { + public static void init(IEventBus modBus) { LOCK.lock(); - IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); loadClientConfig(); CCRenderEventHandler.init(); + HighlightHandler.init(); + ExceptionMessageEventHandler.init(); - MinecraftForge.EVENT_BUS.addListener(ClientInit::onClientDisconnected); + GuiTextures.CCL.init(modBus); - bus.addListener(ClientInit::onClientSetup); - bus.addListener(ClientInit::onRegisterGeometryLoaders); - bus.addListener(ClientInit::onResourceReload); + modBus.addListener(ClientInit::onClientSetup); + modBus.addListener(ClientInit::onRegisterGeometryLoaders); + modBus.addListener(ClientInit::onResourceReload); } private static void onClientSetup(FMLClientSetupEvent event) { @@ -73,17 +74,12 @@ private static void loadClientConfig() { clientTag.save(); } - private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut event) { - ConfigSyncManager.onClientDisconnected(); - } - private static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register("item_composite", new CompositeItemModel()); - event.register("class", new ClassModelLoader()); + event.register(new ResourceLocation(MOD_ID, "item_composite"), new CompositeItemModel()); + event.register(new ResourceLocation(MOD_ID, "class"), new ClassModelLoader()); } private static void onResourceReload(RegisterClientReloadListenersEvent event) { - event.registerReloadListener(CCGuiTextures.getAtlasHolder()); event.registerReloadListener((ResourceManagerReloadListener) e -> CursorHelper.onResourceReload()); } } diff --git a/src/main/java/codechicken/lib/internal/DataGenerators.java b/src/main/java/codechicken/lib/internal/DataGenerators.java index 89cad861..67016d4d 100644 --- a/src/main/java/codechicken/lib/internal/DataGenerators.java +++ b/src/main/java/codechicken/lib/internal/DataGenerators.java @@ -2,6 +2,7 @@ import codechicken.lib.datagen.LanguageProvider; import codechicken.lib.util.CCLTags; +import net.covers1624.quack.util.CrashLock; import net.minecraft.core.HolderLookup; import net.minecraft.data.DataGenerator; import net.minecraft.data.PackOutput; @@ -9,11 +10,11 @@ import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraftforge.common.data.BlockTagsProvider; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.data.event.GatherDataEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.data.BlockTagsProvider; +import net.neoforged.neoforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.data.event.GatherDataEvent; import java.util.concurrent.CompletableFuture; @@ -22,11 +23,16 @@ /** * Created by covers1624 on 13/12/20. */ -@Mod.EventBusSubscriber (modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD) public class DataGenerators { - @SubscribeEvent - public static void gatherDataGenerators(GatherDataEvent event) { + private static final CrashLock LOCK = new CrashLock("Already Initialized"); + + public static void init(IEventBus modBus) { + LOCK.lock(); + modBus.addListener(DataGenerators::gatherDataGenerators); + } + + private static void gatherDataGenerators(GatherDataEvent event) { DataGenerator gen = event.getGenerator(); PackOutput output = gen.getPackOutput(); CompletableFuture lookupProvider = event.getLookupProvider(); diff --git a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java b/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java index 9048b023..19bee76d 100644 --- a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java +++ b/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java @@ -1,10 +1,8 @@ package codechicken.lib.internal; -import codechicken.lib.CodeChickenLib; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.covers1624.quack.util.CrashLock; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.TickEvent; import java.util.HashSet; import java.util.Set; @@ -13,14 +11,19 @@ /** * Created by covers1624 on 25/07/18. */ -@EventBusSubscriber (value = Dist.CLIENT, modid = CodeChickenLib.MOD_ID) public class ExceptionMessageEventHandler { + private static final CrashLock LOCK = new CrashLock("Already Initialized"); + public static Set exceptionMessageCache = new HashSet<>(); private static long lastExceptionClear; - @SubscribeEvent - public static void clientTick(TickEvent.ClientTickEvent event) { + public static void init() { + LOCK.lock(); + NeoForge.EVENT_BUS.addListener(ExceptionMessageEventHandler::clientTick); + } + + private static void clientTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.END) { //Clear the known exceptions every 5 seconds. long time = System.nanoTime(); diff --git a/src/main/java/codechicken/lib/internal/HighlightHandler.java b/src/main/java/codechicken/lib/internal/HighlightHandler.java index aada1ba9..c269635f 100644 --- a/src/main/java/codechicken/lib/internal/HighlightHandler.java +++ b/src/main/java/codechicken/lib/internal/HighlightHandler.java @@ -1,6 +1,5 @@ package codechicken.lib.internal; -import codechicken.lib.CodeChickenLib; import codechicken.lib.colour.EnumColour; import codechicken.lib.render.RenderUtils; import codechicken.lib.render.buffer.TransformingVertexConsumer; @@ -9,16 +8,15 @@ import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexFormat; +import net.covers1624.quack.util.CrashLock; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RenderLevelStageEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.neoforge.client.event.RenderLevelStageEvent; +import net.neoforged.neoforge.common.NeoForge; import org.jetbrains.annotations.Nullable; import static net.minecraft.client.renderer.RenderStateShard.*; @@ -26,9 +24,10 @@ /** * Created by covers1624 on 9/06/18. */ -@Mod.EventBusSubscriber (value = Dist.CLIENT, modid = CodeChickenLib.MOD_ID) public class HighlightHandler { + private static final CrashLock LOCK = new CrashLock("Already Initialized"); + private static final Cuboid6 BOX = Cuboid6.full.copy().expand(0.02); private static final float[] RED = EnumColour.RED.getColour(128).packArray(); @@ -58,8 +57,12 @@ public void setupRenderState() { .createCompositeState(false) ); - @SubscribeEvent - public static void renderLevelLast(RenderLevelStageEvent event) { + public static void init() { + LOCK.lock(); + NeoForge.EVENT_BUS.addListener(HighlightHandler::renderLevelLast); + } + + private static void renderLevelLast(RenderLevelStageEvent event) { if (event.getStage() != RenderLevelStageEvent.Stage.AFTER_PARTICLES) return; if (highlight != null) { diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 8aef2588..972981b3 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -32,6 +32,8 @@ import java.util.function.Consumer; import java.util.function.Supplier; +import static java.util.Objects.requireNonNull; + /** * Mostly internal, intended for developer use. *

@@ -289,7 +291,7 @@ protected void serialize() throws IOException { int ret = runFfmpeg( List.of( - FFMPEG_BINARY.get(), + requireNonNull(FFMPEG_BINARY.get()), "-y", "-framerate", String.valueOf(fps), "-i", tempDir.toAbsolutePath() + "/%d.png", diff --git a/src/main/java/codechicken/lib/world/TileChunkLoadHook.java b/src/main/java/codechicken/lib/internal/TileChunkLoadHook.java similarity index 64% rename from src/main/java/codechicken/lib/world/TileChunkLoadHook.java rename to src/main/java/codechicken/lib/internal/TileChunkLoadHook.java index beef0c80..87ad09df 100644 --- a/src/main/java/codechicken/lib/world/TileChunkLoadHook.java +++ b/src/main/java/codechicken/lib/internal/TileChunkLoadHook.java @@ -1,28 +1,25 @@ -package codechicken.lib.world; +package codechicken.lib.internal; +import codechicken.lib.world.IChunkLoadTile; +import net.covers1624.quack.util.CrashLock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.level.ChunkEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.level.ChunkEvent; public class TileChunkLoadHook { - private static boolean init; + private static final CrashLock LOCK = new CrashLock("Already Initialized."); public static void init() { - if (init) { - return; - } - init = true; + LOCK.lock(); - MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook()); + NeoForge.EVENT_BUS.addListener(TileChunkLoadHook::onChunkLoad); } - @SubscribeEvent - public void onChunkLoad(ChunkEvent.Load event) { + private static void onChunkLoad(ChunkEvent.Load event) { ChunkAccess iChunk = event.getChunk(); LevelChunk chunk; if (iChunk instanceof LevelChunk) { diff --git a/src/main/java/codechicken/lib/internal/command/CCLCommands.java b/src/main/java/codechicken/lib/internal/command/CCLCommands.java index 65e1a9f1..ea5eec69 100644 --- a/src/main/java/codechicken/lib/internal/command/CCLCommands.java +++ b/src/main/java/codechicken/lib/internal/command/CCLCommands.java @@ -11,9 +11,9 @@ import net.covers1624.quack.util.CrashLock; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; -import net.minecraftforge.client.event.RegisterClientCommandsEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.RegisterCommandsEvent; +import net.neoforged.neoforge.client.event.RegisterClientCommandsEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.RegisterCommandsEvent; /** * Created by covers1624 on 17/9/20. @@ -25,8 +25,8 @@ public class CCLCommands { public static void init() { LOCK.lock(); - MinecraftForge.EVENT_BUS.addListener(CCLCommands::registerServerCommands); - MinecraftForge.EVENT_BUS.addListener(CCLCommands::registerClientCommands); + NeoForge.EVENT_BUS.addListener(CCLCommands::registerServerCommands); + NeoForge.EVENT_BUS.addListener(CCLCommands::registerClientCommands); } private static void registerServerCommands(RegisterCommandsEvent event) { @@ -44,5 +44,4 @@ private static void registerClientCommands(RegisterClientCommandsEvent event) { ItemInfoCommand.register(dispatcher); RenderItemToFileCommand.register(dispatcher); } - } diff --git a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java index d1ba89b3..81688135 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java @@ -7,12 +7,12 @@ import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.ResourceArgument; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.EntityType; -import net.minecraftforge.registries.ForgeRegistries; import java.util.ArrayList; import java.util.Comparator; @@ -65,11 +65,11 @@ private static int countAllEntities(CommandContext ctx, Pred int total = 0; for (EntityType type : order) { int count = counts.getInt(type); - String name = ForgeRegistries.ENTITY_TYPES.getKey(type).toString(); + String name = BuiltInRegistries.ENTITY_TYPE.getKey(type).toString(); ctx.getSource().sendSuccess(() -> Component.literal(GREEN + name + RESET + " x " + AQUA + count), false); total += count; } - if (order.size() == 0) { + if (order.isEmpty()) { ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.count.fail"), false); } else if (order.size() > 1) { int finalTotal = total; diff --git a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java index fd2df032..fb0b8619 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java @@ -8,6 +8,7 @@ import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.ResourceArgument; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerChunkCache; @@ -15,9 +16,8 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.monster.Enemy; -import net.minecraftforge.registries.ForgeRegistries; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -77,10 +77,11 @@ private static int killEntities(CommandContext ctx, @Nullabl ServerChunkCache provider = world.getChunkSource(); Object2IntMap> counts = new Object2IntOpenHashMap<>(); counts.defaultReturnValue(0); - FastStream entities = FastStream.of(world.getEntities().getAll()) + List entities = FastStream.of(world.getEntities().getAll()) .filter(Objects::nonNull) .filter(predicate) - .filter(e -> provider.hasChunk(floor(e.getX()) >> 4, floor(e.getZ()) >> 4)); + .filter(e -> provider.hasChunk(floor(e.getX()) >> 4, floor(e.getZ()) >> 4)) + .toList(); for (Entity e : entities) { killFunc.accept(e); @@ -94,11 +95,11 @@ private static int killEntities(CommandContext ctx, @Nullabl int total = 0; for (EntityType t : order) { int count = counts.getInt(t); - String name = ForgeRegistries.ENTITY_TYPES.getKey(t).toString(); + String name = BuiltInRegistries.ENTITY_TYPE.getKey(t).toString(); ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.success.line", RED + name + RESET + " x " + AQUA + count), false); total += count; } - if (order.size() == 0) { + if (order.isEmpty()) { ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.fail"), false); } else if (order.size() > 1) { int finalTotal = total; diff --git a/src/main/java/codechicken/lib/internal/command/admin/package-info.java b/src/main/java/codechicken/lib/internal/command/admin/package-info.java new file mode 100644 index 00000000..0424575b --- /dev/null +++ b/src/main/java/codechicken/lib/internal/command/admin/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.command.admin; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java index 94b1880d..6fe5213e 100644 --- a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java @@ -10,6 +10,7 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.coordinates.BlockPosArgument; import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.block.Block; @@ -17,9 +18,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; -import net.minecraftforge.registries.ForgeRegistries; -import static codechicken.lib.util.LambdaUtils.tryOrNull; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal; @@ -120,13 +119,13 @@ private static int dumpInfo(CommandContext ctx) { BlockEntity tile = level.getBlockEntity(pos); StringBuilder builder = new StringBuilder("\nBlock info:\n"); builder.append(" BlockPos: ").append(String.format("x:%s, y:%s, z:%s", pos.getX(), pos.getY(), pos.getZ())).append("\n"); - builder.append(" Block Class: ").append(tryOrNull(() -> block.getClass())).append("\n"); - builder.append(" Registry Name: ").append(tryOrNull(() -> ForgeRegistries.BLOCKS.getKey(block))).append("\n"); + builder.append(" Block Class: ").append(block.getClass()).append("\n"); + builder.append(" Registry Name: ").append(BuiltInRegistries.BLOCK.getKey(block)).append("\n"); builder.append(" State: ").append(state).append("\n"); builder.append("Tile at position\n"); - builder.append(" Tile Class: ").append(tryOrNull(() -> tile.getClass())).append("\n"); - builder.append(" Tile Id: ").append(tryOrNull(() -> ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(tile.getType()))).append("\n"); - builder.append(" Tile NBT: ").append(tryOrNull(() -> tile.saveWithoutMetadata())).append("\n"); + builder.append(" Tile Class: ").append(tile != null ? tile.getClass() : null).append("\n"); + builder.append(" Tile Id: ").append(tile != null ? BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(tile.getType()) : null).append("\n"); + builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata() : null).append("\n"); source.sendSuccess(() -> Component.literal(builder.toString()), false); return 0; diff --git a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java index e05bffbf..67f6b06e 100644 --- a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java @@ -3,11 +3,11 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.registries.ForgeRegistries; import static net.minecraft.commands.Commands.literal; @@ -31,7 +31,7 @@ private static int execute(CommandContext command) { if (stack.isEmpty()) return 0; String tag = stack.hasTag() ? stack.getTag().toString() : "Item has no NBT."; - ctx.sendSuccess(() -> Component.literal("Registry Name: " + ForgeRegistries.ITEMS.getKey(stack.getItem())), false); + ctx.sendSuccess(() -> Component.literal("Registry Name: " + BuiltInRegistries.ITEM.getKey(stack.getItem())), false); ctx.sendSuccess(() -> Component.literal("NBT : " + tag), false); return 0; } diff --git a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java index 9a9a747b..9102f0fe 100644 --- a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java @@ -5,14 +5,16 @@ import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.commands.CommandRuntimeException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; +import static java.util.Objects.requireNonNull; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal; @@ -21,6 +23,8 @@ */ public class RenderItemToFileCommand { + private static final DynamicCommandExceptionType ERROR_INVALID = new DynamicCommandExceptionType(p_311534_ -> (Component) p_311534_); + public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ccl") .then(literal("render_held") @@ -50,7 +54,7 @@ public static void register(CommandDispatcher dispatcher) { ); } - private static int renderToFile(CommandContext ctx, int resolution) { + private static int renderToFile(CommandContext ctx, int resolution) throws CommandSyntaxException { String path = getPath(ctx); ItemStack held = getHeldItem(); @@ -59,7 +63,7 @@ private static int renderToFile(CommandContext ctx, int reso return 0; } - private static int renderAnim(CommandContext ctx, int resolution) { + private static int renderAnim(CommandContext ctx, int resolution) throws CommandSyntaxException { CommandSourceStack src = ctx.getSource(); int fps = IntegerArgumentType.getInteger(ctx, "fps"); int duration = IntegerArgumentType.getInteger(ctx, "duration"); @@ -96,30 +100,30 @@ private static int renderAnim(CommandContext ctx, int resolu return 0; } - private static String getPath(CommandContext ctx) { + private static String getPath(CommandContext ctx) throws CommandSyntaxException { String str = StringArgumentType.getString(ctx, "name"); if (str.contains("..")) { - throw new CommandRuntimeException(Component.literal("'..' is not allowed in name.")); + throw ERROR_INVALID.create(Component.literal("'..' is not allowed in name.")); } return str; } - public static int getResolution(CommandContext ctx) { + public static int getResolution(CommandContext ctx) throws CommandSyntaxException { int res = IntegerArgumentType.getInteger(ctx, "resolution"); if ((res & res - 1) != 0) { - throw new CommandRuntimeException(Component.literal("Resolution must be a power of 2. 16, 32, 64...")); + throw ERROR_INVALID.create(Component.literal("Resolution must be a power of 2. 16, 32, 64...")); } return res; } - private static ItemStack getHeldItem() { - LocalPlayer player = Minecraft.getInstance().player; + private static ItemStack getHeldItem() throws CommandSyntaxException { + LocalPlayer player = requireNonNull(Minecraft.getInstance().player); ItemStack held = player.getItemInHand(InteractionHand.MAIN_HAND); if (held.isEmpty()) { held = player.getItemInHand(InteractionHand.OFF_HAND); } if (held.isEmpty()) { - throw new CommandRuntimeException(Component.literal("You are not holding anything.")); + throw ERROR_INVALID.create(Component.literal("You are not holding anything.")); } return held; } diff --git a/src/main/java/codechicken/lib/internal/command/client/package-info.java b/src/main/java/codechicken/lib/internal/command/client/package-info.java index eefafb3f..9ec1c645 100644 --- a/src/main/java/codechicken/lib/internal/command/client/package-info.java +++ b/src/main/java/codechicken/lib/internal/command/client/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.internal.command.client; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/command/dev/package-info.java b/src/main/java/codechicken/lib/internal/command/dev/package-info.java new file mode 100644 index 00000000..228f9ba4 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/command/dev/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.command.dev; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java index 3a0bea86..8155057d 100644 --- a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java +++ b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java @@ -20,11 +20,14 @@ import java.util.Collections; import java.util.List; +import static net.covers1624.quack.util.SneakyUtils.unsafeCast; + /** * Created by brandon3055 on 31/12/2023 */ @JeiPlugin public class JEIPlugin implements IModPlugin { + private static final ResourceLocation ID = new ResourceLocation(CodeChickenLib.MOD_ID, "jei_plugin"); public JEIPlugin() { @@ -43,15 +46,17 @@ public List getGuiExtraAreas(ModularGuiContainer screen) { return FastStream.of(screen.getModularGui().getJeiExclusions()).map(e -> e.getRectangle().toRect2i()).toList(); } }); - registration.addGhostIngredientHandler(ModularGuiContainer.class, new IngredientDropHandler()); + Class> clazz = unsafeCast(ModularGuiContainer.class); + registration.addGhostIngredientHandler(clazz, new IngredientDropHandler()); } - private static class IngredientDropHandler implements IGhostIngredientHandler { + private static class IngredientDropHandler implements IGhostIngredientHandler> { + private ModularGui gui; private boolean highlight = true; @Override - public List> getTargetsTyped(ModularGuiContainer screen, ITypedIngredient ingredient, boolean doStart) { + public List> getTargetsTyped(ModularGuiContainer screen, ITypedIngredient ingredient, boolean doStart) { gui = screen.getModularGui(); gui.setJeiHighlightTime(doStart ? 60 * 20 : 3 * 20); highlight = !doStart; @@ -74,6 +79,7 @@ public boolean shouldHighlightTargets() { } private record DropTarget(GuiElement element) implements IGhostIngredientHandler.Target { + @Override public Rect2i getArea() { return element.getRectangle().toRect2i(); diff --git a/src/main/java/codechicken/lib/internal/compat/package-info.java b/src/main/java/codechicken/lib/internal/compat/package-info.java new file mode 100644 index 00000000..6de2ee23 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/compat/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.compat; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java b/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java index 6f42475b..f614a5e7 100644 --- a/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java +++ b/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java @@ -1,5 +1,6 @@ package codechicken.lib.internal.mixin; +import org.jetbrains.annotations.Nullable; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; @@ -23,9 +24,9 @@ public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { // @formatter:off @Override public void onLoad(String mixinPackage) { } - @Override public String getRefMapperConfig() { return null; } + @Nullable @Override public String getRefMapperConfig() { return null; } @Override public void acceptTargets(Set myTargets, Set otherTargets) { } - @Override public List getMixins() { return null; } + @Nullable @Override public List getMixins() { return null; } @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } // @formatter:on diff --git a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java index 0157a042..32a39bb9 100644 --- a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java +++ b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java @@ -7,7 +7,7 @@ import net.minecraft.client.resources.model.BakedModel; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.client.ForgeHooksClient; +import net.neoforged.neoforge.client.ClientHooks; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -30,8 +30,8 @@ public void onRenderItem(ItemStack stack, ItemDisplayContext context, boolean le if (modelIn instanceof IItemRenderer) { ci.cancel(); mStack.pushPose(); - //If anyone doesnt return an IItemRenderer from here, your doing it wrong. - IItemRenderer renderer = (IItemRenderer) ForgeHooksClient.handleCameraTransforms(mStack, modelIn, context, leftHand); + // If anyone doesn't return an IItemRenderer from here, your doing it wrong. + IItemRenderer renderer = (IItemRenderer) ClientHooks.handleCameraTransforms(mStack, modelIn, context, leftHand); mStack.translate(-0.5D, -0.5D, -0.5D); renderer.renderItem(stack, context, mStack, buffers, packedLight, packedOverlay); mStack.popPose(); diff --git a/src/main/java/codechicken/lib/internal/mixin/dev/package-info.java b/src/main/java/codechicken/lib/internal/mixin/dev/package-info.java new file mode 100644 index 00000000..03aa8ecf --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/dev/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.mixin.dev; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/mixin/package-info.java b/src/main/java/codechicken/lib/internal/mixin/package-info.java new file mode 100644 index 00000000..69ca6a4f --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.mixin; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java index 5655ef14..cd4b27c7 100644 --- a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java +++ b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java @@ -1,8 +1,8 @@ package codechicken.lib.internal.network; -import codechicken.lib.packet.PacketCustomChannelBuilder; +import codechicken.lib.packet.PacketCustomChannel; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.network.event.EventNetworkChannel; +import net.neoforged.bus.api.IEventBus; /** * Created by covers1624 on 28/10/19. @@ -10,7 +10,11 @@ public class CCLNetwork { public static final ResourceLocation NET_CHANNEL = new ResourceLocation("ccl:internal"); - public static EventNetworkChannel netChannel; + public static final PacketCustomChannel channel = new PacketCustomChannel(NET_CHANNEL) + .optional() + .clientConfiguration(() -> ClientConfigurationPacketHandler::new) + .client(() -> ClientPacketHandler::new) + .server(() -> ServerPacketHandler::new); //Client handled. public static final int C_ADD_LANDING_EFFECTS = 1; @@ -23,11 +27,7 @@ public class CCLNetwork { //Login handled. public static final int L_CONFIG_SYNC = 1; - public static void init() { - netChannel = PacketCustomChannelBuilder.named(NET_CHANNEL)// - .assignClientHandler(() -> ClientPacketHandler::new)// - .assignServerHandler(() -> ServerPacketHandler::new)// - .assignLoginHandler(() -> LoginPacketHandler::new)// - .build(); + public static void init(IEventBus modBus) { + channel.init(modBus); } } diff --git a/src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java new file mode 100644 index 00000000..ad1f3b0a --- /dev/null +++ b/src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java @@ -0,0 +1,21 @@ +package codechicken.lib.internal.network; + +import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.packet.ICustomPacketHandler; +import codechicken.lib.packet.PacketCustom; +import net.minecraft.client.Minecraft; + +import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; + +/** + * Created by covers1624 on 5/3/20. + */ +public class ClientConfigurationPacketHandler implements ICustomPacketHandler.IClientConfigurationPacketHandler { + + @Override + public void handlePacket(PacketCustom packet, Minecraft mc) { + switch (packet.getType()) { + case L_CONFIG_SYNC -> ConfigSyncManager.readSyncPacket(packet); + } + } +} diff --git a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java index 32bccf89..ab11a8a0 100644 --- a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java +++ b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java @@ -11,14 +11,16 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.MenuAccess; import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.registries.ForgeRegistries; import static codechicken.lib.internal.network.CCLNetwork.*; +import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 14/07/2017. @@ -26,31 +28,32 @@ public class ClientPacketHandler implements IClientPacketHandler { @Override - public void handlePacket(PacketCustom packet, Minecraft mc, ClientPacketListener handler) { + public void handlePacket(PacketCustom packet, Minecraft mc) { switch (packet.getType()) { case C_ADD_LANDING_EFFECTS -> { BlockPos pos = packet.readPos(); Vector3 vec = packet.readVector(); int numParticles = packet.readVarInt(); - BlockState state = mc.level.getBlockState(pos); + BlockState state = requireNonNull(mc.level).getBlockState(pos); CustomParticleHandler.addLandingEffects(mc.level, pos, state, vec, numParticles); } case C_OPEN_CONTAINER -> handleOpenContainer(packet, mc); - case C_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromServer(mc.player, packet); + case C_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromServer(requireNonNull(mc.player), packet); } } @SuppressWarnings ("unchecked") private void handleOpenContainer(PacketCustom packet, Minecraft mc) { - MenuType rawType = packet.readRegistryIdDirect(ForgeRegistries.MENU_TYPES); + MenuType rawType = packet.readRegistryIdDirect(BuiltInRegistries.MENU); int windowId = packet.readVarInt(); Component name = packet.readTextComponent(); if (rawType instanceof ICCLContainerType type) { MenuScreens.getScreenFactory(rawType, mc, windowId, name) .map(e -> (MenuScreens.ScreenConstructor) e) .ifPresent(screenFactory -> { - AbstractContainerMenu container = type.create(windowId, Minecraft.getInstance().player.getInventory(), packet); - Screen screen = screenFactory.create(container, mc.player.getInventory(), name); + LocalPlayer player = requireNonNull(mc.player); + AbstractContainerMenu container = type.create(windowId, player.getInventory(), packet); + Screen screen = screenFactory.create(container, player.getInventory(), name); mc.player.containerMenu = ((MenuAccess) screen).getMenu(); mc.setScreen(screen); }); diff --git a/src/main/java/codechicken/lib/internal/network/LoginPacketHandler.java b/src/main/java/codechicken/lib/internal/network/LoginPacketHandler.java deleted file mode 100644 index 93092ac6..00000000 --- a/src/main/java/codechicken/lib/internal/network/LoginPacketHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.config.ConfigSyncManager; -import codechicken.lib.packet.ICustomPacketHandler; -import codechicken.lib.packet.PacketCustom; -import net.minecraft.client.Minecraft; -import net.minecraft.network.protocol.login.ClientLoginPacketListener; -import net.minecraftforge.network.NetworkEvent; - -import java.util.function.BiConsumer; -import java.util.function.Supplier; - -import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; - -/** - * Created by covers1624 on 5/3/20. - */ -public class LoginPacketHandler implements ICustomPacketHandler.ILoginPacketHandler { - - @Override - public void gatherLoginPackets(BiConsumer> consumer) { - ConfigSyncManager.handleLogin(consumer); - } - - @Override - public void handleLoginPacket(PacketCustom packet, Minecraft mc, ClientLoginPacketListener handler, NetworkEvent.Context context) { - switch (packet.getType()) { - case L_CONFIG_SYNC -> ConfigSyncManager.readSyncPacket(packet); - } - } -} diff --git a/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java index 4edab263..ef18cc5c 100644 --- a/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java +++ b/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java @@ -14,7 +14,7 @@ public class ServerPacketHandler implements IServerPacketHandler { @Override - public void handlePacket(PacketCustom packet, ServerPlayer sender, ServerGamePacketListenerImpl handler) { + public void handlePacket(PacketCustom packet, ServerPlayer sender) { switch (packet.getType()) { case S_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromClient(sender, packet); } diff --git a/src/main/java/codechicken/lib/internal/network/package-info.java b/src/main/java/codechicken/lib/internal/network/package-info.java new file mode 100644 index 00000000..788d4aae --- /dev/null +++ b/src/main/java/codechicken/lib/internal/network/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.network; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/package-info.java b/src/main/java/codechicken/lib/internal/package-info.java index 5b874732..65183a0f 100644 --- a/src/main/java/codechicken/lib/internal/package-info.java +++ b/src/main/java/codechicken/lib/internal/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.internal; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/inventory/InventoryCopy.java b/src/main/java/codechicken/lib/inventory/InventoryCopy.java index c0767233..bd377fb0 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryCopy.java +++ b/src/main/java/codechicken/lib/inventory/InventoryCopy.java @@ -5,7 +5,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; import java.util.Objects; /** @@ -62,18 +61,15 @@ public boolean isEmpty() { } @Override - @Nonnull public ItemStack getItem(int slot) { return items[slot]; } - @Nonnull public ItemStack removeItem(int slot, int amount) { return InventoryUtils.decrStackSize(this, slot, amount); } @Override - @Nonnull public ItemStack removeItemNoUpdate(int slot) { return InventoryUtils.removeStackFromSlot(this, slot); } @@ -89,11 +85,6 @@ public boolean stillValid(Player player) { return true; } - @Override - public int getMaxStackSize() { - return 64; - } - @Override public void setChanged() { } @@ -103,14 +94,6 @@ public boolean canPlaceItem(int i, ItemStack itemstack) { return inv.canPlaceItem(i, itemstack); } - @Override - public void startOpen(Player player) { - } - - @Override - public void stopOpen(Player player) { - } - @Override public void clearContent() { } diff --git a/src/main/java/codechicken/lib/inventory/InventoryNBT.java b/src/main/java/codechicken/lib/inventory/InventoryNBT.java index 6cc341e7..caaf123d 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryNBT.java +++ b/src/main/java/codechicken/lib/inventory/InventoryNBT.java @@ -6,7 +6,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; import java.util.Arrays; import java.util.Objects; @@ -46,19 +45,16 @@ public boolean isEmpty() { } @Override - @Nonnull public ItemStack getItem(int slot) { return items[slot]; } @Override - @Nonnull public ItemStack removeItem(int slot, int amount) { return InventoryUtils.decrStackSize(this, slot, amount); } @Override - @Nonnull public ItemStack removeItemNoUpdate(int slot) { return InventoryUtils.removeStackFromSlot(this, slot); } @@ -69,11 +65,6 @@ public void setItem(int slot, ItemStack stack) { setChanged(); } - @Override - public int getMaxStackSize() { - return 64; - } - @Override public void setChanged() { writeNBT(); @@ -89,17 +80,4 @@ public void clearContent() { public boolean stillValid(Player player) { return true; } - - @Override - public void startOpen(Player player) { - } - - @Override - public void stopOpen(Player player) { - } - - @Override - public boolean canPlaceItem(int i, ItemStack itemstack) { - return true; - } } diff --git a/src/main/java/codechicken/lib/inventory/InventoryRange.java b/src/main/java/codechicken/lib/inventory/InventoryRange.java index 57a24a8e..550857c4 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryRange.java +++ b/src/main/java/codechicken/lib/inventory/InventoryRange.java @@ -4,23 +4,18 @@ import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; /** * Inventory wrapper for unified ISided/IInventory access */ public class InventoryRange { - public Container inv; - public Direction face; - public WorldlyContainer sidedInv; - public int[] slots; - - @Deprecated// Use EnumFacing version. - public InventoryRange(Container inv, int side) { - this(inv, Direction.BY_3D_DATA[side]); - } + public final Container inv; + public @Nullable final Direction face; + public @Nullable WorldlyContainer sidedInv; + public final int[] slots; public InventoryRange(Container inv, Direction side) { this.inv = inv; @@ -42,6 +37,7 @@ public InventoryRange(Container inv) { public InventoryRange(Container inv, int fslot, int lslot) { this.inv = inv; + this.face = null; slots = new int[lslot - fslot]; for (int i = 0; i < slots.length; i++) { slots[i] = fslot + i; @@ -57,11 +53,11 @@ public InventoryRange(Container inv, InventoryRange access) { } } - public boolean canInsertItem(int slot, @Nonnull ItemStack item) { + public boolean canInsertItem(int slot, ItemStack item) { return sidedInv == null ? inv.canPlaceItem(slot, item) : sidedInv.canPlaceItemThroughFace(slot, item, face); } - public boolean canExtractItem(int slot, @Nonnull ItemStack item) { + public boolean canExtractItem(int slot, ItemStack item) { return sidedInv == null ? inv.canPlaceItem(slot, item) : sidedInv.canTakeItemThroughFace(slot, item, face); } diff --git a/src/main/java/codechicken/lib/inventory/InventorySimple.java b/src/main/java/codechicken/lib/inventory/InventorySimple.java index 7689e0a9..ac866d17 100644 --- a/src/main/java/codechicken/lib/inventory/InventorySimple.java +++ b/src/main/java/codechicken/lib/inventory/InventorySimple.java @@ -5,7 +5,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; import java.util.Arrays; import java.util.Objects; @@ -64,19 +63,16 @@ public boolean isEmpty() { } @Override - @Nonnull public ItemStack getItem(int slot) { return items[slot]; } @Override - @Nonnull public ItemStack removeItem(int slot, int amount) { return InventoryUtils.decrStackSize(this, slot, amount); } @Override - @Nonnull public ItemStack removeItemNoUpdate(int slot) { return InventoryUtils.removeStackFromSlot(this, slot); } @@ -97,23 +93,10 @@ public boolean stillValid(Player player) { return true; } - @Override - public boolean canPlaceItem(int i, ItemStack itemstack) { - return true; - } - @Override public void setChanged() { } - @Override - public void startOpen(Player player) { - } - - @Override - public void stopOpen(Player player) { - } - @Override public void clearContent() { Arrays.fill(items, ItemStack.EMPTY); diff --git a/src/main/java/codechicken/lib/inventory/InventoryUtils.java b/src/main/java/codechicken/lib/inventory/InventoryUtils.java index b519f2ae..abcf9595 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryUtils.java +++ b/src/main/java/codechicken/lib/inventory/InventoryUtils.java @@ -10,16 +10,13 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - -import javax.annotation.Nonnull; +import net.neoforged.neoforge.items.IItemHandler; public class InventoryUtils { /** * Static default implementation for IInventory method */ - @Nonnull public static ItemStack decrStackSize(Container inv, int slot, int size) { ItemStack item = inv.getItem(slot); @@ -54,7 +51,7 @@ public static ItemStack removeStackFromSlot(Container inv, int slot) { /** * @return The quantity of items from addition that can be added to base */ - public static int incrStackSize(@Nonnull ItemStack base, @Nonnull ItemStack addition) { + public static int incrStackSize(ItemStack base, ItemStack addition) { if (canStack(base, addition)) { return incrStackSize(base, addition.getCount()); } @@ -65,7 +62,7 @@ public static int incrStackSize(@Nonnull ItemStack base, @Nonnull ItemStack addi /** * @return The quantity of items from addition that can be added to base */ - public static int incrStackSize(@Nonnull ItemStack base, int addition) { + public static int incrStackSize(ItemStack base, int addition) { int totalSize = base.getCount() + addition; if (totalSize <= base.getMaxStackSize()) { @@ -123,7 +120,7 @@ public static void readItemStacksFromTag(ItemStack[] items, ListTag tagList) { /** * Gets the maximum quantity of an item that can be inserted into inv */ - public static int getInsertibleQuantity(InventoryRange inv, @Nonnull ItemStack stack) { + public static int getInsertibleQuantity(InventoryRange inv, ItemStack stack) { int quantity = 0; stack = ItemUtils.copyStack(stack, Integer.MAX_VALUE); for (int slot : inv.slots) { @@ -133,7 +130,7 @@ public static int getInsertibleQuantity(InventoryRange inv, @Nonnull ItemStack s return quantity; } - public static int getInsertibleQuantity(Container inv, @Nonnull ItemStack stack) { + public static int getInsertibleQuantity(Container inv, ItemStack stack) { return getInsertibleQuantity(new InventoryRange(inv), stack); } @@ -147,7 +144,7 @@ public static int fitStackInSlot(InventoryRange inv, int slot, ItemStack stack) return Math.min(fit, stack.getCount()); } - public static int fitStackInSlot(Container inv, int slot, @Nonnull ItemStack stack) { + public static int fitStackInSlot(Container inv, int slot, ItemStack stack) { return fitStackInSlot(new InventoryRange(inv), slot, stack); } @@ -155,7 +152,7 @@ public static int fitStackInSlot(Container inv, int slot, @Nonnull ItemStack sta * @param simulate If set to true, no items will actually be inserted * @return The number of items unable to be inserted */ - public static int insertItem(InventoryRange inv, @Nonnull ItemStack stack, boolean simulate) { + public static int insertItem(InventoryRange inv, ItemStack stack, boolean simulate) { stack = stack.copy(); for (int pass = 0; pass < 2; pass++) { for (int slot : inv.slots) { @@ -188,7 +185,7 @@ public static int insertItem(InventoryRange inv, @Nonnull ItemStack stack, boole return stack.getCount(); } - public static int insertItem(Container inv, @Nonnull ItemStack stack, boolean simulate) { + public static int insertItem(Container inv, ItemStack stack, boolean simulate) { return insertItem(new InventoryRange(inv), stack, simulate); } @@ -208,7 +205,7 @@ public static ItemStack getExtractableStack(Container inv, int slot) { return getExtractableStack(new InventoryRange(inv), slot); } - public static boolean areStacksIdentical(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { + public static boolean areStacksIdentical(ItemStack stack1, ItemStack stack2) { if (stack1.isEmpty() || stack2.isEmpty()) { return stack1 == stack2; } @@ -216,7 +213,7 @@ public static boolean areStacksIdentical(@Nonnull ItemStack stack1, @Nonnull Ite return stack1.getItem() == stack2.getItem() && stack1.getDamageValue() == stack2.getDamageValue() && stack1.getCount() == stack2.getCount() && Objects.equal(stack1.getTag(), stack2.getTag()); } - public static boolean canStack(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { + public static boolean canStack(ItemStack stack1, ItemStack stack2) { return stack1.isEmpty() || stack2.isEmpty() || (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameTags(stack2, stack1)) && stack1.isStackable(); } diff --git a/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java b/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java index dd59b6e7..5d03af13 100644 --- a/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java +++ b/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java @@ -4,7 +4,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -53,19 +52,16 @@ public boolean isEmpty() { } @Override - @Nonnull public ItemStack getItem(int slot) { return inv.getItem(slotMap.get(slot)); } @Override - @Nonnull public ItemStack removeItem(int slot, int amount) { return inv.removeItem(slotMap.get(slot), amount); } @Override - @Nonnull public ItemStack removeItemNoUpdate(int slot) { return inv.removeItemNoUpdate(slotMap.get(slot)); } diff --git a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java index 05bb4697..627e5a09 100644 --- a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java +++ b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java @@ -9,9 +9,6 @@ import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import java.util.LinkedList; - public abstract class ContainerExtended extends AbstractContainerMenu { @Nullable @@ -43,8 +40,10 @@ public void sendInitialData(AbstractContainerMenu container, NonNullList Byte.MAX_VALUE) { - sendLargeStack(stack, slot, player); + if (player != null) { + if (stack.getCount() > Byte.MAX_VALUE) { + sendLargeStack(stack, slot, player); + } } } @@ -75,13 +74,12 @@ public void clicked(int slot, int dragType, ClickType clickType, Player player) super.clicked(slot, dragType, clickType, player); } - @Nonnull @Override - public ItemStack quickMoveStack(@Nonnull Player player, int slotIndex) { + public ItemStack quickMoveStack(Player player, int slotIndex) { ItemStack transferredStack = ItemStack.EMPTY; Slot slot = slots.get(slotIndex); - if (slot != null && slot.hasItem()) { + if (slot.hasItem()) { ItemStack stack = slot.getItem(); transferredStack = stack.copy(); @@ -100,7 +98,7 @@ public ItemStack quickMoveStack(@Nonnull Player player, int slotIndex) { } @Override - public boolean moveItemStackTo(@Nonnull ItemStack stack, int startIndex, int endIndex, boolean reverse) { + public boolean moveItemStackTo(ItemStack stack, int startIndex, int endIndex, boolean reverse) { boolean merged = false; int slotIndex = reverse ? endIndex - 1 : startIndex; @@ -176,7 +174,7 @@ protected void bindPlayerInventory(Inventory inventoryPlayer, int x, int y) { } @Override - public boolean stillValid(@Nonnull Player var1) { + public boolean stillValid(Player var1) { return true; } diff --git a/src/main/java/codechicken/lib/inventory/container/SlotDummy.java b/src/main/java/codechicken/lib/inventory/container/SlotDummy.java index 8a63e09f..7383c3dc 100644 --- a/src/main/java/codechicken/lib/inventory/container/SlotDummy.java +++ b/src/main/java/codechicken/lib/inventory/container/SlotDummy.java @@ -7,8 +7,6 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; - public class SlotDummy extends SlotHandleClicks { public final int stackLimit; @@ -29,7 +27,7 @@ public void slotClick(ContainerExtended container, Player player, int button, Cl slotClick(held, button, shift); } - public void slotClick(@Nonnull ItemStack held, int button, boolean shift) { + public void slotClick(ItemStack held, int button, boolean shift) { ItemStack tstack = getItem(); if (!held.isEmpty() && (tstack.isEmpty() || !InventoryUtils.canStack(held, tstack))) { int quantity = Math.min(held.getCount(), stackLimit); @@ -63,7 +61,7 @@ public void slotClick(@Nonnull ItemStack held, int button, boolean shift) { } @Override - public void set(@Nonnull ItemStack stack) { + public void set(ItemStack stack) { if (!stack.isEmpty() && stack.getCount() > stackLimit) { stack = ItemUtils.copyStack(stack, stackLimit); } diff --git a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java index 759b2db8..d08a9c52 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java +++ b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java @@ -8,7 +8,7 @@ /** * The base class of a simple general purpose serializable data system. - * + *

* Created by brandon3055 on 08/09/2023 */ public abstract class AbstractDataStore { @@ -28,7 +28,7 @@ public void set(T value) { markDirty(); } - public void markDirty(){} + public void markDirty() { } public abstract void toBytes(MCDataOutput buf); diff --git a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java index 5a5bf64c..1c2e78bc 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java @@ -4,8 +4,7 @@ import codechicken.lib.data.MCDataOutput; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; /** * Created by brandon3055 on 09/09/2023 diff --git a/src/main/java/codechicken/lib/inventory/container/data/package-info.java b/src/main/java/codechicken/lib/inventory/container/data/package-info.java new file mode 100644 index 00000000..349edd07 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory.container.data; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java index 02338869..3d8017dd 100644 --- a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java @@ -181,7 +181,7 @@ public static boolean canStacksMerge(ItemStack stack1, ItemStack stack2) { @Override public ItemStack quickMoveStack(@NotNull Player player, int slotIndex) { Slot slot = getSlot(slotIndex); - if (slot == null || !slot.hasItem()) { + if (!slot.hasItem()) { return ItemStack.EMPTY; } diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java index 75dcc995..cea22da4 100644 --- a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java @@ -2,11 +2,10 @@ import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.SlotItemHandler; -import net.minecraftforge.items.wrapper.InvWrapper; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.SlotItemHandler; +import net.neoforged.neoforge.items.wrapper.InvWrapper; import java.util.function.*; @@ -17,13 +16,14 @@ * Created by brandon3055 on 10/09/2023 */ public class ModularSlot extends SlotItemHandler { + private boolean canPlace = true; private boolean checkContainer = true; private Supplier enabled = () -> true; private Predicate validator = stack -> true; private Function stackLimit = stack -> Integer.MAX_VALUE; private BiPredicate canRemove = (player, stack) -> true; - private BiConsumer onSet = (oldStack, newStack) -> {}; + private BiConsumer onSet = (oldStack, newStack) -> { }; public ModularSlot(Container container, int index) { this(new InvWrapper(container), index, 0, 0); diff --git a/src/main/java/codechicken/lib/inventory/container/modular/package-info.java b/src/main/java/codechicken/lib/inventory/container/modular/package-info.java new file mode 100644 index 00000000..2f3b2775 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/modular/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory.container.modular; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/inventory/container/package-info.java b/src/main/java/codechicken/lib/inventory/container/package-info.java new file mode 100644 index 00000000..494a5170 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory.container; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/inventory/package-info.java b/src/main/java/codechicken/lib/inventory/package-info.java new file mode 100644 index 00000000..6bf104e9 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/item/SimpleItemTier.java b/src/main/java/codechicken/lib/item/SimpleItemTier.java deleted file mode 100644 index 5fbd9ed9..00000000 --- a/src/main/java/codechicken/lib/item/SimpleItemTier.java +++ /dev/null @@ -1,124 +0,0 @@ -package codechicken.lib.item; - -import net.minecraft.util.LazyLoadedValue; -import net.minecraft.world.item.Tier; -import net.minecraft.world.item.crafting.Ingredient; - -import java.util.function.Supplier; - -/** - * Created by covers1624 on 14/12/20. - */ -public class SimpleItemTier implements Tier { - - private final int maxUses; - private final float efficiency; - private final float attackDamage; - private final int harvestLevel; - private final int enchantability; - private final LazyLoadedValue repairMaterial; - - public SimpleItemTier(int maxUses, float efficiency, float attackDamage, int harvestLevel, int enchantability, Supplier repairMaterial) { - this.maxUses = maxUses; - this.efficiency = efficiency; - this.attackDamage = attackDamage; - this.harvestLevel = harvestLevel; - this.enchantability = enchantability; - this.repairMaterial = new LazyLoadedValue<>(repairMaterial); - } - - public static Builder builder() { - return new Builder(); - } - - public static Builder builder(Tier other) { - return builder().from(other); - } - - @Override - public int getUses() { - return maxUses; - } - - @Override - public float getSpeed() { - return efficiency; - } - - @Override - public float getAttackDamageBonus() { - return attackDamage; - } - - @Override - public int getLevel() { - return harvestLevel; - } - - @Override - public int getEnchantmentValue() { - return enchantability; - } - - @Override - public Ingredient getRepairIngredient() { - return repairMaterial.get(); - } - - public static class Builder { - - private int maxUses; - private float efficiency; - private float attackDamage; - private int harvestLevel; - private int enchantability; - private Supplier repairMaterial; - - private Builder() { - } - - public Builder from(Tier other) { - maxUses(other.getUses()); - efficiency(other.getSpeed()); - attackDamage(other.getAttackDamageBonus()); - harvestLevel(other.getLevel()); - enchantability(other.getEnchantmentValue()); - repairMaterial(other::getRepairIngredient); - return this; - } - - public Builder maxUses(int maxUses) { - this.maxUses = maxUses; - return this; - } - - public Builder efficiency(float efficiency) { - this.efficiency = efficiency; - return this; - } - - public Builder attackDamage(float attackDamage) { - this.attackDamage = attackDamage; - return this; - } - - public Builder harvestLevel(int harvestLevel) { - this.harvestLevel = harvestLevel; - return this; - } - - public Builder enchantability(int enchantability) { - this.enchantability = enchantability; - return this; - } - - public Builder repairMaterial(Supplier repairMaterial) { - this.repairMaterial = repairMaterial; - return this; - } - - public SimpleItemTier build() { - return new SimpleItemTier(maxUses, efficiency, attackDamage, harvestLevel, enchantability, repairMaterial); - } - } -} diff --git a/src/main/java/codechicken/lib/item/package-info.java b/src/main/java/codechicken/lib/item/package-info.java new file mode 100644 index 00000000..7e7f203d --- /dev/null +++ b/src/main/java/codechicken/lib/item/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.item; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/math/InterpHelper.java b/src/main/java/codechicken/lib/math/InterpHelper.java index 7c052166..170bedc9 100644 --- a/src/main/java/codechicken/lib/math/InterpHelper.java +++ b/src/main/java/codechicken/lib/math/InterpHelper.java @@ -23,8 +23,8 @@ */ public class InterpHelper { - private float[][] posCache = new float[4][2]; - private float[] valCache = new float[4]; + private final float[][] posCache = new float[4][2]; + private final float[] valCache = new float[4]; private float x0; private float x1; diff --git a/src/main/java/codechicken/lib/math/MathHelper.java b/src/main/java/codechicken/lib/math/MathHelper.java index bf055bac..95e13884 100644 --- a/src/main/java/codechicken/lib/math/MathHelper.java +++ b/src/main/java/codechicken/lib/math/MathHelper.java @@ -3,6 +3,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Vec3i; +import org.jetbrains.annotations.Nullable; public class MathHelper { @@ -297,29 +298,14 @@ public static int toSide(BlockPos pos) { return side == null ? -1 : side.get3DDataValue(); } - public static Direction getSide(BlockPos pos) { - if (!isAxial(pos)) { - return null; - } - if (pos.getY() < 0) { - return Direction.DOWN; - } - if (pos.getY() > 0) { - return Direction.UP; - } - if (pos.getZ() < 0) { - return Direction.NORTH; - } - if (pos.getZ() > 0) { - return Direction.SOUTH; - } - if (pos.getX() < 0) { - return Direction.WEST; - } - if (pos.getX() > 0) { - return Direction.EAST; - } - + public static @Nullable Direction getSide(BlockPos pos) { + if (!isAxial(pos)) return null; + if (pos.getY() < 0) return Direction.DOWN; + if (pos.getY() > 0) return Direction.UP; + if (pos.getZ() < 0) return Direction.NORTH; + if (pos.getZ() > 0) return Direction.SOUTH; + if (pos.getX() < 0) return Direction.WEST; + if (pos.getX() > 0) return Direction.EAST; return null; } } diff --git a/src/main/java/codechicken/lib/math/package-info.java b/src/main/java/codechicken/lib/math/package-info.java new file mode 100644 index 00000000..9ced2de5 --- /dev/null +++ b/src/main/java/codechicken/lib/math/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.math; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/model/ClassModelLoader.java b/src/main/java/codechicken/lib/model/ClassModelLoader.java index 8238e397..18676f91 100644 --- a/src/main/java/codechicken/lib/model/ClassModelLoader.java +++ b/src/main/java/codechicken/lib/model/ClassModelLoader.java @@ -11,9 +11,9 @@ import net.minecraft.client.resources.model.ModelBaker; import net.minecraft.client.resources.model.ModelState; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.client.model.geometry.IGeometryBakingContext; -import net.minecraftforge.client.model.geometry.IGeometryLoader; -import net.minecraftforge.client.model.geometry.IUnbakedGeometry; +import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; +import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; +import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; diff --git a/src/main/java/codechicken/lib/model/CompositeItemModel.java b/src/main/java/codechicken/lib/model/CompositeItemModel.java index 054641c3..1bdd8e54 100644 --- a/src/main/java/codechicken/lib/model/CompositeItemModel.java +++ b/src/main/java/codechicken/lib/model/CompositeItemModel.java @@ -13,11 +13,11 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.client.model.CompositeModel; -import net.minecraftforge.client.model.geometry.IGeometryBakingContext; -import net.minecraftforge.client.model.geometry.IGeometryLoader; -import net.minecraftforge.client.model.geometry.IUnbakedGeometry; -import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper; +import net.neoforged.neoforge.client.model.CompositeModel; +import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; +import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; +import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; +import net.neoforged.neoforge.client.model.geometry.UnbakedGeometryHelper; import org.jetbrains.annotations.Nullable; import java.util.List; diff --git a/src/main/java/codechicken/lib/model/DummyBakedModel.java b/src/main/java/codechicken/lib/model/DummyBakedModel.java index 553cec52..b82f2bb3 100644 --- a/src/main/java/codechicken/lib/model/DummyBakedModel.java +++ b/src/main/java/codechicken/lib/model/DummyBakedModel.java @@ -1,5 +1,6 @@ package codechicken.lib.model; +import codechicken.lib.texture.TextureUtils; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemOverrides; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -7,11 +8,10 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.Collections; import java.util.List; -import java.util.Random; /** * Simple dummy model. @@ -46,7 +46,7 @@ public boolean isCustomRenderer() { @Override public TextureAtlasSprite getParticleIcon() { - return null; + return TextureUtils.getMissingSprite(); } @Override diff --git a/src/main/java/codechicken/lib/model/ItemQuadBakery.java b/src/main/java/codechicken/lib/model/ItemQuadBakery.java index aaae8e29..2cdac73c 100644 --- a/src/main/java/codechicken/lib/model/ItemQuadBakery.java +++ b/src/main/java/codechicken/lib/model/ItemQuadBakery.java @@ -1,15 +1,13 @@ package codechicken.lib.model; -import codechicken.lib.util.ArrayUtils; -import codechicken.lib.util.LambdaUtils; import com.mojang.math.Transformation; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.BlockElement; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.ModelState; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.client.model.SimpleModelState; -import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper; +import net.neoforged.neoforge.client.model.SimpleModelState; +import net.neoforged.neoforge.client.model.geometry.UnbakedGeometryHelper; import java.util.LinkedList; import java.util.List; @@ -26,12 +24,10 @@ public static List bakeItem(TextureAtlasSprite... sprites) { } public static List bakeItem(ModelState state, TextureAtlasSprite... sprites) { - LambdaUtils.checkArgument(sprites, "Sprites must not be Null or empty!", ArrayUtils::isNullOrContainsNull); - List quads = new LinkedList<>(); for (int i = 0; i < sprites.length; i++) { TextureAtlasSprite sprite = sprites[i]; - List unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite.contents()); + List unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite); quads.addAll(UnbakedGeometryHelper.bakeElements(unbaked, e -> sprite, state, new ResourceLocation("ccl:dynamic"))); } return quads; diff --git a/src/main/java/codechicken/lib/model/ModelRegistryHelper.java b/src/main/java/codechicken/lib/model/ModelRegistryHelper.java deleted file mode 100644 index c703e29a..00000000 --- a/src/main/java/codechicken/lib/model/ModelRegistryHelper.java +++ /dev/null @@ -1,37 +0,0 @@ -package codechicken.lib.model; - -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelResourceLocation; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.LinkedList; -import java.util.List; - -public class ModelRegistryHelper { - - private final List> registerModels = new LinkedList<>(); - - public ModelRegistryHelper() { - this(FMLJavaModLoadingContext.get().getModEventBus()); - } - - public ModelRegistryHelper(IEventBus eventBus) { - eventBus.register(this); - } - - public void register(ModelResourceLocation location, BakedModel model) { - registerModels.add(new ImmutablePair<>(location, model)); - } - - @SubscribeEvent - public void onModelBake(ModelEvent.ModifyBakingResult event) { - for (Pair pair : registerModels) { - event.getModels().put(pair.getKey(), pair.getValue()); - } - } -} diff --git a/src/main/java/codechicken/lib/model/Quad.java b/src/main/java/codechicken/lib/model/Quad.java index bd4428d0..8dbee83e 100644 --- a/src/main/java/codechicken/lib/model/Quad.java +++ b/src/main/java/codechicken/lib/model/Quad.java @@ -29,6 +29,9 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; import net.minecraft.world.phys.AABB; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; /** * A simple easy to manipulate quad format. Can be reset and then used on a different format. @@ -37,12 +40,12 @@ */ public class Quad implements IVertexProducer, IVertexConsumer { - public CachedFormat format; + private @Nullable CachedFormat format; public int tintIndex = -1; - public Direction orientation; + public @Nullable Direction orientation; public boolean diffuseLighting = true; - public TextureAtlasSprite sprite; + public @Nullable TextureAtlasSprite sprite; public Vertex[] vertices = new Vertex[4]; public boolean full; @@ -71,9 +74,13 @@ public Quad(CachedFormat format) { this.format = format; } + public final CachedFormat format() { + return requireNonNull(format, "Quad does not have a format assigned yet."); + } + @Override public VertexFormat getVertexFormat() { - return format.format; + return format().format; } @Override @@ -103,11 +110,11 @@ public void put(int element, float... data) { } Vertex v = vertices[vertexIndex]; if (v == null) { - v = new Vertex(format); + v = new Vertex(format()); vertices[vertexIndex] = v; } System.arraycopy(data, 0, v.raw[element], 0, data.length); - if (element == (format.elementCount - 1)) { + if (element == (format().elementCount - 1)) { vertexIndex++; if (vertexIndex == 4) { vertexIndex = 0; @@ -127,7 +134,7 @@ public void put(Quad quad) { @Override public void pipe(IVertexConsumer consumer) { if (consumer instanceof IVertexConsumer) { - ((IVertexConsumer) consumer).put(this); + consumer.put(this); } else { consumer.setQuadTint(tintIndex); consumer.setQuadOrientation(orientation); @@ -174,7 +181,7 @@ public void clamp(AABB bb) { */ public void clamp(Cuboid6 cuboid) { for (Vertex vertex : vertices) { - float[] vec = vertex.vec; + float[] vec = vertex.vec(); vec[0] = (float) MathHelper.clip(vec[0], cuboid.min.x, cuboid.max.x); vec[1] = (float) MathHelper.clip(vec[1], cuboid.min.y, cuboid.max.y); vec[2] = (float) MathHelper.clip(vec[2], cuboid.min.z, cuboid.max.z); @@ -189,17 +196,17 @@ public void clamp(Cuboid6 cuboid) { * @param setNormal If the normal vector should be updated. */ public void calculateOrientation(boolean setNormal) { - v1.set(vertices[3].vec).subtract(t.set(vertices[1].vec)); - v2.set(vertices[2].vec).subtract(t.set(vertices[0].vec)); + v1.set(vertices[3].vec()).subtract(t.set(vertices[1].vec())); + v2.set(vertices[2].vec()).subtract(t.set(vertices[0].vec())); Vector3 normal = v2.crossProduct(v1).normalize(); - if (format.hasNormal && setNormal) { + if (format().hasNormal && setNormal) { for (Vertex vertex : vertices) { - vertex.normal[0] = (float) normal.x; - vertex.normal[1] = (float) normal.y; - vertex.normal[2] = (float) normal.z; - vertex.normal[3] = 0; + vertex.normal()[0] = (float) normal.x; + vertex.normal()[1] = (float) normal.y; + vertex.normal()[2] = (float) normal.z; + vertex.normal()[3] = 0; } } orientation = Direction.getNearest(normal.x, normal.y, normal.z); @@ -214,7 +221,7 @@ public Quad copy() { if (!full) { throw new RuntimeException("Only copying full quads is supported."); } - Quad quad = new Quad(format); + Quad quad = new Quad(format()); quad.tintIndex = tintIndex; quad.orientation = orientation; quad.diffuseLighting = diffuseLighting; @@ -240,7 +247,7 @@ public Quad copyFrom(Quad quad) { sprite = quad.sprite; full = quad.full; for (int v = 0; v < 4; v++) { - for (int e = 0; e < format.elementCount; e++) { + for (int e = 0; e < format().elementCount; e++) { System.arraycopy(quad.vertices[v].raw[e], 0, vertices[v].raw[e], 0, 4); } } @@ -283,10 +290,10 @@ public void rewind() { * @return The BakedQuad. */ public BakedQuad bake() { - int[] packedData = new int[format.format.getVertexSize()]; + int[] packedData = new int[format().format.getVertexSize()]; for (int v = 0; v < 4; v++) { - for (int e = 0; e < format.elementCount; e++) { - VertexUtils.pack(vertices[v].raw[e], packedData, format.format, v, e); + for (int e = 0; e < format().elementCount; e++) { + VertexUtils.pack(vertices[v].raw[e], packedData, format().format, v, e); } } @@ -295,9 +302,11 @@ public BakedQuad bake() { // Broken out as a stub for mixins to target easier. private BakedQuad makeQuad(int[] packedData) { - if (format.format != DefaultVertexFormat.BLOCK) { - throw new IllegalStateException("Unable to bake this quad to the specified format. " + format.format); + if (format().format != DefaultVertexFormat.BLOCK) { + throw new IllegalStateException("Unable to bake this quad to the specified format. " + format().format); } + requireNonNull(orientation, "Quad requires an orientation."); + requireNonNull(sprite, "Quad requires a sprite."); return new BakedQuad(packedData, tintIndex, orientation, sprite, diffuseLighting); } @@ -314,12 +323,12 @@ public static class Vertex { public float[][] raw; // References to the arrays inside raw. - public float[] vec; - public float[] normal; - public float[] color; - public float[] uv; - public float[] overlay; - public float[] lightmap; + private float @Nullable [] vec; + private float @Nullable [] normal; + private float @Nullable [] color; + private float @Nullable [] uv; + private float @Nullable [] overlay; + private float @Nullable [] lightmap; /** * Create a new Vertex. @@ -371,6 +380,15 @@ public void preProcess() { } } + // @formatter:off + public final float[] vec() { return requireNonNull(vec, "Vertex does not have the position element.");} + public final float[] normal() { return requireNonNull(normal, "Vertex does not have the normal element.");} + public final float[] color() { return requireNonNull(color, "Vertex does not have the colour element.");} + public final float[] uv() { return requireNonNull(uv, "Vertex does not have the uv element.");} + public final float[] overlay() { return requireNonNull(overlay, "Vertex does not have the overlay element.");} + public final float[] lightmap() { return requireNonNull(lightmap, "Vertex does not have the lightmap element.");} + // @formatter:on + /** * Gets the 2d X coord for the given axis. * @@ -379,9 +397,9 @@ public void preProcess() { */ public float dx(int s) { if (s <= 1) { - return vec[0]; + return vec()[0]; } else { - return vec[2]; + return vec()[2]; } } @@ -393,9 +411,9 @@ public float dx(int s) { */ public float dy(int s) { if (s > 0) { - return vec[1]; + return vec()[1]; } else { - return vec[2]; + return vec()[2]; } } @@ -408,13 +426,13 @@ public float dy(int s) { */ public Vertex interpColorFrom(InterpHelper interpHelper, Vertex[] others) { for (int e = 0; e < 4; e++) { - float p1 = others[0].color[e]; - float p2 = others[1].color[e]; - float p3 = others[2].color[e]; - float p4 = others[3].color[e]; + float p1 = others[0].color()[e]; + float p2 = others[1].color()[e]; + float p3 = others[2].color()[e]; + float p4 = others[3].color()[e]; // Only interpolate if colors are different. if (p1 != p2 || p2 != p3 || p3 != p4) { - color[e] = interpHelper.interpolate(p1, p2, p3, p4); + color()[e] = interpHelper.interpolate(p1, p2, p3, p4); } } return this; @@ -429,12 +447,12 @@ public Vertex interpColorFrom(InterpHelper interpHelper, Vertex[] others) { */ public Vertex interpUVFrom(InterpHelper interpHelper, Vertex[] others) { for (int e = 0; e < 2; e++) { - float p1 = others[0].uv[e]; - float p2 = others[1].uv[e]; - float p3 = others[2].uv[e]; - float p4 = others[3].uv[e]; + float p1 = others[0].uv()[e]; + float p2 = others[1].uv()[e]; + float p3 = others[2].uv()[e]; + float p4 = others[3].uv()[e]; if (p1 != p2 || p2 != p3 || p3 != p4) { - uv[e] = interpHelper.interpolate(p1, p2, p3, p4); + uv()[e] = interpHelper.interpolate(p1, p2, p3, p4); } } return this; @@ -449,12 +467,12 @@ public Vertex interpUVFrom(InterpHelper interpHelper, Vertex[] others) { */ public Vertex interpLightMapFrom(InterpHelper interpHelper, Vertex[] others) { for (int e = 0; e < 2; e++) { - float p1 = others[0].lightmap[e]; - float p2 = others[1].lightmap[e]; - float p3 = others[2].lightmap[e]; - float p4 = others[3].lightmap[e]; + float p1 = others[0].lightmap()[e]; + float p2 = others[1].lightmap()[e]; + float p3 = others[2].lightmap()[e]; + float p4 = others[3].lightmap()[e]; if (p1 != p2 || p2 != p3 || p3 != p4) { - lightmap[e] = interpHelper.interpolate(p1, p2, p3, p4); + lightmap()[e] = interpHelper.interpolate(p1, p2, p3, p4); } } return this; diff --git a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java b/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java index 3e58dd29..5865a9a7 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java @@ -19,11 +19,10 @@ import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.common.util.ConcatenatedListView; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.common.util.ConcatenatedListView; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -78,7 +77,7 @@ protected List getAllQuads(BlockState state, ModelData modelData) { } @Override - public Set getHitEffects(@Nonnull BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData) { + public Set getHitEffects(BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData) { Vector3 vec = new Vector3(traceResult.getLocation()).subtract(traceResult.getBlockPos()); return getAllQuads(state, modelData).stream() .filter(quad -> quad.getDirection() == traceResult.getDirection()) diff --git a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java b/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java index c93011b3..258bf2f3 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java @@ -7,8 +7,9 @@ import codechicken.lib.util.TransformUtils; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.BakedModel; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; +import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 19/11/2016. @@ -70,11 +71,7 @@ public boolean usesBlockLight() { } public TextureAtlasSprite getParticleTexture() { - //TODO, Move this to use a ResourceLocation. - if (particle == null) { - particle = TextureUtils.getMissingSprite(); - } - return particle; + return maybeMissingTexture(particle); } @Override @@ -90,6 +87,13 @@ public Builder toBuilder() { return new Builder(this); } + private static TextureAtlasSprite maybeMissingTexture(@Nullable TextureAtlasSprite sprite) { + if (sprite == null) { + sprite = TextureUtils.getMissingSprite(); + } + return sprite; + } + /** * Created by covers1624 on 21/02/2017. */ @@ -131,7 +135,7 @@ public PerspectiveBuilder toBuilder() { public static class PerspectiveBuilder extends Builder { - private PerspectiveModelState transforms; + private @Nullable PerspectiveModelState transforms; protected PerspectiveBuilder(PerspectiveProperties properties) { super(properties); @@ -150,7 +154,7 @@ public PerspectiveBuilder withTransforms(PerspectiveModelState transforms) { @Override public PerspectiveProperties build() { - return new PerspectiveProperties(transforms, super.build()); + return new PerspectiveProperties(requireNonNull(transforms), super.build()); } } } @@ -161,7 +165,7 @@ public static class Builder { private boolean isGui3D; private boolean isBuiltInRenderer; private boolean usesBlockLight; - private TextureAtlasSprite particle; + private @Nullable TextureAtlasSprite particle; protected Builder() { } @@ -174,7 +178,7 @@ protected Builder(ModelProperties properties) { particle = properties.particle; } - protected Builder(boolean isAO, boolean isGui3D, boolean usesBlockLight, boolean isBuiltInRenderer, TextureAtlasSprite particle) { + protected Builder(boolean isAO, boolean isGui3D, boolean usesBlockLight, boolean isBuiltInRenderer, @Nullable TextureAtlasSprite particle) { this.isAO = isAO; this.isGui3D = isGui3D; this.usesBlockLight = usesBlockLight; @@ -231,7 +235,7 @@ public PerspectiveBuilder withTransforms(PerspectiveModelState transforms) { } public ModelProperties build() { - return new ModelProperties(isAO, isGui3D, usesBlockLight, isBuiltInRenderer, particle); + return new ModelProperties(isAO, isGui3D, usesBlockLight, isBuiltInRenderer, maybeMissingTexture(particle)); } } diff --git a/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java b/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java index cb67cfa3..94854b7d 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java @@ -1,5 +1,6 @@ package codechicken.lib.model.bakedmodels; +import codechicken.lib.texture.TextureUtils; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemOverrides; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -7,11 +8,10 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.Collections; import java.util.List; -import java.util.Random; /** * Created by covers1624 on 29/06/2017. @@ -51,7 +51,7 @@ public boolean isCustomRenderer() { @Override public TextureAtlasSprite getParticleIcon() { - return null; + return TextureUtils.getMissingSprite(); } @Override diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java index 85f1c4df..e06f7a78 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java @@ -9,6 +9,7 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; @@ -19,8 +20,8 @@ @Deprecated // These may go away unless there is sufficient need for generic implementations like these. public class PerspectiveAwareBakedModel extends AbstractBakedPropertiesModel { - private final ImmutableMap> faceQuads; - private final ImmutableList generalQuads; + private final Map> faceQuads; + private final List generalQuads; public PerspectiveAwareBakedModel(Map> faceQuads, PerspectiveModelState transforms, ModelProperties properties) { this(faceQuads, ImmutableList.of(), transforms, properties); @@ -49,15 +50,10 @@ public PerspectiveAwareBakedModel(Map> faceQuads, Lis } @Override - public List getQuads(BlockState state, Direction side, RandomSource rand) { - if (side == null) { - return generalQuads; - } else { - if (faceQuads.containsKey(side)) { - return faceQuads.get(side); - } - } - return ImmutableList.of(); + public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { + if (side == null) return generalQuads; + + return faceQuads.getOrDefault(side, List.of()); } @Override diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java index e3a37c87..610efe86 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java @@ -8,8 +8,8 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.ChunkRenderTypeSet; +import net.neoforged.neoforge.client.model.data.ModelData; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -22,8 +22,8 @@ @Deprecated // These may go away unless there is sufficient need for generic implementations like these. public class PerspectiveAwareLayeredModel extends AbstractBakedPropertiesModel { - private final ImmutableMap> unculledQuads; - private final ImmutableMap>> faceQuads; + private final Map> unculledQuads; + private final Map>> faceQuads; private final RenderType generallayer; private final ChunkRenderTypeSet chunkLayers; diff --git a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java b/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java index ae0172d3..7c9fc03f 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java +++ b/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java @@ -22,10 +22,10 @@ import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import java.util.function.Function; @@ -38,10 +38,8 @@ public abstract class WrappedItemModel implements BakedModel { protected final BakedModel wrapped; protected final ModelState parentState; - @Nullable - protected LivingEntity entity; - @Nullable - protected ClientLevel world; + protected @Nullable LivingEntity entity; + protected @Nullable ClientLevel world; private final ItemOverrides overrideList = new ItemOverrides() { @Override @@ -58,7 +56,7 @@ public WrappedItemModel(BakedModel wrapped) { } @Override - public List getQuads(BlockState state, Direction side, RandomSource rand) { + public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { return Collections.emptyList(); } @@ -111,6 +109,7 @@ protected void renderWrapped(ItemStack stack, PoseStack pStack, MultiBufferSourc // TODO this needs to be redesigned so other IItemRenderers can be used as override models. protected void renderWrapped(ItemStack stack, PoseStack pStack, MultiBufferSource buffers, int packedLight, int packedOverlay, boolean fabulous, Function consOverride) { BakedModel model = wrapped.getOverrides().resolve(wrapped, stack, world, entity, 0); + if (model == null) return; // What? ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer(); RenderType rType = ItemBlockRenderTypes.getRenderType(stack, fabulous); diff --git a/src/main/java/codechicken/lib/model/bakedmodels/package-info.java b/src/main/java/codechicken/lib/model/bakedmodels/package-info.java new file mode 100644 index 00000000..39092011 --- /dev/null +++ b/src/main/java/codechicken/lib/model/bakedmodels/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.model.bakedmodels; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/model/package-info.java b/src/main/java/codechicken/lib/model/package-info.java new file mode 100644 index 00000000..864653ce --- /dev/null +++ b/src/main/java/codechicken/lib/model/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.model; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java b/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java index 41866bec..fbe7fd63 100644 --- a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java +++ b/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java @@ -24,6 +24,7 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.LinkedList; @@ -68,7 +69,7 @@ public class BakedPipeline implements IVertexConsumer { private final PipelineElement[] elements; private final Map> nameLookup; - private IPipelineConsumer first; + private @Nullable IPipelineConsumer first; private final Quad unpacker = new Quad(); @@ -168,23 +169,28 @@ public void setElementState(String name, boolean enabled) { * @param collector The IVertexConsumer that should collect the transformed quad. */ public void prepare(IVertexConsumer collector) { + if (elements.length == 0) throw new IllegalStateException("No elements in the pipeline."); + IPipelineConsumer next = null; for (PipelineElement element : elements) { if (element.isEnabled) { if (first == null) { first = element.consumer; } else { + assert next != null; next.setParent(element.consumer); } next = element.consumer; } } + assert next != null; next.setParent(collector); } @Override public VertexFormat getVertexFormat() { check(); + assert first != null; return first.getVertexFormat(); } @@ -234,6 +240,7 @@ private void check() { } private void onFull() { + assert first != null; first.setInputQuad(unpacker); first.put(unpacker); } @@ -243,11 +250,17 @@ private void onFull() { */ public static class PipelineElement { - public String name; - public boolean defaultState; - public T consumer; + public final String name; + public final boolean defaultState; + public final T consumer; public boolean isEnabled; + public PipelineElement(String name, boolean defaultState, T consumer) { + this.name = name; + this.defaultState = defaultState; + this.consumer = consumer; + } + public void reset(CachedFormat format) { isEnabled = defaultState; consumer.setParent(null); @@ -360,11 +373,7 @@ private PipelineElement makeElement(String name if (elements.stream().anyMatch(p -> p.name.equals(name))) { throw new IllegalArgumentException("Unable to add element with duplicate name: " + name); } - PipelineElement element = new PipelineElement<>(); - element.name = name; - element.consumer = factory.create(); - element.defaultState = defaultState; - return element; + return new PipelineElement<>(name, defaultState, factory.create()); } /** diff --git a/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java b/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java index edd5c8d8..89ff5e54 100644 --- a/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java +++ b/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java @@ -22,6 +22,7 @@ import codechicken.lib.model.IVertexConsumer; import codechicken.lib.model.Quad; import codechicken.lib.model.pipeline.transformers.QuadReInterpolator; +import org.jetbrains.annotations.Nullable; /** * Anything implementing this may be used in the BakedPipeline. @@ -55,5 +56,5 @@ public interface IPipelineConsumer extends IVertexConsumer { * * @param parent The parent. */ - void setParent(IVertexConsumer parent); + void setParent(@Nullable IVertexConsumer parent); } diff --git a/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java b/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java index eb402930..ac2aa55f 100644 --- a/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java +++ b/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java @@ -24,9 +24,12 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import org.jetbrains.annotations.Nullable; import javax.annotation.OverridingMethodsMustInvokeSuper; +import static java.util.Objects.requireNonNull; + /** * Base class for a simple QuadTransformer. * Operates on BakedQuads. @@ -37,8 +40,8 @@ public abstract class QuadTransformer implements IVertexConsumer, IPipelineConsumer { protected final Quad quad; - protected CachedFormat format; - protected IVertexConsumer consumer; + protected @Nullable CachedFormat format; + protected @Nullable IVertexConsumer consumer; /** * Used for the BakedPipeline. @@ -69,7 +72,7 @@ public void reset(CachedFormat format) { } @Override - public void setParent(IVertexConsumer parent) { + public void setParent(@Nullable IVertexConsumer parent) { consumer = parent; } @@ -82,7 +85,7 @@ public void setInputQuad(Quad quad) { } // @formatter:off - @Override public VertexFormat getVertexFormat() { return format.format; } + @Override public VertexFormat getVertexFormat() { return requireNonNull(format).format; } @Override public void setQuadTint( int tint ) { quad.setQuadTint( tint ); } @Override public void setQuadOrientation( Direction orientation ) { quad.setQuadOrientation( orientation ); } @Override public void setApplyDiffuseLighting( boolean diffuse ) { quad.setApplyDiffuseLighting( diffuse ); } @@ -112,7 +115,7 @@ public void put(Quad quad) { public void onFull() { if (transform()) { - quad.pipe(consumer); + quad.pipe(requireNonNull(consumer)); } } diff --git a/src/main/java/codechicken/lib/model/pipeline/package-info.java b/src/main/java/codechicken/lib/model/pipeline/package-info.java new file mode 100644 index 00000000..c23cee20 --- /dev/null +++ b/src/main/java/codechicken/lib/model/pipeline/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.model.pipeline; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java index 5a99b5f8..77f5f796 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java @@ -53,7 +53,7 @@ public QuadAlphaOverride setAlphaOverride(float alphaOverride) { public boolean transform() { if (format.hasColor) { for (Vertex v : quad.vertices) { - v.color[3] = alphaOverride; + v.color()[3] = alphaOverride; } } return true; diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java index 22742a3a..3bf0e5a2 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java @@ -61,6 +61,7 @@ public void setClampBounds(Cuboid6 bounds) { @Override public boolean transform() { + assert quad.orientation != null; int s = quad.orientation.ordinal() >> 1; quad.clamp(clampBounds); diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java index d605f2b0..33b06429 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java @@ -112,6 +112,7 @@ public void setThickness(double thickness) { @Override public boolean transform() { + assert quad.orientation != null; int side = quad.orientation.ordinal(); if (side != mySide && side != (mySide ^ 1)) { for (int hoz : horizonals[mySide]) { @@ -119,17 +120,17 @@ public boolean transform() { if ((facadeMask & (1 << hoz)) != 0) { Corner corner = Corner.fromSides(mySide ^ 1, side, hoz); for (Vertex vertex : quad.vertices) { - float x = vertex.vec[0]; - float y = vertex.vec[1]; - float z = vertex.vec[2]; + float x = vertex.vec()[0]; + float y = vertex.vec()[1]; + float z = vertex.vec()[2]; if (epsComp(x, corner.pX(box)) && epsComp(y, corner.pY(box)) && epsComp(z, corner.pZ(box))) { Vec3i vec = Direction.BY_3D_DATA[hoz].getNormal(); x -= vec.getX() * thickness; y -= vec.getY() * thickness; z -= vec.getZ() * thickness; - vertex.vec[0] = x; - vertex.vec[1] = y; - vertex.vec[2] = z; + vertex.vec()[0] = x; + vertex.vec()[1] = y; + vertex.vec()[2] = z; } } } diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java index 6bdbb977..a4827488 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java @@ -82,6 +82,7 @@ public void setMask(int mask) { @Override public boolean transform() { + assert quad.orientation != null; if (mask == 0) { return true;// No mask, nothing changes. } @@ -92,26 +93,26 @@ public boolean transform() { switch (quad.orientation.getAxis()) { case X -> { float bound = (float) (dir == POSITIVE ? bounds.max.x : bounds.min.x); - float x1 = vertices[0].vec[0]; - float x2 = vertices[1].vec[0]; - float x3 = vertices[2].vec[0]; - float x4 = vertices[3].vec[0]; + float x1 = vertices[0].vec()[0]; + float x2 = vertices[1].vec()[0]; + float x3 = vertices[2].vec()[0]; + float x4 = vertices[3].vec()[0]; return x1 != x2 || x2 != x3 || x3 != x4 || x4 != bound; } case Y -> { float bound = (float) (dir == POSITIVE ? bounds.max.y : bounds.min.y); - float y1 = vertices[0].vec[1]; - float y2 = vertices[1].vec[1]; - float y3 = vertices[2].vec[1]; - float y4 = vertices[3].vec[1]; + float y1 = vertices[0].vec()[1]; + float y2 = vertices[1].vec()[1]; + float y3 = vertices[2].vec()[1]; + float y4 = vertices[3].vec()[1]; return y1 != y2 || y2 != y3 || y3 != y4 || y4 != bound; } case Z -> { float bound = (float) (dir == POSITIVE ? bounds.max.z : bounds.min.z); - float z1 = vertices[0].vec[2]; - float z2 = vertices[1].vec[2]; - float z3 = vertices[2].vec[2]; - float z4 = vertices[3].vec[2]; + float z1 = vertices[0].vec()[2]; + float z2 = vertices[1].vec()[2]; + float z3 = vertices[2].vec()[2]; + float z4 = vertices[3].vec()[2]; return z1 != z2 || z2 != z3 || z3 != z4 || z4 != bound; } } diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java index 8bb27314..03611722 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java @@ -53,11 +53,13 @@ public void reset(CachedFormat format) { @Override public void setInputQuad(Quad quad) { super.setInputQuad(quad); + assert quad.orientation != null; quad.resetInterp(interpHelper, quad.orientation.ordinal() >> 1); } @Override public boolean transform() { + assert quad.orientation != null; int s = quad.orientation.ordinal() >> 1; if (format.hasColor || format.hasUV || format.hasLightMap) { interpCache.copyFrom(quad); diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java index b2750423..326b5442 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java @@ -59,9 +59,9 @@ public boolean transform() { float g = (tint >> 0x08 & 0xFF) / 255F; float b = (tint & 0xFF) / 255F; for (Vertex v : quad.vertices) { - v.color[0] *= r; - v.color[1] *= g; - v.color[2] *= b; + v.color()[0] *= r; + v.color()[1] *= g; + v.color()[2] *= b; } } return true; diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java b/src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java new file mode 100644 index 00000000..50811589 --- /dev/null +++ b/src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.model.pipeline.transformers; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/package-info.java b/src/main/java/codechicken/lib/package-info.java new file mode 100644 index 00000000..17d58fbd --- /dev/null +++ b/src/main/java/codechicken/lib/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java index ebea637e..acfc81c3 100644 --- a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java @@ -1,16 +1,12 @@ package codechicken.lib.packet; import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.protocol.login.ClientLoginPacketListener; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.network.NetworkEvent; +import net.minecraft.server.network.ConfigurationTask; +import net.neoforged.neoforge.network.event.OnGameConfigurationEvent; +import org.jetbrains.annotations.ApiStatus; -import java.util.function.BiConsumer; -import java.util.function.Supplier; +import java.util.function.Consumer; /** * Created by covers1624 on 2/03/2017. @@ -22,12 +18,10 @@ interface IClientPacketHandler extends ICustomPacketHandler { /** * Called on the client to handle a packet sent from the server. * - * @param packet The packet. - * @param mc The Minecraft instance. - * @param handler The ClientPlayNetHandler. + * @param packet The packet. + * @param mc The Minecraft instance. */ - @OnlyIn (Dist.CLIENT) - void handlePacket(PacketCustom packet, Minecraft mc, ClientPacketListener handler); + void handlePacket(PacketCustom packet, Minecraft mc); } interface IServerPacketHandler extends ICustomPacketHandler { @@ -35,42 +29,31 @@ interface IServerPacketHandler extends ICustomPacketHandler { /** * Called on the server to handle a packet sent from a client. * - * @param packet The Packet. - * @param sender The player who sent the packet. - * @param handler The ServerPlayNetHandler + * @param packet The Packet. + * @param sender The player who sent the packet. */ - void handlePacket(PacketCustom packet, ServerPlayer sender, ServerGamePacketListenerImpl handler); + void handlePacket(PacketCustom packet, ServerPlayer sender); } - interface ILoginPacketHandler extends ICustomPacketHandler { + /** + * Used with {@link OnGameConfigurationEvent} to send packets to the client during the configuration phase. + */ + interface IClientConfigurationPacketHandler extends ICustomPacketHandler { /** - * Called on the server to gather all login packets to be sent to the client. - * Unlike usual PacketCustom operation, Login packets are handled differently in FML, - * and require an acknowledgement response to be sent. Login packets must be sent using, - * this. + * Called on the client to handle a configuration phase packet. * - * @param consumer The consumer to accept any packets to be sent, - * The first generic parameter being a descriptive name for the packet used - * in FML logging, the second generic being a supplier used to generate the - * packet. Supplier is used for cleaner scope variable name hiding. + * @param packet The packet. + * @param mc The Minecraft instance. */ - void gatherLoginPackets(BiConsumer> consumer); + void handlePacket(PacketCustom packet, Minecraft mc); + } - /** - * Called on the client to handle a login packet provided through {@link #gatherLoginPackets}. - * This method unlike the other handlers, does not sync to the main thread for processing, instead - * it is fired on the network thread, this is to allow mods to choose if the packet is important - * in the handshake cycle and must be handled before anything else can continue. If the data isn't - * critical to the handshake process, feel free to use {@link NetworkEvent.Context#enqueueWork(Runnable)} - * to throw things on the main thread. - * - * @param packet The packet to handle. - * @param mc The Minecraft instance. - * @param handler Vanilla's NetHandler. - * @param context The network context. - */ - @OnlyIn (Dist.CLIENT) - void handleLoginPacket(PacketCustom packet, Minecraft mc, ClientLoginPacketListener handler, NetworkEvent.Context context); + // TODO this is tricky, as we don't have any context to identify the sending client and have a meaningful back/forth. + // Its likely not incredibly useful for our uses cases here. + @ApiStatus.Experimental + interface IServerConfigurationPacketHandler extends ICustomPacketHandler { + + void handlePacket(PacketCustom packet, ServerPlayer sender, Consumer onTaskCompleted); } } diff --git a/src/main/java/codechicken/lib/packet/PacketCustom.java b/src/main/java/codechicken/lib/packet/PacketCustom.java index 570aea2d..6cbc6002 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustom.java +++ b/src/main/java/codechicken/lib/packet/PacketCustom.java @@ -2,49 +2,46 @@ import codechicken.lib.data.MCDataByteBuf; import codechicken.lib.math.MathHelper; -import codechicken.lib.util.ServerUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.players.ServerOpList; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.registries.IForgeRegistry; -import org.apache.commons.lang3.tuple.Pair; +import net.neoforged.neoforge.fluids.FluidStack; +import org.jetbrains.annotations.Nullable; import java.nio.*; import java.util.UUID; -//TODO, Evaluate explicit packet compression again. //Tasty Cheese! public final class PacketCustom extends MCDataByteBuf { private final ResourceLocation channel; + private final boolean inbound; private final int type; - public PacketCustom(ByteBuf payload) { - super(payload); - this.channel = null; - this.type = readUByte(); + PacketCustom(Pkt pkt) { + super(pkt.data); + channel = pkt.id; + inbound = true; + type = readUByte(); } public PacketCustom(ResourceLocation channel, int type) { @@ -53,12 +50,13 @@ public PacketCustom(ResourceLocation channel, int type) { throw new RuntimeException("Invalid packet type, Must be between 0 and 255. Got: " + type); } this.channel = channel; + inbound = false; this.type = type; writeByte(type); } - public boolean incoming() { - return channel == null; + public boolean isInbound() { + return inbound; } public int getType() { @@ -69,112 +67,68 @@ public ResourceLocation getChannel() { return channel; } - public Packet toPacket(NetworkDirection direction) { - return toPacket(direction, 0); - } + public CustomPacketPayload toCustomPayload() { + if (isInbound()) throw new RuntimeException("Unable to send an inbound packet."); - public Packet toPacket(NetworkDirection direction, int index) { - if (incoming()) { - throw new IllegalStateException("Tried to write an incoming packet"); - } - return direction.buildPacket(Pair.of(toPacketBuffer(), index), channel).getThis(); + return new Pkt(channel, toFriendlyByteBuf()); } - //endregion - //region Server -> Client. - public void sendToPlayer(ServerPlayer player) { - sendToPlayer(toPacket(NetworkDirection.PLAY_TO_CLIENT), player); + // region Server -> Client + public Packet toClientPacket() { + return PacketSender.toClientPacket(toCustomPayload()); } - public static void sendToPlayer(Packet packet, ServerPlayer player) { - if (player == null) { - sendToClients(packet); - } else { - player.connection.send(packet); - } + public void sendToPlayer(@Nullable ServerPlayer player) { + PacketSender.sendToPlayer(toCustomPayload(), player); } - public void sendToClients() { - sendToClients(toPacket(NetworkDirection.PLAY_TO_CLIENT)); + public void sendToAllPlayers() { + PacketSender.sendToAllPlayers(toCustomPayload()); } - public static void sendToClients(Packet packet) { - ServerUtils.getServer().getPlayerList().broadcastAll(packet); + public void sendToAllAround(BlockPos pos, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toCustomPayload(), pos, range, dim); } - public void sendPacketToAllAround(BlockPos pos, double range, ResourceKey dim) { - sendPacketToAllAround(pos.getX(), pos.getY(), pos.getZ(), range, dim); - } - - public void sendPacketToAllAround(double x, double y, double z, double range, ResourceKey dim) { - sendToAllAround(toPacket(NetworkDirection.PLAY_TO_CLIENT), x, y, z, range, dim); - } - - public static void sendToAllAround(Packet packet, double x, double y, double z, double range, ResourceKey dim) { - ServerUtils.getServer().getPlayerList().broadcast(null, x, y, z, range, dim, packet); + public void sendToAllAround(double x, double y, double z, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toCustomPayload(), x, y, z, range, dim); } public void sendToDimension(ResourceKey dim) { - sendToDimension(toPacket(NetworkDirection.PLAY_TO_CLIENT), dim); - } - - public static void sendToDimension(Packet packet, ResourceKey dim) { - ServerUtils.getServer().getPlayerList().broadcastAll(packet, dim); + PacketSender.sendToDimension(toCustomPayload(), dim); } public void sendToChunk(BlockEntity tile) { - sendToChunk(tile.getLevel(), tile.getBlockPos()); + PacketSender.sendToChunk(toCustomPayload(), tile); } - public void sendToChunk(Level world, BlockPos blockPos) { - sendToChunk(toPacket(NetworkDirection.PLAY_TO_CLIENT), world, blockPos); + public void sendToChunk(ServerLevel level, BlockPos pos) { + PacketSender.sendToChunk(toCustomPayload(), level, pos); } - public void sendToChunk(Level world, int chunkX, int chunkZ) { - sendToChunk(toPacket(NetworkDirection.PLAY_TO_CLIENT), world, chunkX, chunkZ); + public void sendToChunk(ServerLevel level, int chunkX, int chunkZ) { + PacketSender.sendToChunk(toCustomPayload(), level, chunkX, chunkZ); } - public void sendToChunk(Level world, ChunkPos pos) { - sendToChunk(toPacket(NetworkDirection.PLAY_TO_CLIENT), world, pos); - } - - public static void sendToChunk(Packet packet, Level world, BlockPos blockPos) { - sendToChunk(packet, world, blockPos.getX() >> 4, blockPos.getZ() >> 4); - } - - public static void sendToChunk(Packet packet, Level world, int chunkX, int chunkZ) { - sendToChunk(packet, world, new ChunkPos(chunkX, chunkZ)); - } - - public static void sendToChunk(Packet packet, Level world, ChunkPos pos) { - ServerLevel serverLevel = (ServerLevel) world; - serverLevel.getChunkSource().chunkMap.getPlayers(pos, false).forEach(e -> e.connection.send(packet)); + public void sendToChunk(ServerLevel level, ChunkPos pos) { + PacketSender.sendToChunk(toCustomPayload(), level, pos); } public void sendToOps() { - sendToOps(toPacket(NetworkDirection.PLAY_TO_CLIENT)); + PacketSender.sendToOps(toCustomPayload()); } + // endregion - public static void sendToOps(Packet packet) { - ServerOpList opList = ServerUtils.getServer().getPlayerList().getOps(); - for (ServerPlayer player : ServerUtils.getServer().getPlayerList().getPlayers()) { - if (opList.get(player.getGameProfile()) != null) { - sendToPlayer(packet, player); - } - } + // region Client -> Server + public Packet toServerPacket() { + return PacketSender.toServerPacket(toCustomPayload()); } - @OnlyIn (Dist.CLIENT) public void sendToServer() { - sendToServer(toPacket(NetworkDirection.PLAY_TO_SERVER)); - } - - @OnlyIn (Dist.CLIENT) - public static void sendToServer(Packet packet) { - Minecraft.getInstance().getConnection().send(packet); + PacketSender.sendToServer(toCustomPayload()); } + // endregion - //endregion //region Machine Generated overrides. //@formatter:off @Override public PacketCustom writeByte(int p0) { super.writeByte(p0); return this; } @@ -227,16 +181,24 @@ public static void sendToServer(Packet packet) { @Override public PacketCustom writeVec3i(Vec3i vec) { super.writeVec3i(vec); return this; } @Override public PacketCustom writeVec3d(Vec3 vec) { super.writeVec3d(vec); return this; } @Override public PacketCustom writeCompoundNBT(CompoundTag tag) { super.writeCompoundNBT(tag); return this; } + @Override public PacketCustom writeNullableCompoundNBT(@Nullable CompoundTag tag) { super.writeNullableCompoundNBT(tag); return this; } @Override public PacketCustom writeFluidStack(FluidStack stack) { super.writeFluidStack(stack); return this; } @Override public PacketCustom writeItemStack(ItemStack stack) { super.writeItemStack(stack); return this; } - @Override public PacketCustom writeItemStack(ItemStack stack, boolean limitedTag) { super.writeItemStack(stack, limitedTag); return this; } @Override public PacketCustom writeTextComponent(Component component) { super.writeTextComponent(component); return this; } - @Override public PacketCustom writeRegistryIdDirect(IForgeRegistry registry, T entry) { super.writeRegistryIdDirect(registry, entry); return this; } - @Override public PacketCustom writeRegistryIdDirect(IForgeRegistry registry, ResourceLocation entry) { super.writeRegistryIdDirect(registry, entry); return this; } - @Override public PacketCustom writeRegistryId(IForgeRegistry registry, T entry) { super.writeRegistryId(registry, entry); return this; } - @Override public PacketCustom writeRegistryId(IForgeRegistry registry, ResourceLocation entry) { super.writeRegistryId(registry, entry); return this; } + @Override public PacketCustom writeRegistryIdDirect(Registry registry, T entry) { super.writeRegistryIdDirect(registry, entry); return this; } + @Override public PacketCustom writeRegistryIdDirect(Registry registry, ResourceLocation entry) { super.writeRegistryIdDirect(registry, entry); return this; } + @Override public PacketCustom writeRegistryId(Registry registry, T entry) { super.writeRegistryId(registry, entry); return this; } + @Override public PacketCustom writeRegistryId(Registry registry, ResourceLocation entry) { super.writeRegistryId(registry, entry); return this; } @Override public PacketCustom writeByteBuf(ByteBuf buf) { super.writeByteBuf(buf); return this; } @Override public PacketCustom append(ByteBuf buf) { super.append(buf); return this; } - //@formatter:off + //@formatter:on //endregion + + record Pkt(ResourceLocation id, FriendlyByteBuf data) implements CustomPacketPayload { + + @Override + public void write(FriendlyByteBuf buf) { + buf.writeBytes(data); + } + } } diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java new file mode 100644 index 00000000..f435b76a --- /dev/null +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -0,0 +1,136 @@ +package codechicken.lib.packet; + +import codechicken.lib.packet.ICustomPacketHandler.IClientConfigurationPacketHandler; +import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; +import codechicken.lib.packet.ICustomPacketHandler.IServerConfigurationPacketHandler; +import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlerEvent; +import net.neoforged.neoforge.network.handling.ISynchronizedWorkHandler; +import net.neoforged.neoforge.network.registration.IPayloadRegistrar; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.function.Supplier; + +/** + * Created by covers1624 on 3/7/24. + */ +public class PacketCustomChannel { + + private static final Logger LOGGER = LoggerFactory.getLogger(PacketCustomChannel.class); + + public final ResourceLocation channel; + + private @Nullable String version; + private boolean optional; + private @Nullable IClientConfigurationPacketHandler clientConfiguration; + private @Nullable IServerConfigurationPacketHandler serverConfiguration; + + private @Nullable IClientPacketHandler client; + private @Nullable IServerPacketHandler server; + + public PacketCustomChannel(ResourceLocation channel) { + this.channel = channel; + } + + public PacketCustomChannel versioned(String version) { + this.version = version; + return this; + } + + public PacketCustomChannel optional() { + optional = true; + return this; + } + + public PacketCustomChannel clientConfiguration(Supplier> supplier) { + if (FMLEnvironment.dist.isClient()) { + clientConfiguration = supplier.get().get(); + } + return this; + } + + // TODO +// public PacketCustomChannel serverConfiguration(Supplier> supplier) { +// serverConfiguration = supplier.get().get(); +// return this; +// } + + public PacketCustomChannel client(Supplier> supplier) { + if (FMLEnvironment.dist.isClient()) { + client = supplier.get().get(); + } + return this; + } + + public PacketCustomChannel server(Supplier> supplier) { + server = supplier.get().get(); + return this; + } + + public void init(IEventBus modBus) { + modBus.addListener(this::onRegisterPayloadHandlerEvent); + } + + private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlerEvent event) { + IPayloadRegistrar registrar = event.registrar(channel.getNamespace()); + + if (optional) registrar = registrar.optional(); + if (version != null) registrar = registrar.versioned(version); + + if (client != null || server != null) { + registrar.play( + channel, + e -> new PacketCustom.Pkt(channel, e.retain()), + handlers -> { + if (client != null) { + handlers.client((payload, context) -> { + enqueue(context.workHandler(), payload, () -> { + client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + }); + } + if (server != null) { + handlers.server((payload, context) -> { + enqueue(context.workHandler(), payload, () -> { + server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player().orElseThrow()); + }); + }); + } + } + ); + } + if (clientConfiguration != null || serverConfiguration != null) { + registrar.configuration( + channel, + e -> new PacketCustom.Pkt(channel, e.retain()), + handlers -> { + handlers.client((payload, context) -> { + enqueue(context.workHandler(), payload, () -> { + clientConfiguration.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + }); + } + ); + } + } + + private static void enqueue(ISynchronizedWorkHandler workHandler, PacketCustom.Pkt payload, Runnable runnable) { + workHandler.submitAsync(() -> { + try { + runnable.run(); + } finally { + payload.data().release(); + } + }).exceptionally(ex -> { + LOGGER.error("Error processing packet on channel {}", payload.id(), ex); + return null; + }); + } +} diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannelBuilder.java b/src/main/java/codechicken/lib/packet/PacketCustomChannelBuilder.java deleted file mode 100644 index db032ec4..00000000 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannelBuilder.java +++ /dev/null @@ -1,282 +0,0 @@ -package codechicken.lib.packet; - -import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; -import codechicken.lib.packet.ICustomPacketHandler.ILoginPacketHandler; -import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.PacketListener; -import net.minecraft.network.protocol.login.ClientLoginPacketListener; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkRegistry; -import net.minecraftforge.network.event.EventNetworkChannel; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.function.Predicate; -import java.util.function.Supplier; - -import static net.covers1624.quack.util.SneakyUtils.trueP; - -/** - * Used to build a network channel for use with {@link PacketCustom}. - * Similar in design to {@link NetworkRegistry.ChannelBuilder}. - *

- * Created by covers1624 on 28/10/19. - */ -public class PacketCustomChannelBuilder { - - private static final Logger LOGGER = LogManager.getLogger(); - - private static final Supplier CONST_1 = () -> "1"; - - private final NetworkRegistry.ChannelBuilder parent; - private final ResourceLocation channelName; - - private Supplier networkProtocolVersion = CONST_1; - private Predicate clientAcceptedVersions = trueP(); - private Predicate serverAcceptedVersions = trueP(); - - private IClientPacketHandler clientHandler; - private IServerPacketHandler serverHandler; - private ILoginPacketHandler loginHandler; - - private PacketCustomChannelBuilder(ResourceLocation channelName) { - this.channelName = channelName; - parent = NetworkRegistry.ChannelBuilder.named(channelName); - } - - /** - * Create a new {@link PacketCustomChannelBuilder} with the given channel name. - * Channel names are global and must be unique per mod. Just use this format: - * "mod_id:network_name". For example: 'codechickenlib:internal' - * - * @param channelName The Channel name. - * @return The builder. - */ - public static PacketCustomChannelBuilder named(ResourceLocation channelName) { - return new PacketCustomChannelBuilder(channelName); - } - - /** - * Register a Supplier that provides the protocol version associated with this channel. - * You are able to compare this value each side of the connection against its local version, - * if you wish to talk across protocol versions. The default is to provide '1' as the version. - * - * @param networkProtocolVersion The version Supplier. - * @return The same builder. - */ - public PacketCustomChannelBuilder networkProtocolVersion(Supplier networkProtocolVersion) { - this.networkProtocolVersion = networkProtocolVersion; - return this; - } - - /** - * Register a Predicate to check the Server side protocol version on the Client. The - * default will accept any remote versions. - * - * @param clientAcceptedVersions The Predicate. - * @return The same builder. - */ - public PacketCustomChannelBuilder clientAcceptedVersions(Predicate clientAcceptedVersions) { - this.clientAcceptedVersions = clientAcceptedVersions; - return this; - } - - /** - * Register a Predicate to check the Client side protocol version on the Server. The - * default will accept any remote versions. - * - * @param serverAcceptedVersions The Predicate. - * @return The same builder. - */ - public PacketCustomChannelBuilder serverAcceptedVersions(Predicate serverAcceptedVersions) { - this.serverAcceptedVersions = serverAcceptedVersions; - return this; - } - - /** - * Register a double Supplier, to construct the {@link IClientPacketHandler} for the client side. - * The double Supplier is used to avoid class loading issues on the server side, you do NOT - * need any external sided checks if you call using the following example: - *
- * builder.assignClientHandler(() -> ClientPacketHandler::new); - *

- * - * @param clientHandler The Supplier. - * @return The same builder. - */ - public PacketCustomChannelBuilder assignClientHandler(Supplier> clientHandler) { - if (FMLEnvironment.dist == Dist.CLIENT) { - this.clientHandler = clientHandler.get().get(); - } - return this; - } - - /** - * Register a double Supplier, to construct the {@link IServerPacketHandler} for the client side. - * The double Supplier is used to avoid confusion with {@link #assignClientHandler}. - * Example usage: builder.assignClientHandler(() -> ServerPacketHandler::new); - * - * @param serverHandler The Supplier. - * @return The same builder. - */ - - public PacketCustomChannelBuilder assignServerHandler(Supplier> serverHandler) { - this.serverHandler = serverHandler.get().get(); - return this; - } - - /** - * Register a double Supplier, to construct the {@link ILoginPacketHandler} for sending packets - * to the client during handshake. See {@link ILoginPacketHandler} for more information. - * Example usage: builder.assignClientHandler(() -> ServerPacketHandler::new); - * - * @param loginHandler The Supplier. - * @return The same builder. - */ - public PacketCustomChannelBuilder assignLoginHandler(Supplier> loginHandler) { - this.loginHandler = loginHandler.get().get(); - return this; - } - - /** - * Actually build and register the channel with Forge. - * - * @return The underlying {@link EventNetworkChannel} - */ - public synchronized EventNetworkChannel build() { - EventNetworkChannel channel = parent - .networkProtocolVersion(networkProtocolVersion) - .clientAcceptedVersions(clientAcceptedVersions) - .serverAcceptedVersions(serverAcceptedVersions) - .eventNetworkChannel(); - - if (clientHandler != null) { - channel.registerObject(new ClientHandler(clientHandler)); - } - - if (serverHandler != null) { - channel.registerObject(new ServerHandler(serverHandler)); - } - if (loginHandler != null) { - channel.registerObject(new LoginHandler(loginHandler)); - } - return channel; - } - - /** - * Handler for Client received packets. - */ - private class ClientHandler { - - private final IClientPacketHandler packetHandler; - - public ClientHandler(IClientPacketHandler packetHandler) { - this.packetHandler = packetHandler; - } - - @SubscribeEvent - public void onClientPayload(NetworkEvent.ServerCustomPayloadEvent event) { - if (event instanceof NetworkEvent.ServerCustomPayloadLoginEvent) { - return; - } - ByteBuf payload = event.getPayload().copy(); - PacketCustom packet = new PacketCustom(payload); - NetworkEvent.Context ctx = event.getSource().get(); - PacketListener netHandler = ctx.getNetworkManager().getPacketListener(); - ctx.setPacketHandled(true); - if (netHandler instanceof ClientPacketListener nh) { - ctx.enqueueWork(() -> { - try { - packetHandler.handlePacket(packet, Minecraft.getInstance(), nh); - } catch (Throwable ex) { - LOGGER.error("Error handling packet on channel {}.", channelName, ex); - } finally { - payload.release(); - } - }); - } - } - } - - /** - * Handler for Server received packets. - */ - private class ServerHandler { - - private final IServerPacketHandler packetHandler; - - public ServerHandler(IServerPacketHandler packetHandler) { - this.packetHandler = packetHandler; - } - - @SubscribeEvent - public void onServerPayload(NetworkEvent.ClientCustomPayloadEvent event) { - ByteBuf payload = event.getPayload().copy(); - PacketCustom packet = new PacketCustom(payload); - NetworkEvent.Context ctx = event.getSource().get(); - PacketListener netHandler = ctx.getNetworkManager().getPacketListener(); - ctx.setPacketHandled(true); - if (netHandler instanceof ServerGamePacketListenerImpl nh) { - ctx.enqueueWork(() -> { - try { - packetHandler.handlePacket(packet, nh.player, nh); - } catch (Throwable ex) { - LOGGER.error("Error handling packet on channel {}.", channelName, ex); - } finally { - payload.release(); - } - }); - } - } - } - - /** - * Handler for Login packets. - */ - private class LoginHandler { - - private final ILoginPacketHandler packetHandler; - - public LoginHandler(ILoginPacketHandler packetHandler) { - this.packetHandler = packetHandler; - } - - @SubscribeEvent - public void onGatherLoginPayloads(NetworkEvent.GatherLoginPayloadsEvent event) { - packetHandler.gatherLoginPackets((ctx, packetSupplier) -> { - PacketCustom packet = packetSupplier.get(); - event.add(packet.toPacketBuffer(), packet.getChannel(), ctx); - }); - } - - @SubscribeEvent - public void onClientPayload(NetworkEvent.LoginPayloadEvent event) { - ByteBuf payload = event.getPayload().copy(); - PacketCustom packet = new PacketCustom(payload); - NetworkEvent.Context ctx = event.getSource().get(); - PacketListener netHandler = ctx.getNetworkManager().getPacketListener(); - ctx.setPacketHandled(true); - if (netHandler instanceof ClientLoginPacketListener nh) { - try { - packetHandler.handleLoginPacket(packet, Minecraft.getInstance(), nh, ctx); - } catch (Throwable ex) { - LOGGER.error("Error handling login packet on channel {}.", channelName, ex); - } finally { - payload.release(); - //For _some_ reason sending this response packet in FML is private. So just spoof the packet :D - ctx.getPacketDispatcher().sendPacket(new ResourceLocation("fml:handshake"), new FriendlyByteBuf(Unpooled.buffer().writeByte(99))); - } - } - } - } -} diff --git a/src/main/java/codechicken/lib/packet/PacketSender.java b/src/main/java/codechicken/lib/packet/PacketSender.java new file mode 100644 index 00000000..9d9c0615 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/PacketSender.java @@ -0,0 +1,277 @@ +package codechicken.lib.packet; + +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.players.PlayerList; +import net.minecraft.server.players.ServerOpList; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; +import static net.neoforged.neoforge.server.ServerLifecycleHooks.getCurrentServer; + +/** + * Created by covers1624 on 17/9/24. + */ +public class PacketSender { + + // region Server -> Client + + /** + * Create a client bound packet for the given custom payload. + * + * @param payload The payload. + * @return The packet. + */ + public static Packet toClientPacket(CustomPacketPayload payload) { + return new ClientboundCustomPayloadPacket(payload); + } + + /** + * Overload of {@link #sendToPlayer(Packet, ServerPlayer)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToPlayer(CustomPacketPayload payload, @Nullable ServerPlayer player) { + sendToPlayer(toClientPacket(payload), player); + } + + /** + * Send the given packet to the specified player. If the specified player is {@code null}, + * sends the packet to all connected clients. + * + * @param packet The packet to send. + * @param player The receiver. {@code null} for all players. + */ + public static void sendToPlayer(Packet packet, @Nullable ServerPlayer player) { + if (player == null) { + sendToAllPlayers(packet); + } else { + player.connection.send(packet); + } + } + + /** + * Overload of {@link #sendToAllPlayers(Packet)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToAllPlayers(CustomPacketPayload payload) { + sendToAllPlayers(toClientPacket(payload)); + } + + /** + * Sends the given packet to all connected clients. + * + * @param packet The packet to send. + */ + public static void sendToAllPlayers(Packet packet) { + getCurrentServer().getPlayerList().broadcastAll(packet); + } + + /** + * Overload of {@link #sendToAllAround(Packet, BlockPos, double, ResourceKey)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToAllAround(CustomPacketPayload payload, BlockPos pos, double range, ResourceKey dim) { + sendToAllAround(toClientPacket(payload), pos, range, dim); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

+ * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param packet The packet to send. + * @param pos The origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public static void sendToAllAround(Packet packet, BlockPos pos, double range, ResourceKey dim) { + sendToAllAround(packet, pos.getX(), pos.getY(), pos.getZ(), range, dim); + } + + /** + * Overload of {@link #sendToAllAround(Packet, double, double, double, double, ResourceKey)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToAllAround(CustomPacketPayload payload, double x, double y, double z, double range, ResourceKey dim) { + sendToAllAround(toClientPacket(payload), x, y, z, range, dim); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

+ * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param packet The packet to send. + * @param x The X origin point to send around. + * @param y The Y origin point to send around. + * @param z The Z origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public static void sendToAllAround(Packet packet, double x, double y, double z, double range, ResourceKey dim) { + getCurrentServer().getPlayerList().broadcast(null, x, y, z, range, dim, packet); + } + + /** + * Overload of {@link #sendToDimension(Packet, ResourceKey)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToDimension(CustomPacketPayload payload, ResourceKey dim) { + sendToDimension(toClientPacket(payload), dim); + } + + /** + * Send the given packet to all players within the given dimension. + * + * @param packet The packet to send. + * @param dim The dimension to send to. + */ + public static void sendToDimension(Packet packet, ResourceKey dim) { + getCurrentServer().getPlayerList().broadcastAll(packet, dim); + } + + /** + * Overload of {@link #sendToChunk(Packet, BlockEntity)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, BlockEntity tile) { + sendToChunk(toClientPacket(payload), tile); + } + + /** + * Send the given packet to all players watching the chunk, that the given {@link BlockEntity} + * is within. + * + * @param packet The packet to send. + * @param tile The {@link BlockEntity} of the watched chunk to send to. + */ + public static void sendToChunk(Packet packet, BlockEntity tile) { + sendToChunk(packet, (ServerLevel) requireNonNull(tile.getLevel()), tile.getBlockPos()); + } + + /** + * Overload of {@link #sendToChunk(Packet, ServerLevel, BlockPos)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, ServerLevel level, BlockPos pos) { + sendToChunk(toClientPacket(payload), level, pos); + } + + /** + * Send the given packet to all players watching the chunk specified by the + * given {@link BlockPos} in the specified dimension. + * + * @param packet The packet to send. + * @param level The level containing the chunk to send to. + * @param pos The {@link BlockPos} specifying the chunk to send to. + */ + public static void sendToChunk(Packet packet, ServerLevel level, BlockPos pos) { + sendToChunk(packet, level, pos.getX() >> 4, pos.getZ() >> 4); + } + + /** + * Overload of {@link #sendToChunk(Packet, ServerLevel, int, int)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, ServerLevel level, int chunkX, int chunkZ) { + sendToChunk(toClientPacket(payload), level, chunkX, chunkZ); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param packet The packet to send. + * @param level The level containing the chunk to send to. + * @param chunkX The chunk X coordinate to send to. + * @param chunkZ The chunk Z coordinate to send to. + */ + public static void sendToChunk(Packet packet, ServerLevel level, int chunkX, int chunkZ) { + sendToChunk(packet, level, new ChunkPos(chunkX, chunkZ)); + } + + /** + * Overload of {@link #sendToChunk(Packet, ServerLevel, ChunkPos)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, ServerLevel level, ChunkPos pos) { + sendToChunk(toClientPacket(payload), level, pos); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param packet The packet to send. + * @param level The level containing the chunk to send to. + * @param pos The {@link ChunkPos} to send to. + */ + public static void sendToChunk(Packet packet, ServerLevel level, ChunkPos pos) { + level.getChunkSource().chunkMap.getPlayers(pos, false).forEach(e -> sendToPlayer(packet, e)); + } + + /** + * Overload of {@link #sendToOps(Packet)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToOps(CustomPacketPayload payload) { + sendToOps(toClientPacket(payload)); + } + + /** + * Send the given packet to all server operators. + * + * @param packet The packet to send. + */ + public static void sendToOps(Packet packet) { + PlayerList playerList = getCurrentServer().getPlayerList(); + ServerOpList opList = playerList.getOps(); + for (ServerPlayer player : playerList.getPlayers()) { + if (opList.get(player.getGameProfile()) != null) { + sendToPlayer(packet, player); + } + } + } + // endregion + + // region Client -> Server + + /** + * Create a server bound packet for the given custom payload. + * + * @param payload The payload. + * @return The packet. + */ + public static Packet toServerPacket(CustomPacketPayload payload) { + return new ServerboundCustomPayloadPacket(payload); + } + + /** + * Overload of {@link #sendToServer(Packet)} first wrapping {@code payload} to + * a server bound packet. + */ + public static void sendToServer(CustomPacketPayload payload) { + sendToServer(toServerPacket(payload)); + } + + /** + * Send the given packet to the server. + * + * @param packet The packet to send. + */ + public static void sendToServer(Packet packet) { + requireNonNull(Minecraft.getInstance().getConnection()).send(packet); + } + + // endregion +} diff --git a/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java b/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java index 8e9510f9..64b533c0 100644 --- a/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java @@ -26,10 +26,10 @@ protected void addHandler(int id, IClientPacketHandler handler) { } @Override - public void handlePacket(PacketCustom packet, Minecraft mc, ClientPacketListener handler) { + public void handlePacket(PacketCustom packet, Minecraft mc) { IClientPacketHandler h = handlers.get(packet.getType()); if (h != null) { - h.handlePacket(packet, mc, handler); + h.handlePacket(packet, mc); } else { LOGGER.warn("Received unknown packet on channel '{}' with descriptor '{}'.", packet.getChannel(), packet.getType()); } diff --git a/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java b/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java index 18831e58..ec6fa48b 100644 --- a/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java @@ -26,10 +26,10 @@ protected void addHandler(int id, IServerPacketHandler handler) { } @Override - public void handlePacket(PacketCustom packet, ServerPlayer sender, ServerGamePacketListenerImpl handler) { + public void handlePacket(PacketCustom packet, ServerPlayer sender) { IServerPacketHandler h = handlers.get(packet.getType()); if (h != null) { - h.handlePacket(packet, sender, handler); + h.handlePacket(packet, sender); } else { LOGGER.warn("Received unknown packet on channel '{}' with descriptor '{}'.", packet.getChannel(), packet.getType()); } diff --git a/src/main/java/codechicken/lib/packet/package-info.java b/src/main/java/codechicken/lib/packet/package-info.java new file mode 100644 index 00000000..f675488c --- /dev/null +++ b/src/main/java/codechicken/lib/packet/package-info.java @@ -0,0 +1,7 @@ +/** + * Created by covers1624 on 3/7/24. + */ +@NonNullApi +package codechicken.lib.packet; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java b/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java index 322845ad..b64a06d4 100644 --- a/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java +++ b/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java @@ -6,8 +6,7 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; - -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; /** * A VoxelShape implementation, produces a {@link VoxelShapeBlockHitResult} when ray traced. diff --git a/src/main/java/codechicken/lib/raytracer/MergedVoxelShapeHolder.java b/src/main/java/codechicken/lib/raytracer/MergedVoxelShapeHolder.java deleted file mode 100644 index 74506a86..00000000 --- a/src/main/java/codechicken/lib/raytracer/MergedVoxelShapeHolder.java +++ /dev/null @@ -1,55 +0,0 @@ -package codechicken.lib.raytracer; - -import net.minecraft.world.phys.shapes.Shapes; -import net.minecraft.world.phys.shapes.VoxelShape; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Function; - -/** - * Created by covers1624 on 3/10/20. - */ -public class MergedVoxelShapeHolder { - - private final Set shapeParts = new HashSet<>(); - private final Set partCache = new HashSet<>(); - - private VoxelShape mergedShape; - private Function extractor; - private Function postProcess; - - public MergedVoxelShapeHolder setExtractor(Function extractor) { - this.extractor = extractor; - return this; - } - - public MergedVoxelShapeHolder setPostProcessHook(Function postProcess) { - this.postProcess = postProcess; - return this; - } - - public void clear() { - shapeParts.clear(); - partCache.clear(); - mergedShape = null; - } - - public VoxelShape update(Collection things) { - partCache.clear(); - for (T thing : things) { - partCache.add(extractor.apply(thing)); - } - if (!partCache.equals(shapeParts) || mergedShape == null) { - shapeParts.clear(); - shapeParts.addAll(partCache); - //Same as VoxelShapes.or(VoxelShapes.empty(), shapeParts.toArray()); Except we skip useless array creation. - VoxelShape merged = shapeParts.stream().reduce(Shapes.empty(), Shapes::or); - mergedShape = postProcess.apply(merged); - } - - return mergedShape; - } - -} diff --git a/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java b/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java index 817e2f55..f9ebff45 100644 --- a/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java +++ b/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java @@ -6,8 +6,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; - -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; diff --git a/src/main/java/codechicken/lib/raytracer/RayTracer.java b/src/main/java/codechicken/lib/raytracer/RayTracer.java index d6c06688..2fd14b24 100644 --- a/src/main/java/codechicken/lib/raytracer/RayTracer.java +++ b/src/main/java/codechicken/lib/raytracer/RayTracer.java @@ -1,25 +1,26 @@ package codechicken.lib.raytracer; import codechicken.lib.vec.Vector3; -import net.covers1624.quack.annotation.ReplaceWith; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.ClipContext; -import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.ForgeMod; +import net.neoforged.neoforge.common.NeoForgeMod; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; public class RayTracer { + @Nullable public static BlockHitResult retraceBlock(BlockGetter level, Player player, BlockPos pos) { Vec3 startVec = getStartVec(player); Vec3 endVec = getEndVec(player); @@ -35,13 +36,16 @@ public static BlockHitResult retraceBlock(BlockGetter level, Player player, Bloc return baseTraceResult; } - private static double getBlockReachDistance_server(ServerPlayer player) { - return player.getAttribute(ForgeMod.BLOCK_REACH.get()).getValue(); + private static double getBlockReachDistance_server(Player player) { + return player.getAttributeValue(NeoForgeMod.BLOCK_REACH.value()); } - @OnlyIn (Dist.CLIENT) - private static double getBlockReachDistance_client() { - return Minecraft.getInstance().gameMode.getPickRange(); + private static double getBlockReachDistance_client(Player player) { + AttributeInstance reach = player.getAttribute(NeoForgeMod.BLOCK_REACH.value()); + if (reach != null) return reach.getValue(); + + // We may not have NeoForge on the client. + return requireNonNull(Minecraft.getInstance().gameMode).getPickRange(); } public static BlockHitResult retrace(Player player) { @@ -75,9 +79,11 @@ public static Vec3 getStartVec(Player player) { return getCorrectedHeadVec(player); } - @Deprecated // Use attribute directly? avoid all this nonsense. public static double getBlockReachDistance(Player player) { - return player.level().isClientSide ? getBlockReachDistance_client() : player instanceof ServerPlayer ? getBlockReachDistance_server((ServerPlayer) player) : 5D; + if (player instanceof ServerPlayer) return getBlockReachDistance_server(player); + if (player.level().isClientSide) return getBlockReachDistance_client(player); + // /shrug? we tried? + return 5D; } public static Vec3 getEndVec(Player player) { diff --git a/src/main/java/codechicken/lib/raytracer/package-info.java b/src/main/java/codechicken/lib/raytracer/package-info.java new file mode 100644 index 00000000..3cea5c17 --- /dev/null +++ b/src/main/java/codechicken/lib/raytracer/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.raytracer; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/BakedVertexSource.java b/src/main/java/codechicken/lib/render/BakedVertexSource.java index 65b6adc0..ef4c6749 100644 --- a/src/main/java/codechicken/lib/render/BakedVertexSource.java +++ b/src/main/java/codechicken/lib/render/BakedVertexSource.java @@ -95,14 +95,14 @@ private void onFull() { int v = vertexIndex++; Quad.Vertex vertex = unpacker.vertices[i]; Vertex5 vertex5 = vertices[v]; - vertex5.vec.set(vertex.vec); - vertex5.uv.set(vertex.uv); + vertex5.vec.set(vertex.vec()); + vertex5.uv.set(vertex.uv()); Vector3 normal = getAttr(NormalAttribute.attributeKey)[v]; - normal.set(vertex.normal); + normal.set(vertex.normal()); getAttr(LightCoordAttribute.attributeKey)[v].compute(vertex5.vec, normal); - getAttr(ColourAttribute.attributeKey)[v] = Colour.packRGBA(vertex.color); + getAttr(ColourAttribute.attributeKey)[v] = Colour.packRGBA(vertex.color()); sprites[v] = unpacker.sprite; } diff --git a/src/main/java/codechicken/lib/render/CCModel.java b/src/main/java/codechicken/lib/render/CCModel.java index 4c953e4d..a9ff032a 100644 --- a/src/main/java/codechicken/lib/render/CCModel.java +++ b/src/main/java/codechicken/lib/render/CCModel.java @@ -28,16 +28,17 @@ public class CCModel implements IVertexSource, Copyable { public Vertex5[] verts; public ArrayList attributes = new ArrayList<>(); - protected CCModel(VertexFormat.Mode vertexMode) { + protected CCModel(VertexFormat.Mode vertexMode, int numVerts) { if (vertexMode != VertexFormat.Mode.QUADS && vertexMode != VertexFormat.Mode.TRIANGLES) { throw new IllegalArgumentException("Models must be QUADS or TRIANGLES"); } this.vertexMode = vertexMode; vp = vertexMode == VertexFormat.Mode.QUADS ? 4 : 3; + verts = new Vertex5[numVerts]; } - public Vector3[] normals() { + public Vector3 @Nullable [] normals() { return getAttribute(NormalAttribute.attributeKey); } @@ -347,6 +348,8 @@ public CCModel computeNormals(int start, int length) { */ public CCModel computeLighting(LightModel light) { Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + int[] colours = getAttribute(LightingAttribute.attributeKey); if (colours == null) { colours = getOrAllocate(LightingAttribute.attributeKey); @@ -377,8 +380,10 @@ public CCModel setTex(int tex) { * @return The model */ public CCModel computeLightCoords() { - LC[] lcs = getOrAllocate(LightCoordAttribute.attributeKey); Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + + LC[] lcs = getOrAllocate(LightCoordAttribute.attributeKey); for (int i = 0; i < verts.length; i++) { lcs[i] = new LC().compute(verts[i].vec, normals[i]); } @@ -391,8 +396,10 @@ public CCModel computeLightCoords() { * @return The model */ public CCModel smoothNormals() { - ArrayList map = new ArrayList<>(); Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + + ArrayList map = new ArrayList<>(); nextvert: for (int k = 0; k < verts.length; k++) { Vector3 vec = verts[k].vec; @@ -496,14 +503,12 @@ public static CCModel triModel(int numVerts) { return newModel(VertexFormat.Mode.TRIANGLES, numVerts); } - public static CCModel newModel(VertexFormat.Mode vertexMode, int numVerts) { - CCModel model = newModel(vertexMode); - model.verts = new Vertex5[numVerts]; - return model; + public static CCModel newModel(VertexFormat.Mode vertexMode) { + return newModel(vertexMode, 0); } - public static CCModel newModel(VertexFormat.Mode vertexMode) { - return new CCModel(vertexMode); + public static CCModel newModel(VertexFormat.Mode vertexMode, int numVerts) { + return new CCModel(vertexMode, numVerts); } public static CCModel createModel(List verts, List uvs, List normals, VertexFormat.Mode vertexMode, List polys) { @@ -514,9 +519,7 @@ public static CCModel createModel(List verts, List uvs, List 0; CCModel model = CCModel.newModel(vertexMode, polys.size()); - if (hasNormals) { - model.getOrAllocate(NormalAttribute.attributeKey); - } + Vector3[] mNormals = hasNormals ? model.getOrAllocate(NormalAttribute.attributeKey) : null; for (int i = 0; i < polys.size(); i++) { int[] ai = polys.get(i); @@ -528,7 +531,7 @@ public static CCModel createModel(List verts, List uvs, List models) { - if (models.isEmpty()) { - return null; - } + if (models.isEmpty()) throw new IllegalArgumentException("Can't combine an empty collection of models."); int numVerts = 0; VertexFormat.Mode vertexMode = null; @@ -807,10 +809,12 @@ public Vector3 collapse() { } public CCModel zOffset(Cuboid6 offsets) { + Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + for (int k = 0; k < verts.length; k++) { Vertex5 vert = verts[k]; - Vector3 normal = normals()[k]; - switch (VectorUtils.findSide(normal)) { + switch (VectorUtils.findSide(normals[k])) { case 0 -> vert.vec.y += offsets.min.y; case 1 -> vert.vec.y += offsets.max.y; case 2 -> vert.vec.z += offsets.min.z; diff --git a/src/main/java/codechicken/lib/render/CCModelLibrary.java b/src/main/java/codechicken/lib/render/CCModelLibrary.java index 10327877..b3e5bc08 100644 --- a/src/main/java/codechicken/lib/render/CCModelLibrary.java +++ b/src/main/java/codechicken/lib/render/CCModelLibrary.java @@ -13,16 +13,12 @@ public class CCModelLibrary { - public static CCModel icosahedron4; - public static CCModel icosahedron7; + public static final CCModel icosahedron4; + public static final CCModel icosahedron7; private static int i; static { - generateIcosahedron(); - } - - private static void generateIcosahedron() { Vector3[] verts = new Vector3[12]; verts[0] = new Vector3(-1, phi, 0); diff --git a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java index 1f25a147..148a7844 100644 --- a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java +++ b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java @@ -1,49 +1,41 @@ package codechicken.lib.render; -import codechicken.lib.gui.modular.lib.CursorHelper; import codechicken.lib.raytracer.VoxelShapeBlockHitResult; import codechicken.lib.vec.Matrix4; +import net.covers1624.quack.util.CrashLock; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.RenderHighlightEvent; -import net.minecraftforge.client.event.ScreenEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.neoforge.client.event.RenderHighlightEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.TickEvent; public class CCRenderEventHandler { + private static final CrashLock LOCK = new CrashLock("Already Initialized"); + public static int renderTime; public static float renderFrame; - private static boolean hasInit = false; - public static void init() { - if (!hasInit) { - MinecraftForge.EVENT_BUS.register(new CCRenderEventHandler()); - hasInit = true; - } + LOCK.lock(); + NeoForge.EVENT_BUS.addListener(CCRenderEventHandler::clientTick); + NeoForge.EVENT_BUS.addListener(CCRenderEventHandler::renderTick); + NeoForge.EVENT_BUS.addListener(EventPriority.LOW, CCRenderEventHandler::onBlockHighlight); } - @SubscribeEvent - public void clientTick(TickEvent.ClientTickEvent event) { + private static void clientTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.END) { renderTime++; } } - @SubscribeEvent - public void renderTick(TickEvent.RenderTickEvent event) { + private static void renderTick(TickEvent.RenderTickEvent event) { if (event.phase == TickEvent.Phase.START) { renderFrame = event.renderTickTime; } } - @OnlyIn (Dist.CLIENT) - @SubscribeEvent (priority = EventPriority.LOW) - public void onBlockHighlight(RenderHighlightEvent.Block event) { + private static void onBlockHighlight(RenderHighlightEvent.Block event) { //We have found a CuboidRayTraceResult, Lets render it properly.. BlockHitResult hit = event.getTarget(); if (hit instanceof VoxelShapeBlockHitResult voxelHit) { diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java index 7415fd27..82dfcfd0 100644 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ b/src/main/java/codechicken/lib/render/CCRenderState.java @@ -22,18 +22,23 @@ import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidStack; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; /** * The core of the CodeChickenLib render system. * Where possible assign a local var of CCRenderState to avoid millions of calls to instance(); * Uses a ThreadLocal system to assign each thread their own CCRenderState so we can use it in Multithreaded chunk batching. - * TODO, proper piping of BakedQuads and CCBakedQuads. + *

+ * Piping Vanilla {@link BakedQuad} instances through here possible via {@link BakedVertexSource}. */ public class CCRenderState { @@ -47,14 +52,14 @@ public class CCRenderState { public final VertexAttribute lightCoordAttrib = new LightCoordAttribute(); //pipeline state - public IVertexSource model; + public @Nullable IVertexSource model; public int firstVertexIndex; public int lastVertexIndex; public int vertexIndex; public CCRenderPipeline pipeline; - public VertexConsumer r; - public VertexFormat fmt; - public CachedFormat cFmt; + public @Nullable VertexConsumer r; + public @Nullable VertexFormat fmt; + public @Nullable CachedFormat cFmt; //context /** @@ -84,7 +89,7 @@ public class CCRenderState { //attribute storage public int side; public LC lc = new LC(); - public TextureAtlasSprite sprite; + public @Nullable TextureAtlasSprite sprite; private CCRenderState() { pipeline = new CCRenderPipeline(this); @@ -232,6 +237,10 @@ public void render(IVertexOperation... ops) { } public void render() { + if (r == null) throw new IllegalStateException("VertexConsumer is not bound."); + if (fmt == null) throw new IllegalStateException("VertexFormat is not bound?"); // this should be handled by the VertexConsumer assertion. + if (model == null) throw new IllegalStateException("Model is not set."); + Vertex5[] verts = model.getVertices(); for (vertexIndex = firstVertexIndex; vertexIndex < lastVertexIndex; vertexIndex++) { model.prepareVertex(this); @@ -246,8 +255,11 @@ public void runPipeline() { } public void writeVert() { - if (r instanceof ISpriteAwareVertexConsumer) { - ((ISpriteAwareVertexConsumer) r).sprite(sprite); + assert r != null; + assert fmt != null; + assert cFmt != null; + if (sprite != null && r instanceof ISpriteAwareVertexConsumer cons) { + cons.sprite(sprite); } ImmutableList elements = fmt.getElements(); for (int e = 0; e < elements.size(); e++) { @@ -309,11 +321,11 @@ public ColourRGBA getColour() { } public VertexConsumer getConsumer() { - return r; + return requireNonNull(r, "VertexConsumer is not bound."); } public VertexFormat getVertexFormat() { - return fmt; + return requireNonNull(fmt, "VertexFormat is not bound."); } public void draw() { diff --git a/src/main/java/codechicken/lib/render/RenderUtils.java b/src/main/java/codechicken/lib/render/RenderUtils.java index bd20ff3b..cd5717cb 100644 --- a/src/main/java/codechicken/lib/render/RenderUtils.java +++ b/src/main/java/codechicken/lib/render/RenderUtils.java @@ -13,10 +13,10 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.client.ClientHooks; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; import java.util.ArrayList; import java.util.List; @@ -54,7 +54,7 @@ public static void renderFluidCuboid(CCRenderState ccrs, Matrix4 mat, RenderType bound.max.y = bound.min.y + (bound.max.y - bound.min.y) * capacity; } IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(type); - Material material = ForgeHooksClient.getBlockMaterial(props.getStillTexture(stack)); + Material material = ClientHooks.getBlockMaterial(props.getStillTexture(stack)); ccrs.bind(renderType, source); ccrs.baseColour = props.getTintColor(stack) << 8 | alpha; makeFluidModel(bound, material.sprite(), res).render(ccrs, mat); diff --git a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java b/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java index 220f71d0..82149dd3 100644 --- a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java +++ b/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java @@ -3,13 +3,13 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.BlockRenderDispatcher; import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -27,8 +27,8 @@ public class BlockRenderingRegistry { private static boolean initialized = false; - private static final Map, ICCBlockRenderer> blockRenderers = new HashMap<>(); - private static final Map, ICCBlockRenderer> fluidRenderers = new HashMap<>(); + private static final Map blockRenderers = new HashMap<>(); + private static final Map fluidRenderers = new HashMap<>(); private static final List globalRenderers = new ArrayList<>(); @OnlyIn (Dist.CLIENT) @@ -52,12 +52,11 @@ public static void init() { * @throws IllegalArgumentException If the same Block is registered twice. */ public static synchronized void registerRenderer(Block block, ICCBlockRenderer renderer) { - Holder delegate = ForgeRegistries.BLOCKS.getDelegateOrThrow(block); - ICCBlockRenderer prev = blockRenderers.get(ForgeRegistries.BLOCKS.getDelegateOrThrow(block)); + ICCBlockRenderer prev = blockRenderers.get(block); if (prev != null) { - throw new IllegalArgumentException("Renderer already registered for block. " + ForgeRegistries.BLOCKS.getKey(block)); + throw new IllegalArgumentException("Renderer already registered for block. " + BuiltInRegistries.BLOCK.getKey(block)); } - blockRenderers.put(delegate, renderer); + blockRenderers.put(block, renderer); } /** @@ -71,12 +70,11 @@ public static synchronized void registerRenderer(Block block, ICCBlockRenderer r * @throws IllegalArgumentException If the same Fluid is registered twice. */ public static synchronized void registerRenderer(Fluid fluid, ICCBlockRenderer renderer) { - Holder delegate = ForgeRegistries.FLUIDS.getDelegateOrThrow(fluid); - ICCBlockRenderer prev = blockRenderers.get(delegate); + ICCBlockRenderer prev = fluidRenderers.get(fluid); if (prev != null) { - throw new IllegalArgumentException("Renderer already registered for fluid. " + ForgeRegistries.FLUIDS.getKey(fluid)); + throw new IllegalArgumentException("Renderer already registered for fluid. " + BuiltInRegistries.FLUID.getKey(fluid)); } - fluidRenderers.put(delegate, renderer); + fluidRenderers.put(fluid, renderer); } /** @@ -97,7 +95,7 @@ static ICCBlockRenderer findFor(Block block, Predicate pred) { } } - ICCBlockRenderer found = blockRenderers.get(ForgeRegistries.BLOCKS.getDelegateOrThrow(block)); + ICCBlockRenderer found = blockRenderers.get(block); if (found != null && pred.test(found)) return found; return null; @@ -111,7 +109,7 @@ static ICCBlockRenderer findFor(Fluid fluid, Predicate pred) { } } - ICCBlockRenderer found = fluidRenderers.get(ForgeRegistries.FLUIDS.getDelegateOrThrow(fluid)); + ICCBlockRenderer found = fluidRenderers.get(fluid); if (found != null && pred.test(found)) return found; return null; diff --git a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java index 594ff821..ca2ea884 100644 --- a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java +++ b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java @@ -13,6 +13,7 @@ import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.BlockRenderDispatcher; import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.player.Player; @@ -21,16 +22,13 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.client.model.data.ModelData; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.concurrent.TimeUnit; -import static codechicken.lib.util.LambdaUtils.tryOrNull; - /** * Created by covers1624 on 8/09/2016. */ @@ -111,20 +109,19 @@ public void renderSingleBlock(BlockState blockStateIn, PoseStack matrixStackIn, } } - @SuppressWarnings ("Convert2MethodRef")//Suppress these, the lambdas need to be synthetic functions instead of a method reference. private static void handleCaughtException(Throwable t, BlockState inState, BlockPos pos, BlockAndTintGetter world) { Block inBlock = inState.getBlock(); BlockEntity tile = world.getBlockEntity(pos); StringBuilder builder = new StringBuilder("\n CCL has caught an exception whilst rendering a block\n"); builder.append(" BlockPos: ").append(String.format("x:%s, y:%s, z:%s", pos.getX(), pos.getY(), pos.getZ())).append("\n"); - builder.append(" Block Class: ").append(tryOrNull(() -> inBlock.getClass())).append("\n"); - builder.append(" Registry Name: ").append(tryOrNull(() -> ForgeRegistries.BLOCKS.getKey(inBlock))).append("\n"); + builder.append(" Block Class: ").append(inBlock.getClass()).append("\n"); + builder.append(" Registry Name: ").append(BuiltInRegistries.BLOCK.getKey(inBlock)).append("\n"); builder.append(" State: ").append(inState).append("\n"); builder.append(" Tile at position\n"); - builder.append(" Tile Class: ").append(tryOrNull(() -> tile.getClass())).append("\n"); - builder.append(" Tile Id: ").append(tryOrNull(() -> ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(tile.getType()))).append("\n"); - builder.append(" Tile NBT: ").append(tryOrNull(() -> tile.saveWithFullMetadata())).append("\n"); + builder.append(" Tile Class: ").append(tile != null ? tile.getClass() : null).append("\n"); + builder.append(" Tile Id: ").append(tile != null ? BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(tile.getType()) : null).append("\n"); + builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata() : null).append("\n"); builder.append("This functionality can be disabled in the CCL config file.\n"); if (ClientInit.messagePlayerOnRenderExceptionCaught) { builder.append("You can also turn off player messages in the CCL config file.\n"); diff --git a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java b/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java index 21a73861..a07b21a6 100644 --- a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java +++ b/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java @@ -13,7 +13,7 @@ import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; import org.jetbrains.annotations.Nullable; /** diff --git a/src/main/java/codechicken/lib/render/block/package-info.java b/src/main/java/codechicken/lib/render/block/package-info.java new file mode 100644 index 00000000..35d5040c --- /dev/null +++ b/src/main/java/codechicken/lib/render/block/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.block; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java index b72a3f1d..303f625b 100644 --- a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java +++ b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java @@ -8,6 +8,7 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; @@ -25,8 +26,8 @@ public class BakedQuadVertexBuilder implements VertexConsumer, ISpriteAwareVerte private final int vSize; private CachedFormat format; - private Colour defaultColour; - private Quad current; + private @Nullable Colour defaultColour; + private @Nullable Quad current; private int vertex; public BakedQuadVertexBuilder() { @@ -77,6 +78,7 @@ public void reset() { @Override public void sprite(TextureAtlasSprite sprite) { checkNewQuad(); + assert current != null; current.setTexture(sprite); } @@ -85,9 +87,10 @@ public VertexConsumer vertex(double x, double y, double z) { if (!format.hasPosition) return this; checkNewQuad(); - current.vertices[vertex].vec[0] = (float) x; - current.vertices[vertex].vec[1] = (float) y; - current.vertices[vertex].vec[2] = (float) z; + assert current != null; + current.vertices[vertex].vec()[0] = (float) x; + current.vertices[vertex].vec()[1] = (float) y; + current.vertices[vertex].vec()[2] = (float) z; return this; } @@ -96,10 +99,11 @@ public VertexConsumer color(int red, int green, int blue, int alpha) { if (!format.hasColor) return this; checkNewQuad(); - current.vertices[vertex].color[0] = red / 255F; - current.vertices[vertex].color[1] = green / 255F; - current.vertices[vertex].color[2] = blue / 255F; - current.vertices[vertex].color[3] = alpha / 255F; + assert current != null; + current.vertices[vertex].color()[0] = red / 255F; + current.vertices[vertex].color()[1] = green / 255F; + current.vertices[vertex].color()[2] = blue / 255F; + current.vertices[vertex].color()[3] = alpha / 255F; return this; } @@ -108,8 +112,9 @@ public VertexConsumer uv(float u, float v) { if (!format.hasUV) return this; checkNewQuad(); - current.vertices[vertex].uv[0] = u; - current.vertices[vertex].uv[1] = v; + assert current != null; + current.vertices[vertex].uv()[0] = u; + current.vertices[vertex].uv()[1] = v; return this; } @@ -118,8 +123,9 @@ public VertexConsumer overlayCoords(int u, int v) { if (!format.hasOverlay) return this; checkNewQuad(); - current.vertices[vertex].overlay[0] = u / (float) 0xF0; - current.vertices[vertex].overlay[1] = v / (float) 0xF0; + assert current != null; + current.vertices[vertex].overlay()[0] = u / (float) 0xF0; + current.vertices[vertex].overlay()[1] = v / (float) 0xF0; return this; } @@ -128,8 +134,9 @@ public VertexConsumer uv2(int u, int v) { if (!format.hasLightMap) return this; checkNewQuad(); - current.vertices[vertex].lightmap[0] = u / (float) 0xF0; - current.vertices[vertex].lightmap[1] = v / (float) 0xF0; + assert current != null; + current.vertices[vertex].lightmap()[0] = u / (float) 0xF0; + current.vertices[vertex].lightmap()[1] = v / (float) 0xF0; return this; } @@ -138,19 +145,21 @@ public VertexConsumer normal(float x, float y, float z) { if (!format.hasNormal) return this; checkNewQuad(); - current.vertices[vertex].normal[0] = x; - current.vertices[vertex].normal[1] = y; - current.vertices[vertex].normal[2] = z; + assert current != null; + current.vertices[vertex].normal()[0] = x; + current.vertices[vertex].normal()[1] = y; + current.vertices[vertex].normal()[2] = z; return this; } @Override public void endVertex() { + assert current != null; vertex++; if (vertex == vSize) { if (mode == VertexFormat.Mode.TRIANGLES) { //Quadulate. - for (int e = 0; e < current.format.elementCount; e++) { + for (int e = 0; e < current.format().elementCount; e++) { System.arraycopy(current.vertices[2].raw[e], 0, current.vertices[3].raw[e], 0, 4); } } @@ -160,7 +169,7 @@ public void endVertex() { if (defaultColour != null) { float[] colour = defaultColour.getRGBA(); for (Quad.Vertex v : current.vertices) { - System.arraycopy(colour, 0, v.color, 0, 4); + System.arraycopy(colour, 0, v.color(), 0, 4); } } quadList.add(current); diff --git a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java index 83c273c2..548a2639 100644 --- a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexSorting; +import net.covers1624.quack.util.SneakyUtils; import net.minecraft.client.renderer.RenderType; /** @@ -17,7 +18,7 @@ public DelegateRenderType(RenderType parent) { } public DelegateRenderType(RenderType parent, VertexFormat format) { - super(parent.name, format, parent.mode(), parent.bufferSize(), parent.affectsCrumbling(), parent.sortOnUpload, null, null); + super(parent.name, format, parent.mode(), parent.bufferSize(), parent.affectsCrumbling(), parent.sortOnUpload, SneakyUtils.none(), SneakyUtils.none()); this.parent = parent; } diff --git a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java index 2a021c6b..59077474 100644 --- a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.function.BiConsumer; +import static java.util.Objects.requireNonNull; import static net.covers1624.quack.util.SneakyUtils.none; /** @@ -69,7 +70,7 @@ public WithCallbacks withState(RenderStateShard shard) { private void render() { rebuild(); vertexBuffer.bind(); - vertexBuffer.drawWithShader(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), RenderSystem.getShader()); + vertexBuffer.drawWithShader(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), requireNonNull(RenderSystem.getShader())); } private void rebuild() { diff --git a/src/main/java/codechicken/lib/render/buffer/package-info.java b/src/main/java/codechicken/lib/render/buffer/package-info.java new file mode 100644 index 00000000..af5aa421 --- /dev/null +++ b/src/main/java/codechicken/lib/render/buffer/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.buffer; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/item/IItemRenderer.java b/src/main/java/codechicken/lib/render/item/IItemRenderer.java index 1c875ddd..112011a2 100644 --- a/src/main/java/codechicken/lib/render/item/IItemRenderer.java +++ b/src/main/java/codechicken/lib/render/item/IItemRenderer.java @@ -14,6 +14,7 @@ import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; @@ -34,7 +35,7 @@ public interface IItemRenderer extends PerspectiveModel { //Useless methods for IItemRenderer. //@formatter:off - @Override default List getQuads(BlockState state, Direction side, RandomSource rand) { return Collections.emptyList(); } + @Override default List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { return Collections.emptyList(); } @Override default boolean isCustomRenderer() { return true; } @Override default TextureAtlasSprite getParticleIcon() { return TextureUtils.getMissingSprite(); } @Override default ItemOverrides getOverrides() { return ItemOverrides.EMPTY; } diff --git a/src/main/java/codechicken/lib/render/item/map/package-info.java b/src/main/java/codechicken/lib/render/item/map/package-info.java new file mode 100644 index 00000000..2a862774 --- /dev/null +++ b/src/main/java/codechicken/lib/render/item/map/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.item.map; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/item/package-info.java b/src/main/java/codechicken/lib/render/item/package-info.java new file mode 100644 index 00000000..9e594b0b --- /dev/null +++ b/src/main/java/codechicken/lib/render/item/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.item; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/lighting/LC.java b/src/main/java/codechicken/lib/render/lighting/LC.java index af7d9ef2..2f13b870 100644 --- a/src/main/java/codechicken/lib/render/lighting/LC.java +++ b/src/main/java/codechicken/lib/render/lighting/LC.java @@ -47,27 +47,15 @@ public LC compute(Vector3 vec, Vector3 normal) { } public LC compute(Vector3 vec, int side) { - boolean offset = false; - switch (side) { - case 0: - offset = vec.y <= 0; - break; - case 1: - offset = vec.y >= 1; - break; - case 2: - offset = vec.z <= 0; - break; - case 3: - offset = vec.z >= 1; - break; - case 4: - offset = vec.x <= 0; - break; - case 5: - offset = vec.x >= 1; - break; - } + boolean offset = switch (side) { + case 0 -> vec.y <= 0; + case 1 -> vec.y >= 1; + case 2 -> vec.z <= 0; + case 3 -> vec.z >= 1; + case 4 -> vec.x <= 0; + case 5 -> vec.x >= 1; + default -> false; + }; if (!offset) { side += 6; } diff --git a/src/main/java/codechicken/lib/render/lighting/LightMatrix.java b/src/main/java/codechicken/lib/render/lighting/LightMatrix.java index 4746f99d..7fb58a21 100644 --- a/src/main/java/codechicken/lib/render/lighting/LightMatrix.java +++ b/src/main/java/codechicken/lib/render/lighting/LightMatrix.java @@ -8,6 +8,9 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; /** * Note that when using the class as a vertex transformer, the vertices are assumed to be within the BB (x, y, z) -> (x+1, y+1, z+1) @@ -20,7 +23,7 @@ public class LightMatrix implements IVertexOperation { public float[][] ao = new float[13][4]; public int[][] brightness = new int[13][4]; - public BlockAndTintGetter access; + public @Nullable BlockAndTintGetter access; public BlockPos pos = BlockPos.ZERO; private int sampled = 0; @@ -89,6 +92,7 @@ public void locate(BlockAndTintGetter a, BlockPos bPos) { } public void sample(int i) { + requireNonNull(access, "LightMatrix must be located first."); if ((sampled & 1 << i) == 0) { BlockPos bp = new BlockPos(pos.getX() + (i % 3) - 1, pos.getY() + (i / 9) - 1, pos.getZ() + (i / 3 % 3) - 1); BlockState b = access.getBlockState(bp); diff --git a/src/main/java/codechicken/lib/render/lighting/LightModel.java b/src/main/java/codechicken/lib/render/lighting/LightModel.java index fc2c4e85..2db5be22 100644 --- a/src/main/java/codechicken/lib/render/lighting/LightModel.java +++ b/src/main/java/codechicken/lib/render/lighting/LightModel.java @@ -9,27 +9,6 @@ public class LightModel implements IVertexOperation { public static final int operationIndex = IVertexOperation.registerOperation(); - public static class Light { - - public Vector3 ambient = new Vector3(); - public Vector3 diffuse = new Vector3(); - public Vector3 position; - - public Light(Vector3 pos) { - position = pos.copy().normalize(); - } - - public Light setDiffuse(Vector3 vec) { - diffuse.set(vec); - return this; - } - - public Light setAmbient(Vector3 vec) { - ambient.set(vec); - return this; - } - } - public static LightModel standardLightModel; static { @@ -43,8 +22,8 @@ public Light setAmbient(Vector3 vec) { //@formatter:on } - private Vector3 ambient = new Vector3(); - private Light[] lights = new Light[8]; + private final Vector3 ambient = new Vector3(); + private final Light[] lights = new Light[8]; private int lightCount; public LightModel addLight(Light light) { @@ -115,4 +94,25 @@ public PlanarLightModel reducePlanar() { } return new PlanarLightModel(colours); } + + public static class Light { + + public Vector3 ambient = new Vector3(); + public Vector3 diffuse = new Vector3(); + public Vector3 position; + + public Light(Vector3 pos) { + position = pos.copy().normalize(); + } + + public Light setDiffuse(Vector3 vec) { + diffuse.set(vec); + return this; + } + + public Light setAmbient(Vector3 vec) { + ambient.set(vec); + return this; + } + } } diff --git a/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java b/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java index 028670ab..384478a8 100644 --- a/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java +++ b/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java @@ -5,13 +5,16 @@ import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; public class PlanarLightMatrix extends PlanarLightModel { public static final int operationIndex = IVertexOperation.registerOperation(); public static PlanarLightMatrix instance = new PlanarLightMatrix(); - public BlockAndTintGetter access; + public @Nullable BlockAndTintGetter access; public BlockPos pos = BlockPos.ZERO; private int sampled = 0; @@ -29,6 +32,7 @@ public PlanarLightMatrix locate(BlockAndTintGetter a, BlockPos bPos) { } public int brightness(int side) { + requireNonNull(access, "PlanarLightMatrix must be located first."); if ((sampled & 1 << side) == 0) { brightness[side] = LevelRenderer.getLightColor(access, pos); sampled |= 1 << side; diff --git a/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java b/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java index 28cc4bab..af98ff73 100644 --- a/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java +++ b/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java @@ -6,6 +6,9 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockAndTintGetter; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; /** * Simple brightness model that only works for axis planar sides @@ -15,12 +18,11 @@ public class SimpleBrightnessModel implements IVertexOperation { public static final int operationIndex = IVertexOperation.registerOperation(); public static SimpleBrightnessModel instance = new SimpleBrightnessModel(); - public BlockAndTintGetter access; + public @Nullable BlockAndTintGetter access; public BlockPos pos = BlockPos.ZERO; private int sampled = 0; - private int[] samples = new int[6]; - private BlockPos c = BlockPos.ZERO; + private final int[] samples = new int[6]; public void locate(BlockAndTintGetter a, BlockPos bPos) { access = a; @@ -29,9 +31,9 @@ public void locate(BlockAndTintGetter a, BlockPos bPos) { } public int sample(int side) { + requireNonNull(access, "SimpleBrightnessModel must be located first."); if ((sampled & 1 << side) == 0) { - c = pos.relative(Direction.BY_3D_DATA[side]); - samples[side] = LevelRenderer.getLightColor(access, c); + samples[side] = LevelRenderer.getLightColor(access, pos.relative(Direction.BY_3D_DATA[side])); sampled |= 1 << side; } return samples[side]; diff --git a/src/main/java/codechicken/lib/render/lighting/package-info.java b/src/main/java/codechicken/lib/render/lighting/package-info.java new file mode 100644 index 00000000..9479687b --- /dev/null +++ b/src/main/java/codechicken/lib/render/lighting/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.lighting; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/model/OBJWriter.java b/src/main/java/codechicken/lib/render/model/OBJWriter.java index ce78f776..2cbd7b18 100644 --- a/src/main/java/codechicken/lib/render/model/OBJWriter.java +++ b/src/main/java/codechicken/lib/render/model/OBJWriter.java @@ -34,15 +34,16 @@ public static void exportObj(Map models, PrintWriter p) { int vStart = verts.size(); int uStart = uvs.size(); int nStart = normals.size(); - boolean hasNormals = m.normals() != null; polys.clear(); + Vector3[] mNormals = m.normals(); + boolean hasNormals = mNormals != null; for (int i = 0; i < m.verts.length; i++) { int[] ia = new int[hasNormals ? 3 : 2]; ia[0] = addIndex(verts, m.verts[i].vec); ia[1] = addIndex(uvs, m.verts[i].uv); if (hasNormals) { - ia[2] = addIndex(normals, m.normals()[i]); + ia[2] = addIndex(normals, mNormals[i]); } polys.add(ia); } diff --git a/src/main/java/codechicken/lib/render/model/package-info.java b/src/main/java/codechicken/lib/render/model/package-info.java index 9d91f4db..0c42dc1d 100644 --- a/src/main/java/codechicken/lib/render/model/package-info.java +++ b/src/main/java/codechicken/lib/render/model/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.render.model; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/package-info.java b/src/main/java/codechicken/lib/render/package-info.java new file mode 100644 index 00000000..2be7d43e --- /dev/null +++ b/src/main/java/codechicken/lib/render/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java b/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java index ee50397b..1ebc2272 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java +++ b/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java @@ -16,8 +16,8 @@ public CustomBreakingParticle(ClientLevel world, double x, double y, double z, d gravity = 1; rCol = gCol = bCol = 0.6F; quadSize /= 2.0F; - this.uo = this.random.nextFloat() * 3.0F; - this.vo = this.random.nextFloat() * 3.0F; + uo = random.nextFloat() * 3.0F; + vo = random.nextFloat() * 3.0F; } public static CustomBreakingParticle newLandingParticle(ClientLevel world, double x, double y, double z, double dx, double dy, double dz, TextureAtlasSprite icon) { @@ -33,19 +33,19 @@ public ParticleRenderType getRenderType() { } protected float getU0() { - return this.sprite.getU((double) ((this.uo + 1.0F) / 4.0F * 16.0F)); + return sprite.getU((uo + 1.0F) / 4.0F); } protected float getU1() { - return this.sprite.getU((double) (this.uo / 4.0F * 16.0F)); + return sprite.getU(uo / 4.0F); } protected float getV0() { - return this.sprite.getV((double) (this.vo / 4.0F * 16.0F)); + return sprite.getV(vo / 4.0F); } protected float getV1() { - return this.sprite.getV((double) ((this.vo + 1.0F) / 4.0F * 16.0F)); + return sprite.getV((vo + 1.0F) / 4.0F); } public void setScale(float scale) { diff --git a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java index 97282afb..e6a64071 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java +++ b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java @@ -23,10 +23,9 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientBlockExtensions; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.model.data.ModelData; import java.util.ArrayList; import java.util.List; @@ -34,6 +33,7 @@ import java.util.Set; import static codechicken.lib.internal.network.CCLNetwork.C_ADD_LANDING_EFFECTS; +import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 21/11/2016. @@ -66,7 +66,7 @@ public static boolean handleRunningEffects(Level world, BlockPos pos, BlockState BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); ParticleEngine particleManager = Minecraft.getInstance().particleEngine; List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); TextureAtlasSprite rolledSprite = sprites.get(world.random.nextInt(sprites.size())); @@ -98,7 +98,7 @@ public static boolean handleHitEffects(BlockState state, Level world, HitResult BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); Cuboid6 bounds = new Cuboid6(); if (hit instanceof VoxelShapeBlockHitResult) { bounds.set(((VoxelShapeBlockHitResult) hit).shape.bounds()); @@ -130,7 +130,7 @@ public static boolean handleDestroyEffects(Level world, BlockPos pos, BlockState BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); Cuboid6 bounds = new Cuboid6(state.getShape(world, pos).bounds()); addBlockDestroyEffects(world, bounds.add(pos), new ArrayList<>(((IModelParticleProvider) model).getDestroyEffects(state, world, pos, modelData)), manager); return true; @@ -147,7 +147,7 @@ public static void addLandingEffects(Level world, BlockPos pos, BlockState state BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); double speed = 0.15000000596046448D; diff --git a/src/main/java/codechicken/lib/render/particle/ICustomParticleBlock.java b/src/main/java/codechicken/lib/render/particle/ICustomParticleBlock.java index d2fb0a6c..767ce790 100644 --- a/src/main/java/codechicken/lib/render/particle/ICustomParticleBlock.java +++ b/src/main/java/codechicken/lib/render/particle/ICustomParticleBlock.java @@ -6,14 +6,14 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.extensions.IForgeBlock; +import net.neoforged.neoforge.common.extensions.IBlockExtension; /** * Trait like interface for adding CustomParticle support to any block, Simply implement :D *

* Created by covers1624 on 31/10/19. */ -public interface ICustomParticleBlock extends IForgeBlock { +public interface ICustomParticleBlock extends IBlockExtension { @Override default boolean addLandingEffects(BlockState state1, ServerLevel worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) { diff --git a/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java b/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java index e6f3af71..482629ca 100644 --- a/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java +++ b/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java @@ -7,9 +7,8 @@ import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; -import javax.annotation.Nonnull; import java.util.Set; /** @@ -31,7 +30,7 @@ default TextureAtlasSprite getParticleIcon() { * @param pos The pos. * @return A Set of Textures to use. */ - Set getHitEffects(@Nonnull BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData); + Set getHitEffects(BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData); /** * Used to retrieve the destroy particles for the block. diff --git a/src/main/java/codechicken/lib/render/particle/package-info.java b/src/main/java/codechicken/lib/render/particle/package-info.java new file mode 100644 index 00000000..ceb3beea --- /dev/null +++ b/src/main/java/codechicken/lib/render/particle/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.particle; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java index dd0bf217..bf444d34 100644 --- a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java +++ b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java @@ -1,6 +1,7 @@ package codechicken.lib.render.pipeline; import codechicken.lib.render.CCRenderState; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; @@ -10,8 +11,6 @@ public class CCRenderPipeline { private final CCRenderState renderState; - @Deprecated - private final PipelineBuilder builder; @Deprecated//Hack removed. public boolean forceFormatAttributes = true; @@ -20,11 +19,10 @@ public class CCRenderPipeline { private final List ops = new ArrayList<>(); private final List nodes = new ArrayList<>(); private final List sorted = new ArrayList<>(); - private PipelineNode loading; + private @Nullable PipelineNode loading; public CCRenderPipeline(CCRenderState renderState) { this.renderState = renderState; - builder = new PipelineBuilder(renderState); } public void setPipeline(IVertexOperation... ops) { @@ -52,6 +50,7 @@ public void rebuild() { unbuild(); + assert renderState.cFmt != null; if (renderState.cFmt.hasNormal) { addAttribute(renderState.normalAttrib); } @@ -76,6 +75,7 @@ public void rebuild() { for (int i = 0; i < ops.size(); i++) { IVertexOperation op = ops.get(i); loading = nodes.get(op.operationID()); + assert loading != null; boolean loaded = op.load(renderState); if (loaded) { loading.op = op; @@ -97,10 +97,12 @@ public void rebuild() { } public void addRequirement(int opRef) { + assert loading != null; loading.deps.add(nodes.get(opRef)); } public void addDependency(VertexAttribute attrib) { + assert loading != null; loading.deps.add(nodes.get(attrib.operationID())); addAttribute(attrib); } @@ -119,45 +121,10 @@ public void operate() { } } - @Deprecated - public PipelineBuilder builder() { - ops.clear(); - return builder; - } - - @Deprecated - public class PipelineBuilder { - - private final CCRenderState renderState; - - public PipelineBuilder(CCRenderState renderState) { - this.renderState = renderState; - } - - public PipelineBuilder add(IVertexOperation op) { - ops.add(op); - return this; - } - - public PipelineBuilder add(IVertexOperation... ops) { - Collections.addAll(CCRenderPipeline.this.ops, ops); - return this; - } - - public void build() { - rebuild(); - } - - public void render() { - rebuild(); - renderState.render(); - } - } - private class PipelineNode { public ArrayList deps = new ArrayList<>(); - public IVertexOperation op; + public @Nullable IVertexOperation op; public void add() { if (op == null) { diff --git a/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java b/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java index 59acee13..60252a90 100644 --- a/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java +++ b/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java @@ -19,7 +19,7 @@ public interface IVertexSource { /** * The number of vertices available in the model. - * + *

* By default, this method just returns the * length of the @link #getVertices()} array. * @@ -36,7 +36,8 @@ default int getVertexCount() { * @return The {@code T} for the given {@link AttributeKey} * or {@code null} of the Attribute does not exist. */ - @Nullable T getAttribute(AttributeKey attr); + @Nullable + T getAttribute(AttributeKey attr); /** * Returns {@code true} if the specified attribute is provided by this {@link IVertexSource}. diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java index 8508f4ca..db7b650f 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java @@ -3,6 +3,7 @@ import codechicken.lib.colour.ColourRGBA; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.VertexAttribute; +import org.jetbrains.annotations.Nullable; /** * Sets colour in CCRS to the specified colour in the model. @@ -11,7 +12,7 @@ public class ColourAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("colour", int[]::new); - private int[] colourRef; + private int @Nullable [] colourRef; public ColourAttribute() { super(attributeKey); @@ -19,6 +20,8 @@ public ColourAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + colourRef = ccrs.model.getAttribute(attributeKey); return colourRef != null || !ccrs.model.hasAttribute(attributeKey); } diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java index 2380d8b5..5aff5974 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java @@ -5,6 +5,7 @@ import codechicken.lib.render.pipeline.VertexAttribute; import codechicken.lib.vec.Transformation; import codechicken.lib.vec.Vector3; +import org.jetbrains.annotations.Nullable; /** * Uses the position of the lightmatrix to compute LC if not provided @@ -13,9 +14,9 @@ public class LightCoordAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("light_coord", LC[]::new); - private final Vector3 vec = new Vector3();//for computation + private final Vector3 vec = new Vector3(); // for computation - private LC[] lcRef; + private LC @Nullable [] lcRef; public LightCoordAttribute() { super(attributeKey); @@ -23,6 +24,8 @@ public LightCoordAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + lcRef = ccrs.model.getAttribute(attributeKey); if (ccrs.model.hasAttribute(attributeKey)) { return lcRef != null; diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java index 4bc25c90..23e337a8 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java @@ -3,6 +3,7 @@ import codechicken.lib.colour.ColourRGBA; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.VertexAttribute; +import org.jetbrains.annotations.Nullable; /** * Created by covers1624 on 10/10/2016. @@ -11,7 +12,7 @@ public class LightingAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("lighting", int[]::new); - private int[] colourRef; + private int @Nullable [] colourRef; public LightingAttribute() { super(attributeKey); @@ -19,6 +20,9 @@ public LightingAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.cFmt != null; + assert ccrs.model != null; + if (!ccrs.computeLighting || !ccrs.cFmt.hasColor || !ccrs.model.hasAttribute(attributeKey)) { return false; } @@ -33,6 +37,7 @@ public boolean load(CCRenderState ccrs) { @Override public void operate(CCRenderState ccrs) { + assert colourRef != null; ccrs.colour = ColourRGBA.multiply(ccrs.colour, colourRef[ccrs.vertexIndex]); } } diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java index 236b8963..01796d2d 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java @@ -4,6 +4,7 @@ import codechicken.lib.render.pipeline.VertexAttribute; import codechicken.lib.vec.Rotation; import codechicken.lib.vec.Vector3; +import org.jetbrains.annotations.Nullable; /** * Apples normals to the render operation. If the model is a planar model it uses known normals. @@ -12,7 +13,7 @@ public class NormalAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("normal", Vector3[]::new); - private Vector3[] normalRef; + private Vector3 @Nullable [] normalRef; public NormalAttribute() { super(attributeKey); @@ -20,6 +21,8 @@ public NormalAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + normalRef = ccrs.model.getAttribute(attributeKey); if (ccrs.model.hasAttribute(attributeKey)) { return normalRef != null; diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java index 12643206..9bc69b46 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java @@ -3,6 +3,7 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.VertexAttribute; import codechicken.lib.util.VectorUtils; +import org.jetbrains.annotations.Nullable; /** * Sets the side state in CCRS based on the provided model. If the model does not have side data it requires normals. @@ -11,7 +12,7 @@ public class SideAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("side", int[]::new); - private int[] sideRef; + private int @Nullable [] sideRef; public SideAttribute() { super(attributeKey); @@ -19,6 +20,8 @@ public SideAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + sideRef = ccrs.model.getAttribute(attributeKey); if (ccrs.model.hasAttribute(attributeKey)) { return sideRef != null; diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/package-info.java b/src/main/java/codechicken/lib/render/pipeline/attribute/package-info.java new file mode 100644 index 00000000..10e76952 --- /dev/null +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.pipeline.attribute; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/pipeline/package-info.java b/src/main/java/codechicken/lib/render/pipeline/package-info.java new file mode 100644 index 00000000..61587d81 --- /dev/null +++ b/src/main/java/codechicken/lib/render/pipeline/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.pipeline; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/shader/ShaderProgram.java b/src/main/java/codechicken/lib/render/shader/ShaderProgram.java index e4dcb223..96e278f4 100644 --- a/src/main/java/codechicken/lib/render/shader/ShaderProgram.java +++ b/src/main/java/codechicken/lib/render/shader/ShaderProgram.java @@ -1,6 +1,7 @@ package codechicken.lib.render.shader; import com.google.common.collect.ImmutableList; +import net.covers1624.quack.collection.FastStream; import net.covers1624.quack.collection.StreamableIterable; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.server.packs.resources.ReloadableResourceManager; @@ -38,8 +39,8 @@ public class ShaderProgram implements ResourceManagerReloadListener { ShaderProgram(Collection shaders, Collection uniforms, @Nullable Runnable applyCallback) { this.shaders = ImmutableList.copyOf(shaders); - this.uniforms = StreamableIterable.of(uniforms) - .toImmutableMap(UniformPair::name, e -> CCUniform.makeUniform(e.name(), e.type(), e.type().getSize(), null)); // TODO dont specify count of 1 here. + this.uniforms = FastStream.of(uniforms) + .toImmutableMap(UniformPair::name, e -> CCUniform.makeUniform(e.name(), e.type(), e.type().getSize(), null)); this.applyCallback = applyCallback; } diff --git a/src/main/java/codechicken/lib/render/shader/package-info.java b/src/main/java/codechicken/lib/render/shader/package-info.java index 34e0cfad..4dec7fc8 100644 --- a/src/main/java/codechicken/lib/render/shader/package-info.java +++ b/src/main/java/codechicken/lib/render/shader/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.render.shader; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/texture/AtlasRegistrar.java b/src/main/java/codechicken/lib/texture/AtlasRegistrar.java deleted file mode 100644 index d0e627fb..00000000 --- a/src/main/java/codechicken/lib/texture/AtlasRegistrar.java +++ /dev/null @@ -1,44 +0,0 @@ -package codechicken.lib.texture; - -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.resources.ResourceLocation; - -import java.util.function.Consumer; - -/** - * Created by covers1624 on 27/10/19. - */ -public interface AtlasRegistrar { - - /** - * Called to register a sprite and a callback for when the TextureAtlasSprite has been loaded. - * - * @param loc The sprite's ResourceLocation. - * @param onReady The callback for the sprite being ready. - */ - void registerSprite(ResourceLocation loc, Consumer onReady); - - /** - * Same as above, just takes a String for the ResourceLocation instead. - * - * @param loc The sprite's ResourceLocation. - * @param onReady The callback for the sprite being ready. - */ - default void registerSprite(String loc, Consumer onReady) { - registerSprite(new ResourceLocation(loc), onReady); - } - - /** - * Same as above, ignores callback. - * May be useful in _some_ cases. - * - * @param loc The sprite's ResourceLocation. - */ - default void registerSprite(ResourceLocation loc) { - registerSprite(loc, e -> { - }); - } - - void postRegister(Consumer func); -} diff --git a/src/main/java/codechicken/lib/texture/IIconRegister.java b/src/main/java/codechicken/lib/texture/IIconRegister.java deleted file mode 100644 index b0bb8039..00000000 --- a/src/main/java/codechicken/lib/texture/IIconRegister.java +++ /dev/null @@ -1,18 +0,0 @@ -package codechicken.lib.texture; - -/** - * Used for easy persistent TextureAtlasSprite registration. - *

- * See {@link SpriteRegistryHelper} - * Created by covers1624 on 27/10/19. - */ -public interface IIconRegister { - - /** - * Called to register your sprites to the AtlasRegistrar. - * Can be called any number of times at runtime. - * - * @param registrar - */ - void registerIcons(AtlasRegistrar registrar); -} diff --git a/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java b/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java deleted file mode 100644 index bba1a7ee..00000000 --- a/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java +++ /dev/null @@ -1,114 +0,0 @@ -//package codechicken.lib.texture; -// -//import com.google.common.collect.HashMultimap; -//import com.google.common.collect.Multimap; -//import net.minecraft.client.renderer.texture.TextureAtlas; -//import net.minecraft.client.renderer.texture.TextureAtlasSprite; -//import net.minecraft.resources.ResourceLocation; -//import net.minecraft.world.inventory.InventoryMenu; -//import net.minecraftforge.client.event.TextureStitchEvent; -//import net.minecraftforge.eventbus.api.IEventBus; -//import net.minecraftforge.eventbus.api.SubscribeEvent; -//import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -// -//import java.util.*; -//import java.util.function.Consumer; -// -///** -// * Utilities for persistent TextureAtlasSprite registration. -// *

-// * Created by covers1624 on 27/10/19. -// */ -//public class SpriteRegistryHelper { -// -// public static final ResourceLocation TEXTURES = InventoryMenu.BLOCK_ATLAS; -// // public static final ResourceLocation PARTICLE_TEXTURES = "textures/particle"; -// // public static final ResourceLocation MOB_EFFECT_TEXTURES = "textures/mob_effect"; -// // public static final ResourceLocation PAINTING_TEXTURES = "textures/painting"; -// -// private final Multimap iconRegisters = HashMultimap.create(); -// private final Map atlasRegistrars = new HashMap<>(); -// -// public SpriteRegistryHelper() { -// this(FMLJavaModLoadingContext.get().getModEventBus()); -// } -// -// public SpriteRegistryHelper(IEventBus eventBus) { -// eventBus.addListener(this::onTextureStitchPre); -// eventBus.addListener(this::onTextureStitchPost); -// } -// -// /** -// * Adds an IIconRegister for the given basePath. -// * The base path should be that returned by {@link AtlasTexture#location()} -// * Some known vanilla defaults are provided above. -// * -// * @param basePath The base path for the Atlas. -// * @param iconRegister The IIconRegister. -// */ -// public void addIIconRegister(ResourceLocation basePath, IIconRegister iconRegister) { -// iconRegisters.put(basePath, iconRegister); -// } -// -// /** -// * Adds an IIconRegister for the {@link #TEXTURES} Atlas. -// * -// * @param iconRegister The IIconRegister. -// */ -// public void addIIconRegister(IIconRegister iconRegister) { -// addIIconRegister(TEXTURES, iconRegister); -// } -// -// //######### INTERNAL -// private AtlasRegistrarImpl getRegistrar(TextureAtlas atlas) { -// AtlasRegistrarImpl registrar = atlasRegistrars.get(atlas.location()); -// if (registrar == null) { -// registrar = new AtlasRegistrarImpl(); -// atlasRegistrars.put(atlas.location(), registrar); -// } -// return registrar; -// } -// -// private void onTextureStitchPre(TextureStitchEvent.Pre event) { -// TextureAtlas atlas = event.getAtlas(); -// AtlasRegistrarImpl registrar = getRegistrar(atlas); -// iconRegisters.get(atlas.location()).forEach(e -> e.registerIcons(registrar)); -// registrar.processPre(event::addSprite); -// } -// -// private void onTextureStitchPost(TextureStitchEvent.Post event) { -// TextureAtlas atlas = event.getAtlas(); -// AtlasRegistrarImpl registrar = getRegistrar(atlas); -// registrar.processPost(atlas); -// } -// -// private static final class AtlasRegistrarImpl implements AtlasRegistrar { -// -// private final Multimap> sprites = HashMultimap.create(); -// private final List> postCallbacks = new ArrayList<>(); -// -// @Override -// public void registerSprite(ResourceLocation loc, Consumer onReady) { -// sprites.put(loc, onReady); -// } -// -// @Override -// public void postRegister(Consumer func) { -// postCallbacks.add(func); -// } -// -// private void processPre(Consumer register) { -// sprites.keySet().forEach(register); -// } -// -// private void processPost(TextureAtlas atlas) { -// for (Map.Entry>> entry : sprites.asMap().entrySet()) { -// TextureAtlasSprite sprite = atlas.getSprite(entry.getKey()); -// entry.getValue().forEach(e -> e.accept(sprite)); -// } -// for (Consumer callback : postCallbacks) { -// callback.accept(atlas); -// } -// } -// } -//} diff --git a/src/main/java/codechicken/lib/texture/TextureUtils.java b/src/main/java/codechicken/lib/texture/TextureUtils.java index cae7d73a..ee81c516 100644 --- a/src/main/java/codechicken/lib/texture/TextureUtils.java +++ b/src/main/java/codechicken/lib/texture/TextureUtils.java @@ -5,17 +5,15 @@ import codechicken.lib.util.ResourceUtils; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; import net.minecraft.world.inventory.InventoryMenu; -import net.minecraft.world.level.block.state.BlockState; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -23,11 +21,11 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; -import java.util.List; -import java.util.Random; public class TextureUtils { + private static final Logger LOGGER = LogManager.getLogger(); + /** * @return an array of ARGB pixel data */ @@ -52,12 +50,11 @@ public static Colour[] loadTextureColours(ResourceLocation resource) { return data; } - public static BufferedImage loadBufferedImage(ResourceLocation textureFile) { + public static @Nullable BufferedImage loadBufferedImage(ResourceLocation textureFile) { try { return loadBufferedImage(ResourceUtils.getResourceAsStream(textureFile)); - } catch (Exception e) { - System.err.println("Failed to load texture file: " + textureFile); - e.printStackTrace(); + } catch (Exception ex) { + LOGGER.error("failed to load texture {}", textureFile, ex); } return null; } @@ -79,25 +76,6 @@ public static void copySubImg(int[] fromTex, int fromWidth, int fromX, int fromY } } - public static void prepareTexture(int target, int texture, int min_mag_filter, int wrap) { - GlStateManager._texParameter(target, GL11.GL_TEXTURE_MIN_FILTER, min_mag_filter); - GlStateManager._texParameter(target, GL11.GL_TEXTURE_MAG_FILTER, min_mag_filter); - if (target == GL11.GL_TEXTURE_2D) { - GlStateManager._bindTexture(target); - } else { - GL11.glBindTexture(target, texture); - } - - switch (target) { - case GL12.GL_TEXTURE_3D: - GlStateManager._texParameter(target, GL12.GL_TEXTURE_WRAP_R, wrap); - case GL11.GL_TEXTURE_2D: - GlStateManager._texParameter(target, GL11.GL_TEXTURE_WRAP_T, wrap); - case GL11.GL_TEXTURE_1D: - GlStateManager._texParameter(target, GL11.GL_TEXTURE_WRAP_S, wrap); - } - } - public static TextureManager getTextureManager() { return Minecraft.getInstance().getTextureManager(); } @@ -133,50 +111,4 @@ public static TextureAtlasSprite getItemTexture(String string) { public static TextureAtlasSprite getItemTexture(ResourceLocation location) { return getTexture(new ResourceLocation(location.getNamespace(), "items/" + location.getPath())); } - - @Deprecated - public static TextureAtlasSprite[] getSideIconsForBlock(BlockState state) { - TextureAtlasSprite[] sideSprites = new TextureAtlasSprite[6]; - TextureAtlasSprite missingSprite = getMissingSprite(); - for (int i = 0; i < 6; i++) { - TextureAtlasSprite[] sprites = getIconsForBlock(state, i); - TextureAtlasSprite sideSprite = missingSprite; - if (sprites.length != 0) { - sideSprite = sprites[0]; - } - sideSprites[i] = sideSprite; - } - return sideSprites; - } - - @Deprecated - public static TextureAtlasSprite[] getIconsForBlock(BlockState state, int side) { - return getIconsForBlock(state, Direction.values()[side]); - } - - @Deprecated - public static TextureAtlasSprite[] getIconsForBlock(BlockState state, Direction side) { - BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state); - if (model != null) { - List quads = model.getQuads(state, side, RandomSource.create(0)); - if (quads != null && quads.size() > 0) { - TextureAtlasSprite[] sprites = new TextureAtlasSprite[quads.size()]; - for (int i = 0; i < quads.size(); i++) { - sprites[i] = quads.get(i).getSprite(); - } - return sprites; - } - } - return new TextureAtlasSprite[0]; - } - - @Deprecated - public static TextureAtlasSprite getParticleIconForBlock(BlockState state) { - BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state); - if (model != null) { - return model.getParticleIcon(); - } - return null; - } - } diff --git a/src/main/java/codechicken/lib/texture/package-info.java b/src/main/java/codechicken/lib/texture/package-info.java new file mode 100644 index 00000000..7a9a871d --- /dev/null +++ b/src/main/java/codechicken/lib/texture/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.texture; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/util/ArrayUtils.java b/src/main/java/codechicken/lib/util/ArrayUtils.java index f97717f1..dc6bc67f 100644 --- a/src/main/java/codechicken/lib/util/ArrayUtils.java +++ b/src/main/java/codechicken/lib/util/ArrayUtils.java @@ -1,5 +1,7 @@ package codechicken.lib.util; +import org.jetbrains.annotations.Nullable; + import java.lang.reflect.Array; import java.util.*; import java.util.function.Function; @@ -253,7 +255,7 @@ public static void arrayCopy(Object src, int srcPos, Object dst, int destPos, in * @param What we are dealing with. * @return The index in the array of the object. */ - public static int indexOf(T[] array, T object) { + public static int indexOf(T[] array, @Nullable T object) { if (object == null) { for (int i = 0; i < array.length; i++) { if (array[i] == null) { @@ -366,7 +368,7 @@ public static T[] rollArray(T[] input, int shift) { * @param The thing. * @return If the element exists at all. */ - public static boolean contains(T[] input, T element) { + public static boolean contains(T[] input, @Nullable T element) { for (T test : input) { if (Objects.equals(test, element)) { return true; @@ -403,7 +405,7 @@ public static T[] inverse(T[] input, T[] allElements) { * @param The thing. * @return If the array is null or contains null. */ - public static boolean isNullOrContainsNull(T[] input) { + public static boolean isNullOrContainsNull(T @Nullable [] input) { if (input != null) { for (T t : input) { if (t == null) { diff --git a/src/main/java/codechicken/lib/util/Boolean2ObjectFunction.java b/src/main/java/codechicken/lib/util/Boolean2ObjectFunction.java deleted file mode 100644 index a7d07a6f..00000000 --- a/src/main/java/codechicken/lib/util/Boolean2ObjectFunction.java +++ /dev/null @@ -1,17 +0,0 @@ -package codechicken.lib.util; - -import java.util.function.Function; - -/** - * Created by covers1624 on 3/17/20. - */ -public interface Boolean2ObjectFunction extends Function { - - R apply(boolean t); - - @Override - @Deprecated - default R apply(Boolean t) { - return apply(t.booleanValue()); - } -} diff --git a/src/main/java/codechicken/lib/util/ClientUtils.java b/src/main/java/codechicken/lib/util/ClientUtils.java index 7f8f87ae..c9e15ccc 100644 --- a/src/main/java/codechicken/lib/util/ClientUtils.java +++ b/src/main/java/codechicken/lib/util/ClientUtils.java @@ -2,14 +2,8 @@ import codechicken.lib.render.CCRenderEventHandler; import net.minecraft.client.Minecraft; -import net.minecraft.network.Connection; -import net.minecraft.world.level.Level; -public class ClientUtils extends CommonUtils { - - public static Level getWorld() { - return Minecraft.getInstance().level; - } +public class ClientUtils { public static boolean inWorld() { return Minecraft.getInstance().getConnection() != null; @@ -22,17 +16,4 @@ public static float getRenderFrame() { public static double getRenderTime() { return CCRenderEventHandler.renderTime + getRenderFrame(); } - - public static String getServerIP() { - try { - Connection networkManager = Minecraft.getInstance().getConnection().getConnection(); - String s = networkManager.getRemoteAddress().toString(); - s = s.substring(s.indexOf("/") + 1); - return s; - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - } } diff --git a/src/main/java/codechicken/lib/util/CommonUtils.java b/src/main/java/codechicken/lib/util/CommonUtils.java deleted file mode 100644 index 7d255ae0..00000000 --- a/src/main/java/codechicken/lib/util/CommonUtils.java +++ /dev/null @@ -1,14 +0,0 @@ -package codechicken.lib.util; - -import net.minecraft.world.level.Level; - -public class CommonUtils { - - public static boolean isClientWorld(Level world) { - return world.isClientSide; - } - - public static boolean isServerWorld(Level world) { - return !world.isClientSide; - } -} diff --git a/src/main/java/codechicken/lib/util/FormatUtil.java b/src/main/java/codechicken/lib/util/FormatUtil.java index e3395419..5a0100aa 100644 --- a/src/main/java/codechicken/lib/util/FormatUtil.java +++ b/src/main/java/codechicken/lib/util/FormatUtil.java @@ -13,21 +13,21 @@ public class FormatUtil { public static String formatNumber(double value) { if (Math.abs(value) < 1000D) return String.valueOf(value); - else if (Math.abs(value) < 1000000D) return addCommas((int) value); //I mean whats the point of displaying 1.235K instead of 1,235? - else if (Math.abs(value) < 1000000000D) return Math.round(value / 1000D) / 1000D + "M"; - else if (Math.abs(value) < 1000000000000D) return Math.round(value / 1000000D) / 1000D + "G"; - else return Math.round(value / 1000000000D) / 1000D + "T"; + if (Math.abs(value) < 1000000D) return addCommas((int) value); //I mean whats the point of displaying 1.235K instead of 1,235? + if (Math.abs(value) < 1000000000D) return Math.round(value / 1000D) / 1000D + "M"; + if (Math.abs(value) < 1000000000000D) return Math.round(value / 1000000D) / 1000D + "G"; + return Math.round(value / 1000000000D) / 1000D + "T"; } public static String formatNumber(long value) { if (value == Long.MIN_VALUE) value = Long.MAX_VALUE; if (Math.abs(value) < 1000L) return String.valueOf(value); - else if (Math.abs(value) < 1000000L) return addCommas(value); - else if (Math.abs(value) < 1000000000L) return Math.round((double)(value / 100000L)) / 10D + "M"; - else if (Math.abs(value) < 1000000000000L) return Math.round((double)(value / 100000000L)) / 10D + "G"; - else if (Math.abs(value) < 1000000000000000L) return Math.round((double)(value / 1000000000L)) / 1000D + "T"; - else if (Math.abs(value) < 1000000000000000000L) return Math.round((double)(value / 1000000000000L)) / 1000D + "P"; - else return Math.round((double) (value / 1000000000000000L)) / 1000D + "E"; + if (Math.abs(value) < 1000000L) return addCommas(value); + if (Math.abs(value) < 1000000000L) return Math.round((double) (value / 100000L)) / 10D + "M"; + if (Math.abs(value) < 1000000000000L) return Math.round((double) (value / 100000000L)) / 10D + "G"; + if (Math.abs(value) < 1000000000000000L) return Math.round((double) (value / 1000000000L)) / 1000D + "T"; + if (Math.abs(value) < 1000000000000000000L) return Math.round((double) (value / 1000000000000L)) / 1000D + "P"; + return Math.round((double) (value / 1000000000000000L)) / 1000D + "E"; } /** diff --git a/src/main/java/codechicken/lib/util/ItemUtils.java b/src/main/java/codechicken/lib/util/ItemUtils.java index ec8443fa..0966278c 100644 --- a/src/main/java/codechicken/lib/util/ItemUtils.java +++ b/src/main/java/codechicken/lib/util/ItemUtils.java @@ -14,9 +14,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import javax.annotation.Nonnull; import java.util.List; -import java.util.Set; import java.util.function.Predicate; /** @@ -40,7 +38,6 @@ public static boolean isPlayerHoldingSomething(Player player) { return !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); } - @Nonnull public static ItemStack getHeldStack(Player player) { ItemStack stack = player.getMainHandItem(); if (stack.isEmpty()) { @@ -66,7 +63,7 @@ public static void dropItem(ItemStack stack, Level level, Vector3 dropLocation) * @param stack ItemStack to drop. * @param velocity The velocity to add. */ - public static void dropItem(Level world, BlockPos pos, @Nonnull ItemStack stack, double velocity) { + public static void dropItem(Level world, BlockPos pos, ItemStack stack, double velocity) { double xVelocity = world.random.nextFloat() * velocity + (1.0D - velocity) * 0.5D; double yVelocity = world.random.nextFloat() * velocity + (1.0D - velocity) * 0.5D; double zVelocity = world.random.nextFloat() * velocity + (1.0D - velocity) * 0.5D; @@ -82,7 +79,7 @@ public static void dropItem(Level world, BlockPos pos, @Nonnull ItemStack stack, * @param pos Location to drop item. * @param stack ItemStack to drop. */ - public static void dropItem(Level world, BlockPos pos, @Nonnull ItemStack stack) { + public static void dropItem(Level world, BlockPos pos, ItemStack stack) { dropItem(world, pos, stack, 0.7D); } @@ -109,7 +106,7 @@ public static void dropInventory(Level world, BlockPos pos, Container inventory) * @param quantity Size of the new stack. * @return The new stack. */ - public static ItemStack copyStack(@Nonnull ItemStack stack, int quantity) { + public static ItemStack copyStack(ItemStack stack, int quantity) { if (stack.isEmpty()) { return ItemStack.EMPTY; } @@ -127,7 +124,7 @@ public static ItemStack copyStack(@Nonnull ItemStack stack, int quantity) { * @param stack Stack to spawn. * @param dir Direction to shoot. */ - public static void ejectItem(Level world, BlockPos pos, @Nonnull ItemStack stack, Direction dir) { + public static void ejectItem(Level world, BlockPos pos, ItemStack stack, Direction dir) { pos.relative(dir); ItemEntity entity = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, stack); entity.setDeltaMovement(Vec3.atLowerCornerOf(dir.getNormal()).scale(0.3)); @@ -156,7 +153,7 @@ public static void ejectItems(Level world, BlockPos pos, List stacks, * @param stack2 Second Stack. * @return Returns the difference. */ - public static int compareItemStack(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { + public static int compareItemStack(ItemStack stack1, ItemStack stack2) { int itemStack1ID = Item.getId(stack1.getItem()); int itemStack2ID = Item.getId(stack2.getItem()); return itemStack1ID != itemStack2ID ? itemStack1ID - itemStack2ID : (stack1.getDamageValue() == stack2.getDamageValue() ? 0 : stack1.getDamageValue() - stack2.getDamageValue()); @@ -167,7 +164,7 @@ public static int compareItemStack(@Nonnull ItemStack stack1, @Nonnull ItemStack * @param stack2 The {@link ItemStack} to compare to. * @return whether the two items are the same in terms of damage and itemID. */ - public static boolean areStacksSameType(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { + public static boolean areStacksSameType(ItemStack stack1, ItemStack stack2) { return !stack1.isEmpty() && !stack2.isEmpty() && (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameTags(stack2, stack1)); } } diff --git a/src/main/java/codechicken/lib/util/LambdaUtils.java b/src/main/java/codechicken/lib/util/LambdaUtils.java deleted file mode 100644 index 7870ea79..00000000 --- a/src/main/java/codechicken/lib/util/LambdaUtils.java +++ /dev/null @@ -1,89 +0,0 @@ -package codechicken.lib.util; - -import net.covers1624.quack.util.SneakyUtils.ThrowingRunnable; - -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; - -/** - * Basically a bunch of lambda helpers. - *

- * Created by covers1624 on 1/06/2017. - */ -public class LambdaUtils { - - /** - * Tests if a predicate holds for all elements of the iterable. - * - * @param iterable The iterable to test. - * @param predicate The predicate. - * @param What we are dealing with. - * @return True if the predicate holds for all elements in the iterable. - */ - //TODO Rename. forAll - public static boolean forEach(Iterable iterable, Predicate predicate) { - for (T e : iterable) { - if (!predicate.test(e)) { - return false; - } - } - return true; - } - - /** - * For Each Array lambda support. Because reasons. - * - * @param elements What to loop. - * @param consumer Lambda. - * @param The thing! - */ - public static void forEach(E[] elements, Consumer consumer) { - for (E element : elements) { - consumer.accept(element); - } - } - - /** - * Provides a predicate callback for checking a condition. - * - * @param argument The thing we are checking. - * @param log What the reason for the predicate failing is. - * @param predicate The predicate callback. - * @param The thing. - */ - public static void checkArgument(E argument, String log, Predicate predicate) { - if (predicate.test(argument)) { - throw new RuntimeException("Argument check failed! Reason: " + log); - } - } - - /** - * Try's the operation quietly, disposing of any exception thrown. - * Useful for things where you literally don't care what the result is. - * - * @param runnable The thing to run. - */ - public static void tryQuietly(ThrowingRunnable runnable) { - try { - runnable.run(); - } catch (Throwable ignored) { - //pokemon - } - } - - /** - * Attempts to run the supplier, returns null on an exception. - * - * @param supplier The supplier to run. - * @param The Generic type. - * @return The thing from the supplier. - */ - public static T tryOrNull(Supplier supplier) { - try { - return supplier.get(); - } catch (Throwable t) { - return null; - } - } -} diff --git a/src/main/java/codechicken/lib/util/LazyValuePair.java b/src/main/java/codechicken/lib/util/LazyValuePair.java deleted file mode 100644 index 928ab8d5..00000000 --- a/src/main/java/codechicken/lib/util/LazyValuePair.java +++ /dev/null @@ -1,39 +0,0 @@ -package codechicken.lib.util; - -import net.minecraft.util.LazyLoadedValue; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.function.Function; - -/** - * Created by covers1624 on 5/1/20. - */ -public class LazyValuePair extends Pair { - - private final K key; - private final LazyLoadedValue value; - - public LazyValuePair(K key, Function func) { - this.key = key; - value = new LazyLoadedValue<>(() -> func.apply(key)); - } - - public static LazyValuePair of(K key, Function func) { - return new LazyValuePair<>(key, func); - } - - @Override - public K getLeft() { - return key; - } - - @Override - public V getRight() { - return value.get(); - } - - @Override - public V setValue(V value) { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/codechicken/lib/util/LogUtils.java b/src/main/java/codechicken/lib/util/LogUtils.java deleted file mode 100644 index 7f05d060..00000000 --- a/src/main/java/codechicken/lib/util/LogUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -package codechicken.lib.util; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.HashSet; -import java.util.Set; - -/** - * Utils for logging things. - *

- * Created by covers1624 on 20/06/2017. - */ -public class LogUtils { - - private static final Set stackTraces = new HashSet<>(); - - public static synchronized void errorOnce(Logger logger, Throwable t, String identifier, String format, Object... data) { - StringWriter sw = new StringWriter(); - t.printStackTrace(new PrintWriter(sw)); - String stackTrace = identifier + sw.toString(); - synchronized (stackTraces) { - if (!stackTraces.contains(stackTrace)) { - logger.log(Level.ERROR, format, data, t); - stackTraces.add(stackTrace); - } - } - } -} diff --git a/src/main/java/codechicken/lib/util/RotationUtils.java b/src/main/java/codechicken/lib/util/RotationUtils.java index b94cb9ea..062d307f 100644 --- a/src/main/java/codechicken/lib/util/RotationUtils.java +++ b/src/main/java/codechicken/lib/util/RotationUtils.java @@ -69,18 +69,13 @@ public static Direction getPlacedRotation(BlockPos pos, LivingEntity entity, boo * @return Next facing. */ public static Direction rotateCounterClockwise(Direction facing) { - switch (facing) { - case NORTH: - return Direction.WEST; - case EAST: - return Direction.NORTH; - case SOUTH: - return Direction.EAST; - case WEST: - return Direction.SOUTH; - default: - throw new IllegalStateException("Unable to get CCW facing of " + facing); - } + return switch (facing) { + case NORTH -> Direction.WEST; + case EAST -> Direction.NORTH; + case SOUTH -> Direction.EAST; + case WEST -> Direction.SOUTH; + default -> throw new IllegalStateException("Unable to get CCW facing of " + facing); + }; } /** @@ -90,18 +85,13 @@ public static Direction rotateCounterClockwise(Direction facing) { * @return Next facing. */ public static Direction rotateClockwise(Direction facing) { - switch (facing) { - case NORTH: - return Direction.EAST; - case EAST: - return Direction.SOUTH; - case SOUTH: - return Direction.WEST; - case WEST: - return Direction.NORTH; - default: - throw new IllegalStateException("Unable to get CW facing of " + facing); - } + return switch (facing) { + case NORTH -> Direction.EAST; + case EAST -> Direction.SOUTH; + case SOUTH -> Direction.WEST; + case WEST -> Direction.NORTH; + default -> throw new IllegalStateException("Unable to get CW facing of " + facing); + }; } /** @@ -111,21 +101,14 @@ public static Direction rotateClockwise(Direction facing) { * @return Next facing. */ public static Direction rotateForward(Direction facing) { - switch (facing) { - case NORTH: - return Direction.DOWN; - case DOWN: - return Direction.UP; - case UP: - return Direction.WEST; - case WEST: - return Direction.EAST; - case EAST: - return Direction.SOUTH; - case SOUTH: - return Direction.NORTH; - } - return Direction.NORTH; + return switch (facing) { + case NORTH -> Direction.DOWN; + case DOWN -> Direction.UP; + case UP -> Direction.WEST; + case WEST -> Direction.EAST; + case EAST -> Direction.SOUTH; + case SOUTH -> Direction.NORTH; + }; } /** @@ -135,21 +118,14 @@ public static Direction rotateForward(Direction facing) { * @return Next facing. */ public static Direction rotateBackwards(Direction facing) { - switch (facing) { - case NORTH: - return Direction.SOUTH; - case SOUTH: - return Direction.EAST; - case EAST: - return Direction.WEST; - case WEST: - return Direction.UP; - case UP: - return Direction.DOWN; - case DOWN: - return Direction.NORTH; - } - return Direction.NORTH; + return switch (facing) { + case NORTH -> Direction.SOUTH; + case SOUTH -> Direction.EAST; + case EAST -> Direction.WEST; + case WEST -> Direction.UP; + case UP -> Direction.DOWN; + case DOWN -> Direction.NORTH; + }; } /** @@ -159,16 +135,12 @@ public static Direction rotateBackwards(Direction facing) { * @return The rotation in Direction. */ public static Direction entityRotationToSide(int rotation) { - switch (rotation) { - case 0: - return Direction.SOUTH; - case 1: - return Direction.WEST; - case 2: - return Direction.NORTH; - default: - return Direction.EAST; - } + return switch (rotation) { + case 0 -> Direction.SOUTH; + case 1 -> Direction.WEST; + case 2 -> Direction.NORTH; + default -> Direction.EAST; + }; } } diff --git a/src/main/java/codechicken/lib/util/ServerUtils.java b/src/main/java/codechicken/lib/util/ServerUtils.java index 94c75e05..f5b31b77 100644 --- a/src/main/java/codechicken/lib/util/ServerUtils.java +++ b/src/main/java/codechicken/lib/util/ServerUtils.java @@ -3,83 +3,34 @@ import codechicken.lib.data.MCDataOutput; import codechicken.lib.internal.network.CCLNetwork; import codechicken.lib.packet.PacketCustom; -import com.mojang.authlib.GameProfile; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceKey; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.players.GameProfileCache; import net.minecraft.world.MenuProvider; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.LogicalSidedProvider; -import net.minecraftforge.event.entity.player.PlayerContainerEvent; -import net.minecraftforge.fml.LogicalSide; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.entity.player.PlayerContainerEvent; +import net.neoforged.neoforge.server.ServerLifecycleHooks; import java.nio.file.Path; -import java.util.List; -import java.util.Locale; -import java.util.UUID; import java.util.function.Consumer; import static codechicken.lib.internal.network.CCLNetwork.C_OPEN_CONTAINER; +import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 22/10/2016. */ public class ServerUtils { - @Deprecated - public static MinecraftServer getServer() { - return (MinecraftServer) LogicalSidedProvider.WORKQUEUE.get(LogicalSide.SERVER); - } - - @Deprecated - public static ServerPlayer getPlayer(String playername) { - return getServer().getPlayerList().getPlayerByName(playername); - } - - public static List getPlayers() { - return getServer().getPlayerList().getPlayers(); - } - public static Path getSaveDirectory() { return getSaveDirectory(Level.OVERWORLD); } public static Path getSaveDirectory(ResourceKey dimension) { - return getServer().storageSource.getDimensionPath(dimension); - } - - public static GameProfile getGameProfile(String username) { - Player player = getPlayer(username); - if (player != null) { - return player.getGameProfile(); - } - - //try and access it in the cache without forcing a save - username = username.toLowerCase(Locale.ROOT); - GameProfileCache.GameProfileInfo cachedEntry = getServer().getProfileCache().profilesByName.get(username); - if (cachedEntry != null) { - return cachedEntry.getProfile(); - } - - //load it from the cache - return getServer().getProfileCache().get(username).orElse(null); - } - - public static boolean isPlayerOP(UUID uuid) { - GameProfile profile = getServer().getProfileCache().get(uuid).orElse(null); - return profile != null && getServer().getPlayerList().isOp(profile); - } - - public static boolean isPlayerOP(String username) { - GameProfile prof = getGameProfile(username); - return prof != null && getServer().getPlayerList().isOp(prof); + return ServerLifecycleHooks.getCurrentServer().storageSource.getDimensionPath(dimension); } public static void openContainer(ServerPlayer player, MenuProvider containerProvider) { @@ -96,10 +47,10 @@ public static void openContainer(ServerPlayer player, MenuProvider containerProv int containerId = player.containerCounter; AbstractContainerMenu container = containerProvider.createMenu(containerId, player.getInventory(), player); - MenuType type = container.getType(); + MenuType type = requireNonNull(container).getType(); PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_OPEN_CONTAINER); - packet.writeRegistryIdDirect(ForgeRegistries.MENU_TYPES, type); + packet.writeRegistryIdDirect(BuiltInRegistries.MENU, type); packet.writeVarInt(containerId); packet.writeTextComponent(containerProvider.getDisplayName()); packetConsumer.accept(packet); @@ -107,6 +58,6 @@ public static void openContainer(ServerPlayer player, MenuProvider containerProv packet.sendToPlayer(player); player.containerMenu = container; player.initMenu(player.containerMenu); - MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, container)); + NeoForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, container)); } } diff --git a/src/main/java/codechicken/lib/util/ThrowingBiConsumer.java b/src/main/java/codechicken/lib/util/ThrowingBiConsumer.java deleted file mode 100644 index cff9d877..00000000 --- a/src/main/java/codechicken/lib/util/ThrowingBiConsumer.java +++ /dev/null @@ -1,12 +0,0 @@ -package codechicken.lib.util; - -/** - * A simple BiConsumer that has a throws declaration. - *

- * Created by covers1624 on 15/06/18. - */ -@FunctionalInterface -public interface ThrowingBiConsumer { - - void accept(A a, B b) throws E; -} diff --git a/src/main/java/codechicken/lib/util/TransformUtils.java b/src/main/java/codechicken/lib/util/TransformUtils.java index 2fc32062..abab10f3 100644 --- a/src/main/java/codechicken/lib/util/TransformUtils.java +++ b/src/main/java/codechicken/lib/util/TransformUtils.java @@ -4,14 +4,11 @@ import codechicken.lib.model.PerspectiveModelState; import codechicken.lib.vec.Vector3; import com.google.common.collect.ImmutableMap; -import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Transformation; import net.minecraft.client.renderer.block.model.ItemTransform; import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.resources.model.ModelState; import net.minecraft.world.item.ItemDisplayContext; -import org.joml.Matrix3f; -import org.joml.Matrix4f; import org.joml.Quaternionf; import org.joml.Vector3f; @@ -170,25 +167,4 @@ public static ModelState stateFromItemTransforms(ItemTransforms itemTransforms) return new PerspectiveModelState(map.build()); } - - /** - * Applies standard lefty flip to a {@link PoseStack}. - * - * @param pStack The {@link PoseStack} to apply to. - */ - @Deprecated (forRemoval = true) - public static void applyLeftyFlip(PoseStack pStack) { - if (!pStack.clear()) { - Matrix4f tMat = pStack.last().pose(); - Matrix3f nMat = pStack.last().normal(); - - tMat.mulLocal(flipX.getMatrix()); - tMat.mul(flipX.getMatrix()); - nMat.mulLocal(flipX.getNormalMatrix()); - nMat.mul(flipX.getNormalMatrix()); - - pStack.last().pose().mul(tMat); - pStack.last().normal().mul(nMat); - } - } } diff --git a/src/main/java/codechicken/lib/util/VectorUtils.java b/src/main/java/codechicken/lib/util/VectorUtils.java index 3272ac28..95b09254 100644 --- a/src/main/java/codechicken/lib/util/VectorUtils.java +++ b/src/main/java/codechicken/lib/util/VectorUtils.java @@ -2,6 +2,7 @@ import codechicken.lib.vec.Vector3; import net.minecraft.core.Direction; +import org.jetbrains.annotations.Nullable; /** * Created by covers1624 on 4/10/2016. @@ -27,25 +28,10 @@ public static Vector3 calculateNormal(Vector3... vertices) { * @return The direction the normal is facing. */ public static int findSide(Vector3 normal) { - if (normal.y <= -0.99) { - return 0; - } - if (normal.y >= 0.99) { - return 1; - } - if (normal.z <= -0.99) { - return 2; - } - if (normal.z >= 0.99) { - return 3; - } - if (normal.x <= -0.99) { - return 4; - } - if (normal.x >= 0.99) { - return 5; - } - return -1; + Direction dir = findSideE(normal); + if (dir == null) return -1; + + return dir.ordinal(); } /** @@ -54,25 +40,14 @@ public static int findSide(Vector3 normal) { * @param normal The normal to calculate from. * @return The direction the normal is facing. */ - public static Direction calcNormalSide(Vector3 normal) { - if (normal.y <= -0.99) { - return Direction.DOWN; - } - if (normal.y >= 0.99) { - return Direction.UP; - } - if (normal.z <= -0.99) { - return Direction.NORTH; - } - if (normal.z >= 0.99) { - return Direction.SOUTH; - } - if (normal.x <= -0.99) { - return Direction.WEST; - } - if (normal.x >= 0.99) { - return Direction.EAST; - } + public static @Nullable Direction findSideE(Vector3 normal) { + if (normal.y <= -0.99) return Direction.DOWN; + if (normal.y >= 0.99) return Direction.UP; + if (normal.z <= -0.99) return Direction.NORTH; + if (normal.z >= 0.99) return Direction.SOUTH; + if (normal.x <= -0.99) return Direction.WEST; + if (normal.x >= 0.99) return Direction.EAST; + return null; } } diff --git a/src/main/java/codechicken/lib/util/package-info.java b/src/main/java/codechicken/lib/util/package-info.java new file mode 100644 index 00000000..4d81d344 --- /dev/null +++ b/src/main/java/codechicken/lib/util/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.util; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/vec/Cuboid6.java b/src/main/java/codechicken/lib/vec/Cuboid6.java index 4788ea85..2c048b13 100644 --- a/src/main/java/codechicken/lib/vec/Cuboid6.java +++ b/src/main/java/codechicken/lib/vec/Cuboid6.java @@ -266,18 +266,12 @@ public Cuboid6 setSide(Direction side, double d) { } public int hashCode() { - long i = Double.doubleToLongBits(min.x); - int j = (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(min.y); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(min.z); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(max.x); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(max.y); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(max.z); - j = 31 * j + (int) (i ^ i >>> 32); + int j = Double.hashCode(min.x); + j = 31 * j + Double.hashCode(min.y); + j = 31 * j + Double.hashCode(min.z); + j = 31 * j + Double.hashCode(max.x); + j = 31 * j + Double.hashCode(max.y); + j = 31 * j + Double.hashCode(max.z); return j; } @@ -286,10 +280,9 @@ public boolean equals(Object obj) { if (super.equals(obj)) { return true; } - if (!(obj instanceof Cuboid6)) { + if (!(obj instanceof Cuboid6 c)) { return false; } - Cuboid6 c = (Cuboid6) obj; return min.equals(c.min) && max.equals(c.max); } diff --git a/src/main/java/codechicken/lib/vec/TransformationList.java b/src/main/java/codechicken/lib/vec/TransformationList.java index ccd7d421..00194bbf 100644 --- a/src/main/java/codechicken/lib/vec/TransformationList.java +++ b/src/main/java/codechicken/lib/vec/TransformationList.java @@ -1,6 +1,7 @@ package codechicken.lib.vec; import codechicken.lib.util.Copyable; +import net.covers1624.quack.collection.FastStream; import net.covers1624.quack.collection.StreamableIterable; import org.jetbrains.annotations.Nullable; @@ -32,7 +33,7 @@ public TransformationList(List transforms) { } public TransformationList(TransformationList other) { - transformations = StreamableIterable.of(other.transformations) + transformations = FastStream.of(other.transformations) .map(Copyable::copy) .toList(); mat = other.mat; @@ -159,7 +160,7 @@ private void compact() { @Override public boolean isRedundant() { - return transformations.size() == 0; + return transformations.isEmpty(); } @Override diff --git a/src/main/java/codechicken/lib/vec/Vector3.java b/src/main/java/codechicken/lib/vec/Vector3.java index ed433b14..830a2a4c 100644 --- a/src/main/java/codechicken/lib/vec/Vector3.java +++ b/src/main/java/codechicken/lib/vec/Vector3.java @@ -80,7 +80,7 @@ public static Vector3 fromEntity(Entity e) { } public static Vector3 fromEntityCenter(Entity e) { - return new Vector3(e.position()).add(0, e.getMyRidingOffset() + e.getBbHeight() / 2, 0); + return new Vector3(e.position()).add(0, e.getBbHeight() / 2, 0); } public static Vector3 fromTile(BlockEntity tile) { @@ -188,8 +188,7 @@ public Vector3 add(Vec3 vec) { return add(vec.x, vec.y, vec.z); } - // TODO Move to use Vec3i - public Vector3 add(BlockPos pos) { + public Vector3 add(Vec3i pos) { return add(pos.getX(), pos.getY(), pos.getZ()); } @@ -212,7 +211,7 @@ public Vector3 subtract(Vec3 vec) { return subtract(vec.x, vec.y, vec.z); } - public Vector3 subtract(BlockPos pos) { + public Vector3 subtract(Vec3i pos) { return subtract(pos.getX(), pos.getY(), pos.getZ()); } @@ -246,7 +245,7 @@ public Vector3 divide(Vector3 vec) { return divide(vec.x, vec.y, vec.z); } - public Vector3 divide(BlockPos pos) { + public Vector3 divide(Vec3i pos) { return divide(pos.getX(), pos.getY(), pos.getZ()); } @@ -502,12 +501,9 @@ public Vector3 setSide(int s, double v) { @Override public int hashCode() { - long j = Double.doubleToLongBits(x); - int i = (int) (j ^ j >>> 32); - j = Double.doubleToLongBits(y); - i = 31 * i + (int) (j ^ j >>> 32); - j = Double.doubleToLongBits(z); - i = 31 * i + (int) (j ^ j >>> 32); + int i = Double.hashCode(x); + i = 31 * i + Double.hashCode(y); + i = 31 * i + Double.hashCode(z); return i; } @@ -516,10 +512,9 @@ public boolean equals(Object o) { if (super.equals(o)) { return true; } - if (!(o instanceof Vector3)) { + if (!(o instanceof Vector3 v)) { return false; } - Vector3 v = (Vector3) o; return x == v.x && y == v.y && z == v.z; } diff --git a/src/main/java/codechicken/lib/vec/package-info.java b/src/main/java/codechicken/lib/vec/package-info.java index 86fe172e..4ad9281d 100644 --- a/src/main/java/codechicken/lib/vec/package-info.java +++ b/src/main/java/codechicken/lib/vec/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.vec; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/vec/uv/IconTransformation.java b/src/main/java/codechicken/lib/vec/uv/IconTransformation.java index 86b78835..ebc77a8a 100644 --- a/src/main/java/codechicken/lib/vec/uv/IconTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/IconTransformation.java @@ -23,8 +23,8 @@ public void operate(CCRenderState ccrs) { @Override public void apply(UV uv) { - uv.u = icon.getU(uv.u * 16); - uv.v = icon.getV(uv.v * 16); + uv.u = icon.getU((float) uv.u); + uv.v = icon.getV((float) uv.v); } @Override diff --git a/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java b/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java index 7038bfcc..2f98bc0b 100644 --- a/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java @@ -29,8 +29,8 @@ public void operate(CCRenderState ccrs) { @Override public void apply(UV uv) { icon = icons[uv.tex % icons.length]; - uv.u = icon.getU(uv.u * 16); - uv.v = icon.getV(uv.v * 16); + uv.u = icon.getU((float) uv.u); + uv.v = icon.getV((float) uv.v); } @Override diff --git a/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java b/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java index 5e2850c9..a77d20ea 100644 --- a/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java @@ -25,8 +25,8 @@ public ScaledIconTransformation(ScaledIconTransformation other) { @Override public void apply(UV uv) { - uv.u = icon.getU(uv.u % 2 * 16) + su * (icon.getU1() - icon.getU0()); - uv.v = icon.getV(uv.v % 2 * 16) + sv * (icon.getV1() - icon.getV0()); + uv.u = icon.getU((float) (uv.u % 2)) + su * (icon.getU1() - icon.getU0()); + uv.v = icon.getV((float) (uv.v % 2)) + sv * (icon.getV1() - icon.getV0()); } @Override diff --git a/src/main/java/codechicken/lib/vec/uv/UVTransformation.java b/src/main/java/codechicken/lib/vec/uv/UVTransformation.java index 3854efcf..db52da15 100644 --- a/src/main/java/codechicken/lib/vec/uv/UVTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/UVTransformation.java @@ -35,5 +35,3 @@ public int operationID() { return operationIndex; } } - - diff --git a/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java b/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java index 9d124cba..08ba7d00 100644 --- a/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java +++ b/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java @@ -1,6 +1,7 @@ package codechicken.lib.vec.uv; import codechicken.lib.util.Copyable; +import net.covers1624.quack.collection.FastStream; import net.covers1624.quack.collection.StreamableIterable; import java.util.ArrayList; @@ -22,7 +23,7 @@ public UVTransformationList(UVTransformation... transforms) { } public UVTransformationList(UVTransformationList other) { - transformations = StreamableIterable.of(other.transformations) + transformations = FastStream.of(other.transformations) .map(Copyable::copy) .toList(); @@ -98,7 +99,7 @@ private void compact() { @Override public boolean isRedundant() { - return transformations.size() == 0; + return transformations.isEmpty(); } @Override diff --git a/src/main/java/codechicken/lib/vec/uv/package-info.java b/src/main/java/codechicken/lib/vec/uv/package-info.java index b36c0aaf..dbaafc4e 100644 --- a/src/main/java/codechicken/lib/vec/uv/package-info.java +++ b/src/main/java/codechicken/lib/vec/uv/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.vec.uv; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/world/package-info.java b/src/main/java/codechicken/lib/world/package-info.java new file mode 100644 index 00000000..c117001e --- /dev/null +++ b/src/main/java/codechicken/lib/world/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.world; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 3c773fef..51b57a39 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -1,90 +1,84 @@ # CodeChickenLib Access Transformer -public net.minecraft.core.Direction f_122348_ # BY_3D_DATA -public net.minecraft.world.phys.BlockHitResult (ZLnet/minecraft/world/phys/Vec3;Lnet/minecraft/core/Direction;Lnet/minecraft/core/BlockPos;Z)V # -public net.minecraft.server.MinecraftServer f_129744_ # storageSource +public net.minecraft.core.Direction BY_3D_DATA +public net.minecraft.world.phys.BlockHitResult (ZLnet/minecraft/world/phys/Vec3;Lnet/minecraft/core/Direction;Lnet/minecraft/core/BlockPos;Z)V +public net.minecraft.server.MinecraftServer storageSource public com.mojang.math.Matrix3f * # All fields. public com.mojang.math.Matrix4f * # All fields. -public com.mojang.blaze3d.vertex.BufferBuilder f_85658_ # format -public com.mojang.blaze3d.vertex.DefaultedVertexConsumer f_85824_ # defaultColorSet -public net.minecraft.world.phys.shapes.VoxelShape f_83211_ # shape -public net.minecraft.world.phys.shapes.VoxelShape (Lnet/minecraft/world/phys/shapes/DiscreteVoxelShape;)V # -public net.minecraft.world.phys.shapes.VoxelShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.phys.shapes.SliceShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.phys.shapes.ArrayVoxelShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.phys.shapes.CubeVoxelShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.inventory.MenuType f_39981_ # constructor -public net.minecraft.server.players.GameProfileCache f_10966_ # profilesByName -public net.minecraft.server.players.GameProfileCache$GameProfileInfo +public com.mojang.blaze3d.vertex.BufferBuilder format +public com.mojang.blaze3d.vertex.DefaultedVertexConsumer defaultColorSet +public net.minecraft.world.phys.shapes.VoxelShape shape +public net.minecraft.world.phys.shapes.VoxelShape (Lnet/minecraft/world/phys/shapes/DiscreteVoxelShape;)V +public net.minecraft.world.phys.shapes.VoxelShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.phys.shapes.SliceShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.phys.shapes.ArrayVoxelShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.phys.shapes.CubeVoxelShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.inventory.MenuType constructor public net.minecraft.client.renderer.RenderStateShard * # Everything. public net.minecraft.client.renderer.RenderType *() # All Methods public net.minecraft.client.renderer.RenderType * # All Fields. -public-f net.minecraft.client.renderer.block.BlockRenderDispatcher f_110900_ # modelRenderer -public net.minecraft.client.renderer.block.BlockRenderDispatcher f_173397_ # blockEntityRenderer -public-f net.minecraft.client.renderer.block.BlockRenderDispatcher f_110901_ # liquidBlockRenderer -public-f net.minecraft.client.Minecraft f_91052_ # blockRenderer -public net.minecraft.world.item.ArmorMaterials f_266010_ # HEALTH_FUNCTION_FOR_TYPE +public-f net.minecraft.client.renderer.block.BlockRenderDispatcher modelRenderer +public net.minecraft.client.renderer.block.BlockRenderDispatcher blockEntityRenderer +public-f net.minecraft.client.renderer.block.BlockRenderDispatcher liquidBlockRenderer +public-f net.minecraft.client.Minecraft blockRenderer +public net.minecraft.world.item.ArmorMaterials HEALTH_FUNCTION_FOR_TYPE -public net.minecraft.commands.arguments.ResourceKeyArgument m_233255_(Lcom/mojang/brigadier/context/CommandContext;Ljava/lang/String;Lnet/minecraft/resources/ResourceKey;Lcom/mojang/brigadier/exceptions/DynamicCommandExceptionType;)Lnet/minecraft/core/Holder; # getRegistryKeyType +public-f net.minecraft.world.level.block.Block stateDefinition +public-f net.minecraft.world.level.block.Block defaultBlockState()Lnet/minecraft/world/level/block/state/BlockState; -public-f net.minecraft.world.level.block.Block f_49792_ # stateDefinition -public-f net.minecraft.world.level.block.Block m_49966_()Lnet/minecraft/world/level/block/state/BlockState; # defaultBlockState -public net.minecraft.data.tags.IntrinsicHolderTagsProvider m_206424_(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/IntrinsicHolderTagsProvider$IntrinsicTagAppender; # tag +public-f net.minecraft.data.loot.LootTableProvider subProviders +public net.minecraft.data.tags.IntrinsicHolderTagsProvider tag(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/IntrinsicHolderTagsProvider$IntrinsicTagAppender; -protected net.minecraft.client.renderer.ShaderInstance f_173331_ # uniforms -protected net.minecraft.client.renderer.ShaderInstance m_173354_(Lcom/google/gson/JsonElement;)V # parseUniformNode -protected-f com.mojang.blaze3d.shaders.Uniform f_85588_ # intValues -protected-f com.mojang.blaze3d.shaders.Uniform f_85589_ # floatValues -protected com.mojang.blaze3d.shaders.Uniform f_85591_ # dirty -public-f com.mojang.blaze3d.shaders.Uniform m_5985_(F)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_7971_(FF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_166700_(IF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5889_(FFF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142276_(Lorg/joml/Vector3f;)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5805_(FFFF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142558_(Lorg/joml/Vector4f;)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5808_(FFFF)V # setSafe -public-f com.mojang.blaze3d.shaders.Uniform m_7401_(IIII)V # setSafe -public-f com.mojang.blaze3d.shaders.Uniform m_142617_(I)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142326_(II)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142693_(III)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142492_(IIII)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5941_([F)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142588_(FFFF)V # setMat2x2 -public-f com.mojang.blaze3d.shaders.Uniform m_141964_(FFFFFF)V # setMat2x3 -public-f com.mojang.blaze3d.shaders.Uniform m_142005_(FFFFFFFF)V # setMat2x4 -public-f com.mojang.blaze3d.shaders.Uniform m_141963_(FFFFFF)V # setMat3x2 -public-f com.mojang.blaze3d.shaders.Uniform m_142217_(FFFFFFFFF)V # setMat3x3 -public-f com.mojang.blaze3d.shaders.Uniform m_142604_(FFFFFFFFFFFF)V # setMat3x4 -public-f com.mojang.blaze3d.shaders.Uniform m_142004_(FFFFFFFF)V # setMat4x2 -public-f com.mojang.blaze3d.shaders.Uniform m_142605_(FFFFFFFFFFFF)V # setMat4x3 -public-f com.mojang.blaze3d.shaders.Uniform m_141978_(FFFFFFFFFFFFFFFF)V # setMat4x4 -public-f com.mojang.blaze3d.shaders.Uniform m_5679_(Lorg/joml/Matrix4f;)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_200759_(Lorg/joml/Matrix3f;)V # set -public com.mojang.blaze3d.shaders.Program (Lcom/mojang/blaze3d/shaders/Program$Type;ILjava/lang/String;)V # -public com.mojang.blaze3d.shaders.Program$Type m_85571_()I # getGlType +protected net.minecraft.client.renderer.ShaderInstance uniforms +protected net.minecraft.client.renderer.ShaderInstance parseUniformNode(Lcom/google/gson/JsonElement;)V +protected-f com.mojang.blaze3d.shaders.Uniform intValues +protected-f com.mojang.blaze3d.shaders.Uniform floatValues +protected com.mojang.blaze3d.shaders.Uniform dirty +public-f com.mojang.blaze3d.shaders.Uniform set(F)V +public-f com.mojang.blaze3d.shaders.Uniform set(FF)V +public-f com.mojang.blaze3d.shaders.Uniform set(IF)V +public-f com.mojang.blaze3d.shaders.Uniform set(FFF)V +public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Vector3f;)V +public-f com.mojang.blaze3d.shaders.Uniform set(FFFF)V +public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Vector4f;)V +public-f com.mojang.blaze3d.shaders.Uniform setSafe(FFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setSafe(IIII)V +public-f com.mojang.blaze3d.shaders.Uniform set(I)V +public-f com.mojang.blaze3d.shaders.Uniform set(II)V +public-f com.mojang.blaze3d.shaders.Uniform set(III)V +public-f com.mojang.blaze3d.shaders.Uniform set(IIII)V +public-f com.mojang.blaze3d.shaders.Uniform set([F)V +public-f com.mojang.blaze3d.shaders.Uniform setMat2x2(FFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat2x3(FFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat2x4(FFFFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat3x2(FFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat3x3(FFFFFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat3x4(FFFFFFFFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat4x2(FFFFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat4x3(FFFFFFFFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform setMat4x4(FFFFFFFFFFFFFFFF)V +public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Matrix4f;)V +public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Matrix3f;)V +public com.mojang.blaze3d.shaders.Program (Lcom/mojang/blaze3d/shaders/Program$Type;ILjava/lang/String;)V +public com.mojang.blaze3d.shaders.Program$Type getGlType()I -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_280092_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/inventory/Slot;)V # renderSlot -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_280211_(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/item/ItemStack;IILjava/lang/String;)V # renderFloatingItem -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97744_(DD)Lnet/minecraft/world/inventory/Slot; # findSlot -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97774_(Lnet/minecraft/world/inventory/Slot;DD)Z # isHovering -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen m_97818_()V # recalculateQuickCraftRemaining -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97706_ # clickedSlot -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97711_ # draggingItem -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97710_ # isSplittingStack -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97717_ # quickCraftingType -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97720_ # quickCraftingRemainder -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97715_ # snapbackItem -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97714_ # snapbackTime -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97707_ # snapbackEnd -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97712_ # snapbackStartX -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen f_97713_ # snapbackStartY -public-f net.minecraft.world.inventory.Slot f_40220_ # x -public-f net.minecraft.world.inventory.Slot f_40221_ # y -public net.minecraft.world.inventory.AbstractContainerMenu m_38897_(Lnet/minecraft/world/inventory/Slot;)Lnet/minecraft/world/inventory/Slot; # addSlot +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen renderSlot(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/inventory/Slot;)V +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen renderFloatingItem(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/item/ItemStack;IILjava/lang/String;)V +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen findSlot(DD)Lnet/minecraft/world/inventory/Slot; +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen isHovering(Lnet/minecraft/world/inventory/Slot;DD)Z +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen recalculateQuickCraftRemaining()V +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen clickedSlot +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen draggingItem +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen isSplittingStack +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen quickCraftingType +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen quickCraftingRemainder +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackItem +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackTime +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackEnd +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackStartX +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackStartY +public-f net.minecraft.world.inventory.Slot x +public-f net.minecraft.world.inventory.Slot y +public net.minecraft.world.inventory.AbstractContainerMenu addSlot(Lnet/minecraft/world/inventory/Slot;)Lnet/minecraft/world/inventory/Slot; -public net.minecraft.client.renderer.texture.TextureAtlas m_276092_()I # getWidth -public net.minecraft.client.renderer.texture.TextureAtlas m_276095_()I # getHeight -public net.minecraft.client.gui.GuiGraphics (Lnet/minecraft/client/Minecraft;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;)V # -public net.minecraft.client.gui.GuiGraphics m_286081_()V # flushIfUnmanaged -public net.minecraft.client.gui.GuiGraphics m_287246_()V # flushIfManaged \ No newline at end of file +public net.minecraft.client.gui.GuiGraphics (Lnet/minecraft/client/Minecraft;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;)V diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index 3b8e4e40..59003ae5 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -1,5 +1,5 @@ modLoader="javafml" -loaderVersion="[${lang_version},)" +loaderVersion="[2,)" issueTrackerURL="https://github.com/TheCBProject/CodeChickenLib" license="GNU Lesser General Public License v2.1" @@ -16,15 +16,15 @@ CodeChickenLib is a library of systems to help make various aspects of minecraft It contains libraries for 3D math and transformations, model rendering, packets, config, colours, asm and a few other things.. ''' [[dependencies.codechickenlib]] - modId="forge" - mandatory=true + modId="neoforge" + type="required" versionRange="[${forge_version},)" ordering="NONE" side="BOTH" [[dependencies.codechickenlib]] modId="minecraft" - mandatory=true - versionRange="[1.20.1]" + type="required" + versionRange="[1.20.4]" ordering="NONE" side="BOTH" diff --git a/src/main/resources/mixins.codechickenlib.json b/src/main/resources/mixins.codechickenlib.json index 72815248..bd87c7df 100644 --- a/src/main/resources/mixins.codechickenlib.json +++ b/src/main/resources/mixins.codechickenlib.json @@ -2,7 +2,6 @@ "required": true, "minVersion": "0.8", "package": "codechicken.lib.internal.mixin", - "refmap": "mixins.codechickenlib.refmap.json", "plugin": "codechicken.lib.internal.mixin.CCLMixinPlugin", "target": "@env(DEFAULT)", "compatibilityLevel": "JAVA_17", diff --git a/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java b/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java index 58931139..0cb112e6 100644 --- a/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java +++ b/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java @@ -3,6 +3,8 @@ import codechicken.lib.model.CachedFormat; import codechicken.lib.model.Quad; import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.neoforged.neoforge.client.textures.UnitTextureAtlasSprite; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -34,6 +36,8 @@ public void testExpand() { public void testExpandWithQuad() { Quad unbaked = new Quad(); unbaked.reset(CachedFormat.BLOCK); + unbaked.setQuadOrientation(Direction.NORTH); + unbaked.setTexture(UnitTextureAtlasSprite.INSTANCE); BakedQuad quad = unbaked.bake(); BakedVertexSource source = new BakedVertexSource(); From 617fe6ba80b735b511e3a2d3f6c73eaa6c2dba51 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 02:45:53 +0930 Subject: [PATCH 49/87] We need to register the client handler on the server. --- .../lib/packet/PacketCustomChannel.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java index f435b76a..9a4cb7b9 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -89,20 +89,20 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlerEvent event) { channel, e -> new PacketCustom.Pkt(channel, e.retain()), handlers -> { - if (client != null) { - handlers.client((payload, context) -> { + handlers.client((payload, context) -> { + if (client != null) { enqueue(context.workHandler(), payload, () -> { client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); }); - }); - } - if (server != null) { - handlers.server((payload, context) -> { + } + }); + handlers.server((payload, context) -> { + if (server != null) { enqueue(context.workHandler(), payload, () -> { server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player().orElseThrow()); }); - }); - } + } + }); } ); } From 1501db7ea90cc6278969ad390afbe4f885c2957e Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 02:46:51 +0930 Subject: [PATCH 50/87] Set CCL internal channel version to mod version. --- src/main/java/codechicken/lib/CodeChickenLib.java | 13 ++++++++++++- .../lib/internal/network/CCLNetwork.java | 2 ++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/CodeChickenLib.java b/src/main/java/codechicken/lib/CodeChickenLib.java index da06f1ed..3886c1e6 100644 --- a/src/main/java/codechicken/lib/CodeChickenLib.java +++ b/src/main/java/codechicken/lib/CodeChickenLib.java @@ -9,12 +9,16 @@ import codechicken.lib.internal.command.CCLCommands; import codechicken.lib.internal.network.CCLNetwork; import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; import net.neoforged.fml.common.Mod; import net.neoforged.fml.loading.FMLConfig; import net.neoforged.fml.loading.FMLEnvironment; +import org.jetbrains.annotations.Nullable; import java.nio.file.Paths; +import static java.util.Objects.requireNonNull; + /** * Created by covers1624 on 12/10/2016. */ @@ -29,9 +33,12 @@ public class CodeChickenLib { public static final String MOD_ID = "codechickenlib"; + private static @Nullable ModContainer container; + public static ConfigCategory config; - public CodeChickenLib(IEventBus modBus) { + public CodeChickenLib(ModContainer container, IEventBus modBus) { + CodeChickenLib.container = container; config = new ConfigFile(MOD_ID) .path(Paths.get("config/ccl.cfg")) .load(); @@ -47,4 +54,8 @@ public CodeChickenLib(IEventBus modBus) { // ConditionalIngredient.Serializer.init(); DataGenerators.init(modBus); } + + public static ModContainer container() { + return requireNonNull(container); + } } diff --git a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java index cd4b27c7..b9665aa1 100644 --- a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java +++ b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java @@ -1,5 +1,6 @@ package codechicken.lib.internal.network; +import codechicken.lib.CodeChickenLib; import codechicken.lib.packet.PacketCustomChannel; import net.minecraft.resources.ResourceLocation; import net.neoforged.bus.api.IEventBus; @@ -12,6 +13,7 @@ public class CCLNetwork { public static final ResourceLocation NET_CHANNEL = new ResourceLocation("ccl:internal"); public static final PacketCustomChannel channel = new PacketCustomChannel(NET_CHANNEL) .optional() + .versioned(CodeChickenLib.container().getModInfo().getVersion().toString()) .clientConfiguration(() -> ClientConfigurationPacketHandler::new) .client(() -> ClientPacketHandler::new) .server(() -> ServerPacketHandler::new); From 9bd2177ca3fdb3f38148746894857636030d9306 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 20:11:50 +0930 Subject: [PATCH 51/87] Packets are required to be 'read', we can't just retain the buffer. --- .../java/codechicken/lib/packet/PacketCustom.java | 2 +- .../codechicken/lib/packet/PacketCustomChannel.java | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/java/codechicken/lib/packet/PacketCustom.java b/src/main/java/codechicken/lib/packet/PacketCustom.java index 6cbc6002..5d042f45 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustom.java +++ b/src/main/java/codechicken/lib/packet/PacketCustom.java @@ -194,7 +194,7 @@ public void sendToServer() { //@formatter:on //endregion - record Pkt(ResourceLocation id, FriendlyByteBuf data) implements CustomPacketPayload { + record Pkt(ResourceLocation id, ByteBuf data) implements CustomPacketPayload { @Override public void write(FriendlyByteBuf buf) { diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java index 9a4cb7b9..9f244828 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -5,6 +5,7 @@ import codechicken.lib.packet.ICustomPacketHandler.IServerConfigurationPacketHandler; import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; import net.minecraft.client.Minecraft; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.neoforged.bus.api.IEventBus; @@ -87,7 +88,7 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlerEvent event) { if (client != null || server != null) { registrar.play( channel, - e -> new PacketCustom.Pkt(channel, e.retain()), + this::read, handlers -> { handlers.client((payload, context) -> { if (client != null) { @@ -109,7 +110,7 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlerEvent event) { if (clientConfiguration != null || serverConfiguration != null) { registrar.configuration( channel, - e -> new PacketCustom.Pkt(channel, e.retain()), + this::read, handlers -> { handlers.client((payload, context) -> { enqueue(context.workHandler(), payload, () -> { @@ -121,6 +122,13 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlerEvent event) { } } + private PacketCustom.Pkt read(FriendlyByteBuf buf) { + return new PacketCustom.Pkt( + channel, + buf.readBytes(buf.readableBytes()) + ); + } + private static void enqueue(ISynchronizedWorkHandler workHandler, PacketCustom.Pkt payload, Runnable runnable) { workHandler.submitAsync(() -> { try { From 797eae9b15a3a3a75b49dd4966c9fdace349bced Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 20:12:24 +0930 Subject: [PATCH 52/87] Apparently our CustomPacketPayload can be called to write more than once --- src/main/java/codechicken/lib/packet/PacketCustom.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/codechicken/lib/packet/PacketCustom.java b/src/main/java/codechicken/lib/packet/PacketCustom.java index 5d042f45..1284fd5f 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustom.java +++ b/src/main/java/codechicken/lib/packet/PacketCustom.java @@ -198,7 +198,9 @@ record Pkt(ResourceLocation id, ByteBuf data) implements CustomPacketPayload { @Override public void write(FriendlyByteBuf buf) { + data.markReaderIndex(); buf.writeBytes(data); + data.resetReaderIndex(); } } } From 2df47fe69cffc71987d22ad18a9e29ec336079c0 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 21:45:49 +0930 Subject: [PATCH 53/87] Always register the configuration channel. --- .../lib/packet/PacketCustomChannel.java | 62 +++++++++---------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java index 9f244828..cb96960c 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -85,41 +85,39 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlerEvent event) { if (optional) registrar = registrar.optional(); if (version != null) registrar = registrar.versioned(version); - if (client != null || server != null) { - registrar.play( - channel, - this::read, - handlers -> { - handlers.client((payload, context) -> { - if (client != null) { - enqueue(context.workHandler(), payload, () -> { - client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); - }); - } - }); - handlers.server((payload, context) -> { - if (server != null) { - enqueue(context.workHandler(), payload, () -> { - server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player().orElseThrow()); - }); - } - }); - } - ); - } - if (clientConfiguration != null || serverConfiguration != null) { - registrar.configuration( - channel, - this::read, - handlers -> { - handlers.client((payload, context) -> { + registrar.play( + channel, + this::read, + handlers -> { + handlers.client((payload, context) -> { + if (client != null) { + enqueue(context.workHandler(), payload, () -> { + client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + } + }); + handlers.server((payload, context) -> { + if (server != null) { + enqueue(context.workHandler(), payload, () -> { + server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player().orElseThrow()); + }); + } + }); + } + ); + registrar.configuration( + channel, + this::read, + handlers -> { + handlers.client((payload, context) -> { + if (clientConfiguration != null) { enqueue(context.workHandler(), payload, () -> { clientConfiguration.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); }); - }); - } - ); - } + } + }); + } + ); } private PacketCustom.Pkt read(FriendlyByteBuf buf) { From 62734a92e533d69b29c94923ae9a8de261879796 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 23:46:01 +0930 Subject: [PATCH 54/87] Ensure folder exists when dumping item renders. --- src/main/java/codechicken/lib/internal/ItemFileRenderer.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 972981b3..024d17e2 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -8,6 +8,7 @@ import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexSorting; import net.covers1624.quack.image.AnimatedGifEncoder; +import net.covers1624.quack.io.IOUtils; import net.covers1624.quack.platform.OperatingSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; @@ -162,7 +163,7 @@ private StaticRenderTask(ItemStack stack, int resolution, Path path) { protected boolean render() throws IOException { try (NativeImage image = takeItemScreenshot()) { image.flipY(); - image.writeToFile(path); + image.writeToFile(IOUtils.makeParents(path)); } return true; } @@ -228,7 +229,7 @@ private GifRenderTask(ItemStack stack, int resolution, Path path, int fps, int d @Override protected void serialize() throws IOException { - try (OutputStream os = Files.newOutputStream(path)) { + try (OutputStream os = Files.newOutputStream(IOUtils.makeParents(path))) { AnimatedGifEncoder encoder = new AnimatedGifEncoder(); encoder.start(os); encoder.setDelay((int) frameDelay); From e33667b973e6c30f30a9c0d9cfbdb7e1f31f62ae Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 23:47:52 +0930 Subject: [PATCH 55/87] Un-flip static images. --- src/main/java/codechicken/lib/internal/ItemFileRenderer.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 024d17e2..957c03bf 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -162,7 +162,6 @@ private StaticRenderTask(ItemStack stack, int resolution, Path path) { @Override protected boolean render() throws IOException { try (NativeImage image = takeItemScreenshot()) { - image.flipY(); image.writeToFile(IOUtils.makeParents(path)); } return true; From bd5cad0df2e529f0dd29fc2489db3f923a700031 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 22 Sep 2024 23:48:08 +0930 Subject: [PATCH 56/87] Log dumping files for ffmpeg. --- src/main/java/codechicken/lib/internal/ItemFileRenderer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 957c03bf..14e7bac5 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -283,6 +283,7 @@ protected void serialize() throws IOException { for (NativeImage frame : frames) { try (frame) { Path file = tempDir.resolve(i++ + ".png"); + LOGGER.info("Dumping: {}", file); tempFiles.add(file); frame.writeToFile(file); } From 883120f6f02cd640132ada12cbae291ae2812e83 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Fri, 8 Nov 2024 18:40:54 +1100 Subject: [PATCH 57/87] Fix ModularGuiContainer background rendering overtop the GUI --- .../lib/gui/modular/ModularGuiContainer.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java index 7caeec3f..36a2e4d9 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -76,9 +76,10 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float imageHeight = (int) root.getValue(GeoParam.HEIGHT); if (modularGui.renderBackground()) { - renderBackground(graphics, mouseX, mouseY, partialTicks); + //Called here to ensure background renders before modularGui elements. + super.renderBackground(graphics, mouseX, mouseY, partialTicks); } - GuiRender render = GuiRender.convert(graphics);//modularGui.createRender(graphics.bufferSource()); + GuiRender render = GuiRender.convert(graphics); modularGui.render(render, partialTicks); super.render(graphics, mouseX, mouseY, partialTicks); @@ -88,6 +89,11 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float } } + @Override + public void renderBackground(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { + //Stubbed to avoid the above super.render() call from rendering the background again. + } + protected boolean handleFloatingItemRender(GuiRender render, int mouseX, int mouseY) { if (modularGui.vanillaSlotRendering()) return false; boolean ret = false; From 05da429433a4df2c2eb3ad42d2eb8c45c3fe9cb5 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Tue, 12 Nov 2024 20:02:30 +1100 Subject: [PATCH 58/87] Fix GUI scrolling --- .../java/codechicken/lib/gui/modular/elements/GuiSlider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java index 23f24d46..13abc8c5 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java @@ -256,7 +256,7 @@ private void handleDrag(double mouseX, double mouseY) { public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { if (isMouseOver() || (scrollableElement != null && scrollableElement.isMouseOver())) { if (!state.canScroll(axis)) return false; - state.setPos(MathHelper.clip(state.getPos() + (state.scrollSpeed() * -scrollX), 0, 1)); + state.setPos(MathHelper.clip(state.getPos() + (state.scrollSpeed() * -scrollY), 0, 1)); return true; } return false; From b30626fec46f6a39dc29774dbcd89a90bdade969 Mon Sep 17 00:00:00 2001 From: brandon3055 Date: Thu, 14 Nov 2024 13:36:30 +1100 Subject: [PATCH 59/87] Update CCL Pack format. --- src/main/resources/pack.mcmeta | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta index 43ef0f5d..8b9bf7cc 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -1,6 +1,6 @@ { "pack": { - "pack_format": 4, + "pack_format": 22, "description": "CCL resource pack" } } From 2ab1743828b23e8d10e0b3b7534184e273b75451 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 20 Oct 2024 18:08:29 +1030 Subject: [PATCH 60/87] Port to 1.21.1 --- build.gradle | 9 +- gradle.properties | 8 +- gradle/wrapper/gradle-wrapper.jar | Bin 43462 -> 43583 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- gradlew | 7 +- gradlew.bat | 2 + .../15d5dd4ace2ad25407a17728f6fbc07b246efd63 | 2 +- .../95d738e2c774c5a4b0452cf55df2775d732b2634 | 36 ++-- .../f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 | 36 ++-- .../generated/data/c/tags/block/wools.json | 20 +++ .../wool => c/tags/block/wools}/black.json | 0 .../wool => c/tags/block/wools}/blue.json | 0 .../wool => c/tags/block/wools}/brown.json | 0 .../wool => c/tags/block/wools}/cyan.json | 0 .../wool => c/tags/block/wools}/gray.json | 0 .../wool => c/tags/block/wools}/green.json | 0 .../tags/block/wools}/light_blue.json | 0 .../tags/block/wools}/light_gray.json | 0 .../wool => c/tags/block/wools}/lime.json | 0 .../wool => c/tags/block/wools}/magenta.json | 0 .../wool => c/tags/block/wools}/orange.json | 0 .../wool => c/tags/block/wools}/pink.json | 0 .../wool => c/tags/block/wools}/purple.json | 0 .../wool => c/tags/block/wools}/red.json | 0 .../wool => c/tags/block/wools}/white.json | 0 .../wool => c/tags/block/wools}/yellow.json | 0 .../generated/data/c/tags/item/wools.json | 20 +++ .../wool => c/tags/item/wools}/black.json | 0 .../wool => c/tags/item/wools}/blue.json | 0 .../wool => c/tags/item/wools}/brown.json | 0 .../wool => c/tags/item/wools}/cyan.json | 0 .../wool => c/tags/item/wools}/gray.json | 0 .../wool => c/tags/item/wools}/green.json | 0 .../tags/item/wools}/light_blue.json | 0 .../tags/item/wools}/light_gray.json | 0 .../wool => c/tags/item/wools}/lime.json | 0 .../wool => c/tags/item/wools}/magenta.json | 0 .../wool => c/tags/item/wools}/orange.json | 0 .../wool => c/tags/item/wools}/pink.json | 0 .../wool => c/tags/item/wools}/purple.json | 0 .../items/wool => c/tags/item/wools}/red.json | 0 .../wool => c/tags/item/wools}/white.json | 0 .../wool => c/tags/item/wools}/yellow.json | 0 .../data/forge/tags/blocks/wool.json | 20 --- .../generated/data/forge/tags/items/wool.json | 20 --- .../lib/block/ModularBlockEntity.java | 17 +- .../component/data/LootTableComponent.java | 7 +- .../component/tile/InventoryComponent.java | 9 +- .../codechicken/lib/colour/EnumColour.java | 45 +++-- .../lib/config/ConfigSyncManager.java | 12 +- .../config/parser/TomlConfigSerializer.java | 2 +- .../codechicken/lib/data/MCDataByteBuf.java | 59 ++++++- .../codechicken/lib/data/MCDataInput.java | 39 ++--- .../codechicken/lib/data/MCDataOutput.java | 46 ++--- .../lib/datagen/DynamicTextureProvider.java | 6 +- .../lib/datagen/ItemModelProvider.java | 6 +- .../lib/datagen/LanguageProvider.java | 2 - .../NoValidationBLockLootSubProvider.java | 23 +-- .../datagen/recipe/AbstractRecipeBuilder.java | 2 +- .../lib/datagen/recipe/RecipeProvider.java | 16 +- .../recipe/SpecialCraftingRecipeBuilder.java | 2 +- .../modular/elements/GuiEntityRenderer.java | 2 +- .../gui/modular/elements/GuiTextField.java | 21 ++- .../lib/gui/modular/lib/CursorHelper.java | 12 +- .../lib/gui/modular/lib/GuiRender.java | 85 +++++----- .../gui/modular/lib/container/SlotGroup.java | 15 +- .../lib/gui/modular/sprite/GuiTextures.java | 2 +- .../lib/gui/modular/sprite/Material.java | 2 +- .../gui/modular/sprite/ModAtlasHolder.java | 4 +- .../codechicken/lib/internal/ClientInit.java | 4 +- .../lib/internal/DataGenerators.java | 132 +++++++-------- .../ExceptionMessageEventHandler.java | 17 +- .../lib/internal/ItemFileRenderer.java | 11 +- .../command/client/HighlightCommand.java | 2 +- .../command/client/ItemInfoCommand.java | 3 +- .../lib/internal/compat/JEIPlugin.java | 2 +- .../internal/mixin/ShaderInstanceMixin.java | 2 +- .../lib/internal/network/CCLNetwork.java | 5 +- .../internal/network/ClientPacketHandler.java | 33 +--- .../lib/inventory/InventoryNBT.java | 9 +- .../lib/inventory/InventoryUtils.java | 18 +- .../lib/inventory/container/CCLMenuType.java | 73 ++++++++ .../container/ContainerExtended.java | 2 +- .../container/ICCLContainerFactory.java | 19 --- .../container/ICCLContainerType.java | 40 ----- .../container/data/AbstractDataStore.java | 5 +- .../inventory/container/data/BooleanData.java | 6 +- .../inventory/container/data/ByteData.java | 6 +- .../inventory/container/data/DoubleData.java | 6 +- .../inventory/container/data/FloatData.java | 6 +- .../inventory/container/data/FluidData.java | 19 ++- .../lib/inventory/container/data/IntData.java | 6 +- .../inventory/container/data/LongData.java | 6 +- .../inventory/container/data/ShortData.java | 6 +- .../modular/ModularGuiContainerMenu.java | 6 +- .../lib/item/SimpleArmorMaterial.java | 157 ------------------ .../codechicken/lib/item/package-info.java | 4 - .../codechicken/lib/model/CachedFormat.java | 4 +- .../lib/model/ClassModelLoader.java | 2 +- .../lib/model/CompositeItemModel.java | 4 +- .../codechicken/lib/model/ItemQuadBakery.java | 2 +- .../lib/packet/ICustomPacketHandler.java | 4 +- .../codechicken/lib/packet/PacketCustom.java | 32 ++-- .../lib/packet/PacketCustomChannel.java | 98 ++++++----- .../codechicken/lib/raytracer/RayTracer.java | 31 +--- .../lib/render/CCRenderEventHandler.java | 15 +- .../codechicken/lib/render/CCRenderState.java | 81 ++------- .../codechicken/lib/render/RenderUtils.java | 52 +++--- .../block/CCBlockRendererDispatcher.java | 2 +- .../buffer/AlphaOverrideVertexConsumer.java | 4 +- .../render/buffer/BakedQuadVertexBuilder.java | 90 +++------- .../lib/render/buffer/DelegateRenderType.java | 7 +- .../buffer/DelegatingVertexConsumer.java | 39 ++--- .../buffer/TransformingVertexConsumer.java | 8 +- .../lib/render/buffer/VBORenderType.java | 26 +-- .../lib/render/model/OBJParser.java | 4 +- .../particle/CustomParticleHandler.java | 10 +- .../lib/render/shader/CCShaderInstance.java | 2 +- .../lib/render/shader/GlslProcessor.java | 4 +- .../codechicken/lib/texture/TextureUtils.java | 10 +- .../java/codechicken/lib/util/CCLTags.java | 76 ++++----- .../java/codechicken/lib/util/ItemUtils.java | 3 +- .../codechicken/lib/util/ResourceUtils.java | 11 -- .../codechicken/lib/util/ServerUtils.java | 42 ----- .../codechicken/lib/util/VertexUtils.java | 20 +-- .../{mods.toml => neoforge.mods.toml} | 2 +- .../lib/render/model/MatLibTests.java | 2 +- .../lib/render/model/OBJParserTests.java | 8 +- 128 files changed, 813 insertions(+), 1105 deletions(-) create mode 100644 src/main/generated/data/c/tags/block/wools.json rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/black.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/blue.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/brown.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/cyan.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/gray.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/green.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/light_blue.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/light_gray.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/lime.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/magenta.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/orange.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/pink.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/purple.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/red.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/white.json (100%) rename src/main/generated/data/{forge/tags/blocks/wool => c/tags/block/wools}/yellow.json (100%) create mode 100644 src/main/generated/data/c/tags/item/wools.json rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/black.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/blue.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/brown.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/cyan.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/gray.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/green.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/light_blue.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/light_gray.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/lime.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/magenta.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/orange.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/pink.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/purple.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/red.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/white.json (100%) rename src/main/generated/data/{forge/tags/items/wool => c/tags/item/wools}/yellow.json (100%) delete mode 100644 src/main/generated/data/forge/tags/blocks/wool.json delete mode 100644 src/main/generated/data/forge/tags/items/wool.json create mode 100644 src/main/java/codechicken/lib/inventory/container/CCLMenuType.java delete mode 100644 src/main/java/codechicken/lib/inventory/container/ICCLContainerFactory.java delete mode 100644 src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java delete mode 100644 src/main/java/codechicken/lib/item/SimpleArmorMaterial.java delete mode 100644 src/main/java/codechicken/lib/item/package-info.java rename src/main/resources/META-INF/{mods.toml => neoforge.mods.toml} (97%) diff --git a/build.gradle b/build.gradle index f00ca8e1..9d23645e 100644 --- a/build.gradle +++ b/build.gradle @@ -5,12 +5,12 @@ plugins { id 'maven-publish' id 'signing' id 'com.github.johnrengelman.shadow' version '7.1.2' - id 'net.neoforged.gradle.userdev' version '7.0.97' + id 'net.neoforged.gradle.userdev' version '7.0.165' } java { toolchain { - languageVersion = JavaLanguageVersion.of(17) + languageVersion = JavaLanguageVersion.of(21) } withSourcesJar() withJavadocJar() @@ -41,7 +41,7 @@ runs { } data { workingDirectory file('run') - programArguments.addAll '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated").absolutePath, '--existing', file("src/main/resources").absolutePath + arguments.addAll '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated").absolutePath, '--existing', file("src/main/resources").absolutePath } } @@ -49,7 +49,7 @@ processResources { inputs.property 'mod_version', mod_version inputs.property 'mc_version', mc_version - filesMatching('META-INF/mods.toml') { + filesMatching('META-INF/neoforge.mods.toml') { expand 'file': ['jarVersion': mod_version], 'mc_version': mc_version, 'forge_version': forge_version, @@ -123,6 +123,7 @@ shadowJar { configurations = [project.configurations.shadow] from file("LICENSE") } +assemble.dependsOn shadowJar tasks.register("signShadowJar") { dependsOn("shadowJar") diff --git a/gradle.properties b/gradle.properties index c135b61f..2362bae0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ org.gradle.daemon=false -mc_version=1.20.4 -forge_version=20.4.237 -mod_version=4.5.0 -jei_version=17.3.0.56 +mc_version=1.21.1 +forge_version=21.1.72 +mod_version=4.6.0 +jei_version=19.21.0.246 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index d64cd4917707c1f8861d8cb53dd15194d4248596..a4b76b9530d66f5e68d973ea569d8e19de379189 100644 GIT binary patch delta 34592 zcmY(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6g~ zCL1d0jcUJO-+8y)#+Wl0=`qCJo^!~ia8$-;rOBE~#*_zRZ*s~5n>IEYEtin@n6TMCEC;3v*irJ77~dTlkH+Ea~ni&gW~z zEBWCpC22aJfc1md!}q~j@)~H{%|IZpVtGYMh}wWjmPAVGFG{e*)g0Ukf*24y3)BXV zL{F7d(CXNXPzVFQlu~e}UL~fsmSnqLDoUS5FIMR1VZnVc3TinGDcHznFA6zTs<73? z4WUqG_@f*^v&jR_Q>a63^$bI30RuiF&nnl+1=px4kSzi_XB+AxOARqt@H;ZXlCce# zxlDYVFRiA{;DaYx(}XclB2S^eT1Q#1;p=9y6{`}J_sm<1Th)5PG zzzBlA<6+TFhl2c=Jl_@yJ}518aXJd2YFCAVu-7TMwT$KZefT7 zs5NxjtWvoM1u)bqHBp$PBs0RBf))u;m?bp>hDT6vTw&Lr!dBTtgj5XtcKJWphk_H; zeH09+T|vQZQ8Efz6lS0!cG`T`QE*MzYzhh@C0zhrg|>NSMAtY9%Huc+TF>Ppkl@@zX1imQDFMlS23i7E;Qs+kyyrF{7O&UZxN+ z-QgiSOj1$l30gw2$s1etFkp1{tI8Eq=&i{Q(-jkZqNBkxHjo*)Mn|Eg=J}ZZ*M!@$ m8X&e#V;O~v<{(@8u;?|riGH1;*CyBcIM_}B>Hc%VBjPV`^lBFX diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a80b22ce..9355b415 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 1aa94a42..f5feea6d 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # 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 +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -84,7 +86,8 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum diff --git a/gradlew.bat b/gradlew.bat index 25da30db..9d21a218 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## diff --git a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 index 5c59c3eb..80a10f55 100644 --- a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 +++ b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 @@ -1,3 +1,3 @@ -// 1.20.1 2024-02-13T15:00:40.20834201 codechickenlib Languages: en_us +// 1.21.1 2024-12-06T17:16:20.755131366 codechickenlib Languages: en_us d535acbe9649e564744ed63aef209ce1508ec451 assets/codechickenlib/lang/en_us.json d535acbe9649e564744ed63aef209ce1508ec451 data/codechickenlib/lang/en_us.json diff --git a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 index 663271f0..bc503cb2 100644 --- a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 +++ b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 @@ -1,18 +1,18 @@ -// 1.20.1 2023-09-08T20:30:19.590475077 CodeChickenLib Block tags. -48ffc90719924738f43a8ea0c526941cbbb83318 data/forge/tags/blocks/wool.json -dc26d59698d238e0c60c400dbffea2ba82af4365 data/forge/tags/blocks/wool/black.json -4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/forge/tags/blocks/wool/blue.json -9f867580ce1e743583fab6a17e3d03248865eafc data/forge/tags/blocks/wool/brown.json -b4b458788e919f93343c36ef996f828bcf610abc data/forge/tags/blocks/wool/cyan.json -62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/forge/tags/blocks/wool/gray.json -1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/forge/tags/blocks/wool/green.json -e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/forge/tags/blocks/wool/light_blue.json -bf7627f1264b6899bedb6f55e19898dad5d03d8c data/forge/tags/blocks/wool/light_gray.json -aceb5be462f62f63438e67877d38c89951e8919e data/forge/tags/blocks/wool/lime.json -cfd0d2c16adae65fbf8640439a1814ab244082cb data/forge/tags/blocks/wool/magenta.json -842c228466435a5cc9221a17f70a778db8617590 data/forge/tags/blocks/wool/orange.json -3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/forge/tags/blocks/wool/pink.json -fec60767247bdbebf6cd451bb3692c9a8ffef908 data/forge/tags/blocks/wool/purple.json -85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/forge/tags/blocks/wool/red.json -8e71446b54f055edb3ba7a025d4335cb78da1b45 data/forge/tags/blocks/wool/white.json -0de700cdfc12e281290ea7bc709d3241620ec9fb data/forge/tags/blocks/wool/yellow.json +// 1.21.1 2024-12-06T17:16:20.746404632 CodeChickenLib Block tags. +9b9a1318b746e42366ee1747896a1c61d71bc0ae data/c/tags/block/wools.json +dc26d59698d238e0c60c400dbffea2ba82af4365 data/c/tags/block/wools/black.json +4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/c/tags/block/wools/blue.json +9f867580ce1e743583fab6a17e3d03248865eafc data/c/tags/block/wools/brown.json +b4b458788e919f93343c36ef996f828bcf610abc data/c/tags/block/wools/cyan.json +62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/c/tags/block/wools/gray.json +1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/c/tags/block/wools/green.json +e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/c/tags/block/wools/light_blue.json +bf7627f1264b6899bedb6f55e19898dad5d03d8c data/c/tags/block/wools/light_gray.json +aceb5be462f62f63438e67877d38c89951e8919e data/c/tags/block/wools/lime.json +cfd0d2c16adae65fbf8640439a1814ab244082cb data/c/tags/block/wools/magenta.json +842c228466435a5cc9221a17f70a778db8617590 data/c/tags/block/wools/orange.json +3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/c/tags/block/wools/pink.json +fec60767247bdbebf6cd451bb3692c9a8ffef908 data/c/tags/block/wools/purple.json +85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/c/tags/block/wools/red.json +8e71446b54f055edb3ba7a025d4335cb78da1b45 data/c/tags/block/wools/white.json +0de700cdfc12e281290ea7bc709d3241620ec9fb data/c/tags/block/wools/yellow.json diff --git a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 index 33d215f6..c16bbd75 100644 --- a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 +++ b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 @@ -1,18 +1,18 @@ -// 1.20.1 2023-09-08T20:30:19.593585402 CodeChickenLib Item tags. -48ffc90719924738f43a8ea0c526941cbbb83318 data/forge/tags/items/wool.json -dc26d59698d238e0c60c400dbffea2ba82af4365 data/forge/tags/items/wool/black.json -4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/forge/tags/items/wool/blue.json -9f867580ce1e743583fab6a17e3d03248865eafc data/forge/tags/items/wool/brown.json -b4b458788e919f93343c36ef996f828bcf610abc data/forge/tags/items/wool/cyan.json -62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/forge/tags/items/wool/gray.json -1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/forge/tags/items/wool/green.json -e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/forge/tags/items/wool/light_blue.json -bf7627f1264b6899bedb6f55e19898dad5d03d8c data/forge/tags/items/wool/light_gray.json -aceb5be462f62f63438e67877d38c89951e8919e data/forge/tags/items/wool/lime.json -cfd0d2c16adae65fbf8640439a1814ab244082cb data/forge/tags/items/wool/magenta.json -842c228466435a5cc9221a17f70a778db8617590 data/forge/tags/items/wool/orange.json -3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/forge/tags/items/wool/pink.json -fec60767247bdbebf6cd451bb3692c9a8ffef908 data/forge/tags/items/wool/purple.json -85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/forge/tags/items/wool/red.json -8e71446b54f055edb3ba7a025d4335cb78da1b45 data/forge/tags/items/wool/white.json -0de700cdfc12e281290ea7bc709d3241620ec9fb data/forge/tags/items/wool/yellow.json +// 1.21.1 2024-12-06T17:16:20.755323336 CodeChickenLib Item tags. +9b9a1318b746e42366ee1747896a1c61d71bc0ae data/c/tags/item/wools.json +dc26d59698d238e0c60c400dbffea2ba82af4365 data/c/tags/item/wools/black.json +4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/c/tags/item/wools/blue.json +9f867580ce1e743583fab6a17e3d03248865eafc data/c/tags/item/wools/brown.json +b4b458788e919f93343c36ef996f828bcf610abc data/c/tags/item/wools/cyan.json +62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/c/tags/item/wools/gray.json +1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/c/tags/item/wools/green.json +e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/c/tags/item/wools/light_blue.json +bf7627f1264b6899bedb6f55e19898dad5d03d8c data/c/tags/item/wools/light_gray.json +aceb5be462f62f63438e67877d38c89951e8919e data/c/tags/item/wools/lime.json +cfd0d2c16adae65fbf8640439a1814ab244082cb data/c/tags/item/wools/magenta.json +842c228466435a5cc9221a17f70a778db8617590 data/c/tags/item/wools/orange.json +3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/c/tags/item/wools/pink.json +fec60767247bdbebf6cd451bb3692c9a8ffef908 data/c/tags/item/wools/purple.json +85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/c/tags/item/wools/red.json +8e71446b54f055edb3ba7a025d4335cb78da1b45 data/c/tags/item/wools/white.json +0de700cdfc12e281290ea7bc709d3241620ec9fb data/c/tags/item/wools/yellow.json diff --git a/src/main/generated/data/c/tags/block/wools.json b/src/main/generated/data/c/tags/block/wools.json new file mode 100644 index 00000000..10f4aa19 --- /dev/null +++ b/src/main/generated/data/c/tags/block/wools.json @@ -0,0 +1,20 @@ +{ + "values": [ + "#c:wools/white", + "#c:wools/orange", + "#c:wools/magenta", + "#c:wools/light_blue", + "#c:wools/yellow", + "#c:wools/lime", + "#c:wools/pink", + "#c:wools/gray", + "#c:wools/light_gray", + "#c:wools/cyan", + "#c:wools/purple", + "#c:wools/blue", + "#c:wools/brown", + "#c:wools/green", + "#c:wools/red", + "#c:wools/black" + ] +} \ No newline at end of file diff --git a/src/main/generated/data/forge/tags/blocks/wool/black.json b/src/main/generated/data/c/tags/block/wools/black.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/black.json rename to src/main/generated/data/c/tags/block/wools/black.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/blue.json b/src/main/generated/data/c/tags/block/wools/blue.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/blue.json rename to src/main/generated/data/c/tags/block/wools/blue.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/brown.json b/src/main/generated/data/c/tags/block/wools/brown.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/brown.json rename to src/main/generated/data/c/tags/block/wools/brown.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/cyan.json b/src/main/generated/data/c/tags/block/wools/cyan.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/cyan.json rename to src/main/generated/data/c/tags/block/wools/cyan.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/gray.json b/src/main/generated/data/c/tags/block/wools/gray.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/gray.json rename to src/main/generated/data/c/tags/block/wools/gray.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/green.json b/src/main/generated/data/c/tags/block/wools/green.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/green.json rename to src/main/generated/data/c/tags/block/wools/green.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/light_blue.json b/src/main/generated/data/c/tags/block/wools/light_blue.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/light_blue.json rename to src/main/generated/data/c/tags/block/wools/light_blue.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/light_gray.json b/src/main/generated/data/c/tags/block/wools/light_gray.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/light_gray.json rename to src/main/generated/data/c/tags/block/wools/light_gray.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/lime.json b/src/main/generated/data/c/tags/block/wools/lime.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/lime.json rename to src/main/generated/data/c/tags/block/wools/lime.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/magenta.json b/src/main/generated/data/c/tags/block/wools/magenta.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/magenta.json rename to src/main/generated/data/c/tags/block/wools/magenta.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/orange.json b/src/main/generated/data/c/tags/block/wools/orange.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/orange.json rename to src/main/generated/data/c/tags/block/wools/orange.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/pink.json b/src/main/generated/data/c/tags/block/wools/pink.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/pink.json rename to src/main/generated/data/c/tags/block/wools/pink.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/purple.json b/src/main/generated/data/c/tags/block/wools/purple.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/purple.json rename to src/main/generated/data/c/tags/block/wools/purple.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/red.json b/src/main/generated/data/c/tags/block/wools/red.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/red.json rename to src/main/generated/data/c/tags/block/wools/red.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/white.json b/src/main/generated/data/c/tags/block/wools/white.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/white.json rename to src/main/generated/data/c/tags/block/wools/white.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/yellow.json b/src/main/generated/data/c/tags/block/wools/yellow.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/yellow.json rename to src/main/generated/data/c/tags/block/wools/yellow.json diff --git a/src/main/generated/data/c/tags/item/wools.json b/src/main/generated/data/c/tags/item/wools.json new file mode 100644 index 00000000..10f4aa19 --- /dev/null +++ b/src/main/generated/data/c/tags/item/wools.json @@ -0,0 +1,20 @@ +{ + "values": [ + "#c:wools/white", + "#c:wools/orange", + "#c:wools/magenta", + "#c:wools/light_blue", + "#c:wools/yellow", + "#c:wools/lime", + "#c:wools/pink", + "#c:wools/gray", + "#c:wools/light_gray", + "#c:wools/cyan", + "#c:wools/purple", + "#c:wools/blue", + "#c:wools/brown", + "#c:wools/green", + "#c:wools/red", + "#c:wools/black" + ] +} \ No newline at end of file diff --git a/src/main/generated/data/forge/tags/items/wool/black.json b/src/main/generated/data/c/tags/item/wools/black.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/black.json rename to src/main/generated/data/c/tags/item/wools/black.json diff --git a/src/main/generated/data/forge/tags/items/wool/blue.json b/src/main/generated/data/c/tags/item/wools/blue.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/blue.json rename to src/main/generated/data/c/tags/item/wools/blue.json diff --git a/src/main/generated/data/forge/tags/items/wool/brown.json b/src/main/generated/data/c/tags/item/wools/brown.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/brown.json rename to src/main/generated/data/c/tags/item/wools/brown.json diff --git a/src/main/generated/data/forge/tags/items/wool/cyan.json b/src/main/generated/data/c/tags/item/wools/cyan.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/cyan.json rename to src/main/generated/data/c/tags/item/wools/cyan.json diff --git a/src/main/generated/data/forge/tags/items/wool/gray.json b/src/main/generated/data/c/tags/item/wools/gray.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/gray.json rename to src/main/generated/data/c/tags/item/wools/gray.json diff --git a/src/main/generated/data/forge/tags/items/wool/green.json b/src/main/generated/data/c/tags/item/wools/green.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/green.json rename to src/main/generated/data/c/tags/item/wools/green.json diff --git a/src/main/generated/data/forge/tags/items/wool/light_blue.json b/src/main/generated/data/c/tags/item/wools/light_blue.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/light_blue.json rename to src/main/generated/data/c/tags/item/wools/light_blue.json diff --git a/src/main/generated/data/forge/tags/items/wool/light_gray.json b/src/main/generated/data/c/tags/item/wools/light_gray.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/light_gray.json rename to src/main/generated/data/c/tags/item/wools/light_gray.json diff --git a/src/main/generated/data/forge/tags/items/wool/lime.json b/src/main/generated/data/c/tags/item/wools/lime.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/lime.json rename to src/main/generated/data/c/tags/item/wools/lime.json diff --git a/src/main/generated/data/forge/tags/items/wool/magenta.json b/src/main/generated/data/c/tags/item/wools/magenta.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/magenta.json rename to src/main/generated/data/c/tags/item/wools/magenta.json diff --git a/src/main/generated/data/forge/tags/items/wool/orange.json b/src/main/generated/data/c/tags/item/wools/orange.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/orange.json rename to src/main/generated/data/c/tags/item/wools/orange.json diff --git a/src/main/generated/data/forge/tags/items/wool/pink.json b/src/main/generated/data/c/tags/item/wools/pink.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/pink.json rename to src/main/generated/data/c/tags/item/wools/pink.json diff --git a/src/main/generated/data/forge/tags/items/wool/purple.json b/src/main/generated/data/c/tags/item/wools/purple.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/purple.json rename to src/main/generated/data/c/tags/item/wools/purple.json diff --git a/src/main/generated/data/forge/tags/items/wool/red.json b/src/main/generated/data/c/tags/item/wools/red.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/red.json rename to src/main/generated/data/c/tags/item/wools/red.json diff --git a/src/main/generated/data/forge/tags/items/wool/white.json b/src/main/generated/data/c/tags/item/wools/white.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/white.json rename to src/main/generated/data/c/tags/item/wools/white.json diff --git a/src/main/generated/data/forge/tags/items/wool/yellow.json b/src/main/generated/data/c/tags/item/wools/yellow.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/yellow.json rename to src/main/generated/data/c/tags/item/wools/yellow.json diff --git a/src/main/generated/data/forge/tags/blocks/wool.json b/src/main/generated/data/forge/tags/blocks/wool.json deleted file mode 100644 index 3754cb21..00000000 --- a/src/main/generated/data/forge/tags/blocks/wool.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "values": [ - "#forge:wool/white", - "#forge:wool/orange", - "#forge:wool/magenta", - "#forge:wool/light_blue", - "#forge:wool/yellow", - "#forge:wool/lime", - "#forge:wool/pink", - "#forge:wool/gray", - "#forge:wool/light_gray", - "#forge:wool/cyan", - "#forge:wool/purple", - "#forge:wool/blue", - "#forge:wool/brown", - "#forge:wool/green", - "#forge:wool/red", - "#forge:wool/black" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/forge/tags/items/wool.json b/src/main/generated/data/forge/tags/items/wool.json deleted file mode 100644 index 3754cb21..00000000 --- a/src/main/generated/data/forge/tags/items/wool.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "values": [ - "#forge:wool/white", - "#forge:wool/orange", - "#forge:wool/magenta", - "#forge:wool/light_blue", - "#forge:wool/yellow", - "#forge:wool/lime", - "#forge:wool/pink", - "#forge:wool/gray", - "#forge:wool/light_gray", - "#forge:wool/cyan", - "#forge:wool/purple", - "#forge:wool/blue", - "#forge:wool/brown", - "#forge:wool/green", - "#forge:wool/red", - "#forge:wool/black" - ] -} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/block/ModularBlockEntity.java b/src/main/java/codechicken/lib/block/ModularBlockEntity.java index 093192cd..ab3cfaa9 100644 --- a/src/main/java/codechicken/lib/block/ModularBlockEntity.java +++ b/src/main/java/codechicken/lib/block/ModularBlockEntity.java @@ -2,6 +2,7 @@ import codechicken.lib.block.ModularTileBlock.TileComponent; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; @@ -43,24 +44,24 @@ public final T getData(TileComponent component) { @Override @MustBeInvokedByOverriders - protected void saveAdditional(CompoundTag tag) { - super.saveAdditional(tag); + protected void saveAdditional(CompoundTag tag, HolderLookup.Provider registries) { + super.saveAdditional(tag, registries); for (DataComponent component : components) { CompoundTag componentTag = new CompoundTag(); - component.save(componentTag); + component.save(componentTag, registries); tag.put(component.tileComponent.name, componentTag); } } @Override @MustBeInvokedByOverriders - public void load(CompoundTag tag) { - super.load(tag); + public void loadAdditional(CompoundTag tag, HolderLookup.Provider registries) { + super.loadAdditional(tag, registries); for (DataComponent component : components) { if (tag.contains(component.tileComponent.name)) { - component.load(tag.getCompound(component.tileComponent.name)); + component.load(tag.getCompound(component.tileComponent.name), registries); } } } @@ -75,10 +76,10 @@ protected DataComponent(ModularBlockEntity tile, TileComponent tileComponent) this.tileComponent = tileComponent; } - protected void save(CompoundTag tag) { + protected void save(CompoundTag tag, HolderLookup.Provider registries) { } - protected void load(CompoundTag tag) { + protected void load(CompoundTag tag, HolderLookup.Provider registries) { } } } diff --git a/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java b/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java index 60818162..98c141a4 100644 --- a/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java @@ -2,11 +2,9 @@ import codechicken.lib.block.ModularBlock; import codechicken.lib.datagen.NoValidationBLockLootSubProvider; +import net.minecraft.core.HolderLookup; import net.minecraft.data.DataProvider; -import net.minecraft.data.loot.BlockLootSubProvider; import net.minecraft.data.loot.LootTableProvider; -import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.storage.loot.LootPool; import net.minecraft.world.level.storage.loot.LootTable; @@ -16,7 +14,6 @@ import org.jetbrains.annotations.ApiStatus; import java.util.ArrayList; -import java.util.Set; import java.util.function.Consumer; /** @@ -42,7 +39,7 @@ protected void addToProvider(DataProvider p) { } provider.subProviders.add( new LootTableProvider.SubProviderEntry( - () -> new NoValidationBLockLootSubProvider() { + registries -> new NoValidationBLockLootSubProvider(registries) { @Override protected void generate() { add(getBlock(), table); diff --git a/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java b/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java index 4784432b..d1237487 100644 --- a/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java +++ b/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java @@ -4,6 +4,7 @@ import codechicken.lib.block.ModularTileBlock; import codechicken.lib.inventory.InventoryUtils; import codechicken.lib.util.ArrayUtils; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.world.Container; @@ -121,13 +122,13 @@ public int getMaxStackSize() { } @Override - protected void save(CompoundTag tag) { - tag.put("Items", InventoryUtils.writeItemStacksToTag(items)); + protected void save(CompoundTag tag, HolderLookup.Provider registries) { + tag.put("Items", InventoryUtils.writeItemStacksToTag(registries, items)); } @Override - protected void load(CompoundTag tag) { - InventoryUtils.readItemStacksFromTag(items, tag.getList("Items", Tag.TAG_COMPOUND)); + protected void load(CompoundTag tag, HolderLookup.Provider registries) { + InventoryUtils.readItemStacksFromTag(registries, items, tag.getList("Items", Tag.TAG_COMPOUND)); } } } diff --git a/src/main/java/codechicken/lib/colour/EnumColour.java b/src/main/java/codechicken/lib/colour/EnumColour.java index 5467d349..f9552a3c 100644 --- a/src/main/java/codechicken/lib/colour/EnumColour.java +++ b/src/main/java/codechicken/lib/colour/EnumColour.java @@ -3,10 +3,14 @@ import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; +import io.netty.buffer.ByteBuf; import net.covers1624.quack.collection.FastStream; import net.minecraft.client.resources.language.I18n; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; +import net.minecraft.util.ByIdMap; import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; @@ -14,6 +18,7 @@ import java.util.Map; import java.util.Objects; import java.util.function.Function; +import java.util.function.IntFunction; /** * Created by covers1624 on 16/09/2016. @@ -21,24 +26,28 @@ public enum EnumColour implements StringRepresentable { //@formatter:off - WHITE ("white", "forge:dyes/white", "forge:wool/white", "item.minecraft.firework_star.white", 0xFFFFFF), - ORANGE ("orange", "forge:dyes/orange", "forge:wool/orange", "item.minecraft.firework_star.orange", 0xC06300), - MAGENTA ("magenta", "forge:dyes/magenta", "forge:wool/magenta", "item.minecraft.firework_star.magenta", 0xB51AB5), - LIGHT_BLUE("light_blue", "forge:dyes/light_blue", "forge:wool/light_blue", "item.minecraft.firework_star.light_blue", 0x6F84F1), - YELLOW ("yellow", "forge:dyes/yellow", "forge:wool/yellow", "item.minecraft.firework_star.yellow", 0xBFBF00), - LIME ("lime", "forge:dyes/lime", "forge:wool/lime", "item.minecraft.firework_star.lime", 0x6BF100), - PINK ("pink", "forge:dyes/pink", "forge:wool/pink", "item.minecraft.firework_star.pink", 0xF14675), - GRAY ("gray", "forge:dyes/gray", "forge:wool/gray", "item.minecraft.firework_star.gray", 0x535353), - LIGHT_GRAY("light_gray", "forge:dyes/light_gray", "forge:wool/light_gray", "item.minecraft.firework_star.light_gray", 0x939393), - CYAN ("cyan", "forge:dyes/cyan", "forge:wool/cyan", "item.minecraft.firework_star.cyan", 0x008787), - PURPLE ("purple", "forge:dyes/purple", "forge:wool/purple", "item.minecraft.firework_star.purple", 0x5E00C0), - BLUE ("blue", "forge:dyes/blue", "forge:wool/blue", "item.minecraft.firework_star.blue", 0x1313C0), - BROWN ("brown", "forge:dyes/brown", "forge:wool/brown", "item.minecraft.firework_star.brown", 0x4F2700), - GREEN ("green", "forge:dyes/green", "forge:wool/green", "item.minecraft.firework_star.green", 0x088700), - RED ("red", "forge:dyes/red", "forge:wool/red", "item.minecraft.firework_star.red", 0xA20F06), - BLACK ("black", "forge:dyes/black", "forge:wool/black", "item.minecraft.firework_star.black", 0x1F1F1F); + WHITE ("white", "c:dyes/white", "c:wools/white", "item.minecraft.firework_star.white", 0xFFFFFF), + ORANGE ("orange", "c:dyes/orange", "c:wools/orange", "item.minecraft.firework_star.orange", 0xC06300), + MAGENTA ("magenta", "c:dyes/magenta", "c:wools/magenta", "item.minecraft.firework_star.magenta", 0xB51AB5), + LIGHT_BLUE("light_blue", "c:dyes/light_blue", "c:wools/light_blue", "item.minecraft.firework_star.light_blue", 0x6F84F1), + YELLOW ("yellow", "c:dyes/yellow", "c:wools/yellow", "item.minecraft.firework_star.yellow", 0xBFBF00), + LIME ("lime", "c:dyes/lime", "c:wools/lime", "item.minecraft.firework_star.lime", 0x6BF100), + PINK ("pink", "c:dyes/pink", "c:wools/pink", "item.minecraft.firework_star.pink", 0xF14675), + GRAY ("gray", "c:dyes/gray", "c:wools/gray", "item.minecraft.firework_star.gray", 0x535353), + LIGHT_GRAY("light_gray", "c:dyes/light_gray", "c:wools/light_gray", "item.minecraft.firework_star.light_gray", 0x939393), + CYAN ("cyan", "c:dyes/cyan", "c:wools/cyan", "item.minecraft.firework_star.cyan", 0x008787), + PURPLE ("purple", "c:dyes/purple", "c:wools/purple", "item.minecraft.firework_star.purple", 0x5E00C0), + BLUE ("blue", "c:dyes/blue", "c:wools/blue", "item.minecraft.firework_star.blue", 0x1313C0), + BROWN ("brown", "c:dyes/brown", "c:wools/brown", "item.minecraft.firework_star.brown", 0x4F2700), + GREEN ("green", "c:dyes/green", "c:wools/green", "item.minecraft.firework_star.green", 0x088700), + RED ("red", "c:dyes/red", "c:wools/red", "item.minecraft.firework_star.red", 0xA20F06), + BLACK ("black", "c:dyes/black", "c:wools/black", "item.minecraft.firework_star.black", 0x1F1F1F); //@formatter:on + public static final StringRepresentable.EnumCodec CODEC = StringRepresentable.fromEnum(EnumColour::values); + public static final IntFunction BY_ID = ByIdMap.continuous(EnumColour::ordinal, values(), ByIdMap.OutOfBoundsStrategy.WRAP); + public static final StreamCodec STREAM_CODEC = ByteBufCodecs.idMapper(BY_ID, EnumColour::ordinal); + private final String name; private final ResourceLocation dyeTagName; private final ResourceLocation woolTagName; @@ -87,8 +96,8 @@ public enum EnumColour implements StringRepresentable { EnumColour(String name, String dyeTagName, String woolTagName, String unlocalizedName, int rgb) { this.name = name; - this.dyeTagName = new ResourceLocation(dyeTagName); - this.woolTagName = new ResourceLocation(woolTagName); + this.dyeTagName = ResourceLocation.parse(dyeTagName); + this.woolTagName = ResourceLocation.parse(woolTagName); this.unlocalizedName = unlocalizedName; this.rgb = rgb; } diff --git a/src/main/java/codechicken/lib/config/ConfigSyncManager.java b/src/main/java/codechicken/lib/config/ConfigSyncManager.java index 80233aec..ca026b18 100644 --- a/src/main/java/codechicken/lib/config/ConfigSyncManager.java +++ b/src/main/java/codechicken/lib/config/ConfigSyncManager.java @@ -3,6 +3,7 @@ import codechicken.lib.packet.PacketCustom; import com.google.common.base.Joiner; import net.covers1624.quack.util.CrashLock; +import net.minecraft.core.RegistryAccess; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.configuration.ServerConfigurationPacketListener; import net.minecraft.resources.ResourceLocation; @@ -11,17 +12,14 @@ import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; import net.neoforged.neoforge.common.NeoForge; import net.neoforged.neoforge.network.configuration.ICustomConfigurationTask; -import net.neoforged.neoforge.network.event.OnGameConfigurationEvent; +import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; -import java.util.function.BiConsumer; import java.util.function.Consumer; -import java.util.function.Supplier; import static codechicken.lib.CodeChickenLib.MOD_ID; import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; @@ -88,18 +86,18 @@ private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut eve } } - private static void onGameConfigurationEvent(OnGameConfigurationEvent event) { + private static void onGameConfigurationEvent(RegisterConfigurationTasksEvent event) { event.register(new ConfigSyncConfigurationTask(event.getListener())); } private record ConfigSyncConfigurationTask(ServerConfigurationPacketListener listener) implements ICustomConfigurationTask { - private static final Type TYPE = new Type(new ResourceLocation(MOD_ID, "config_sync")); + private static final Type TYPE = new Type(ResourceLocation.fromNamespaceAndPath(MOD_ID, "config_sync")); @Override public void run(Consumer sender) { if (!SYNC_MAP.isEmpty()) { - PacketCustom packet = new PacketCustom(NET_CHANNEL, L_CONFIG_SYNC); + PacketCustom packet = new PacketCustom(NET_CHANNEL, L_CONFIG_SYNC, null); packet.writeVarInt(SYNC_MAP.size()); for (Map.Entry entry : SYNC_MAP.entrySet()) { packet.writeResourceLocation(entry.getKey()); diff --git a/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java b/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java index 0b2fb196..714e9421 100644 --- a/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java +++ b/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java @@ -18,7 +18,7 @@ public class TomlConfigSerializer implements ConfigSerializer { @Override public void parse(Path file, ConfigCategoryImpl rootTag) throws IOException { - try (CommentedFileConfig tomlConfig = CommentedFileConfig.builder(file).preserveInsertionOrder().build()) { + try (CommentedFileConfig tomlConfig = CommentedFileConfig.builder(file).sync().preserveInsertionOrder().build()) { tomlConfig.load(); load("", rootTag, tomlConfig); } diff --git a/src/main/java/codechicken/lib/data/MCDataByteBuf.java b/src/main/java/codechicken/lib/data/MCDataByteBuf.java index 6d690d9d..17bd359c 100644 --- a/src/main/java/codechicken/lib/data/MCDataByteBuf.java +++ b/src/main/java/codechicken/lib/data/MCDataByteBuf.java @@ -2,10 +2,16 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import net.minecraft.core.RegistryAccess; import net.minecraft.nbt.ByteArrayTag; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; +import net.neoforged.neoforge.network.connection.ConnectionType; +import org.jetbrains.annotations.Nullable; /** * An {@link MCDataInput} and {@link MCDataOutput} implementation, @@ -16,13 +22,26 @@ public class MCDataByteBuf implements MCDataInput, MCDataOutput { protected final ByteBuf buf; + protected final @Nullable RegistryAccess registryAccess; public MCDataByteBuf() { - this(Unpooled.buffer()); + this(Unpooled.buffer(), null); + } + + public MCDataByteBuf(@Nullable RegistryAccess registryAccess) { + this(Unpooled.buffer(), registryAccess); } public MCDataByteBuf(ByteBuf buf) { + this(buf, null); + } + + public MCDataByteBuf(ByteBuf buf, @Nullable RegistryAccess registryAccess) { this.buf = buf; + if (registryAccess == null && buf instanceof RegistryFriendlyByteBuf rBuf) { + registryAccess = rBuf.registryAccess(); + } + this.registryAccess = registryAccess; } /** @@ -34,15 +53,23 @@ public FriendlyByteBuf toFriendlyByteBuf() { return buf instanceof FriendlyByteBuf ? (FriendlyByteBuf) buf : new FriendlyByteBuf(buf); } + public RegistryFriendlyByteBuf toRegistryFriendlyByteBuf() { + if (buf instanceof RegistryFriendlyByteBuf rBuf) return rBuf; + if (registryAccess == null) { + throw new RuntimeException("RegistryAccess required for this operation."); + } + return new RegistryFriendlyByteBuf(buf, registryAccess, ConnectionType.NEOFORGE); + } + public Tag toTag() { return new ByteArrayTag(buf.array()); } - public static MCDataByteBuf fromTag(Tag tag) { + public static MCDataByteBuf fromTag(Tag tag, RegistryAccess registries) { if (!(tag instanceof ByteArrayTag)) { throw new IllegalArgumentException("Expected ByteArrayNBT, got: " + tag.getClass().getSimpleName()); } - return new MCDataByteBuf(Unpooled.copiedBuffer(((ByteArrayTag) tag).getAsByteArray())); + return new MCDataByteBuf(Unpooled.copiedBuffer(((ByteArrayTag) tag).getAsByteArray()), registries); } public CompoundTag writeToNBT(CompoundTag tag, String key) { @@ -50,8 +77,30 @@ public CompoundTag writeToNBT(CompoundTag tag, String key) { return tag; } - public static MCDataByteBuf readFromNBT(CompoundTag tag, String key) { - return fromTag(tag.get(key)); + public static MCDataByteBuf readFromNBT(CompoundTag tag, String key, RegistryAccess registries) { + return fromTag(tag.get(key), registries); + } + + @Override + public MCDataOutput writeWithCodec(StreamEncoder codec, T thing) { + codec.encode(toFriendlyByteBuf(), thing); + return this; + } + + @Override + public MCDataOutput writeWithRegistryCodec(StreamEncoder codec, T thing) { + codec.encode(toRegistryFriendlyByteBuf(), thing); + return this; + } + + @Override + public T readWithCodec(StreamDecoder codec) { + return codec.decode(toFriendlyByteBuf()); + } + + @Override + public T readWithRegistryCodec(StreamDecoder codec) { + return codec.decode(toRegistryFriendlyByteBuf()); } //@formatter:off diff --git a/src/main/java/codechicken/lib/data/MCDataInput.java b/src/main/java/codechicken/lib/data/MCDataInput.java index b0d0c3d9..a85687d7 100644 --- a/src/main/java/codechicken/lib/data/MCDataInput.java +++ b/src/main/java/codechicken/lib/data/MCDataInput.java @@ -5,16 +5,16 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.EncoderException; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.core.Vec3i; +import net.minecraft.core.*; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.codec.StreamDecoder; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -532,7 +532,7 @@ default Cuboid6 readCuboid() { * @return The {@link ResourceLocation}. */ default ResourceLocation readResourceLocation() { - return new ResourceLocation(readString()); + return ResourceLocation.parse(readString()); } /** @@ -612,14 +612,7 @@ default CompoundTag readCompoundNBT() { * @return The {@link ItemStack}. */ default ItemStack readItemStack() { - if (!readBoolean()) return ItemStack.EMPTY; - - Item item = readRegistryIdDirect(BuiltInRegistries.ITEM); - int count = readVarInt(); - CompoundTag attachments = readNullableCompoundNBT(); - ItemStack stack = new ItemStack(item, count, attachments); - stack.setTag(readNullableCompoundNBT()); - return stack; + return readWithRegistryCodec(ItemStack.OPTIONAL_STREAM_CODEC); } /** @@ -628,15 +621,7 @@ default ItemStack readItemStack() { * @return The {@link FluidStack}. */ default FluidStack readFluidStack() { - if (!readBoolean()) return FluidStack.EMPTY; - - Fluid fluid = readRegistryIdDirect(BuiltInRegistries.FLUID); - int amount = readVarInt(); - CompoundTag tag = readNullableCompoundNBT(); - if (fluid == Fluids.EMPTY) { - return FluidStack.EMPTY; - } - return new FluidStack(fluid, amount, tag); + return readWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC); } /** @@ -645,7 +630,7 @@ default FluidStack readFluidStack() { * @return The {@link Component}. */ default MutableComponent readTextComponent() { - return requireNonNull(Component.Serializer.fromJson(readString())); + return requireNonNull(Component.Serializer.fromJson(readString(), RegistryAccess.EMPTY)); } /** @@ -671,6 +656,14 @@ default T readRegistryId() { ResourceLocation rName = readResourceLocation(); return readRegistryIdDirect(unsafeCast(requireNonNull(BuiltInRegistries.REGISTRY.get(rName), "Registry " + rName + " not found."))); } + + default T readWithCodec(StreamDecoder codec) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); + } + + default T readWithRegistryCodec(StreamDecoder codec) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); + } //endregion //region Netty diff --git a/src/main/java/codechicken/lib/data/MCDataOutput.java b/src/main/java/codechicken/lib/data/MCDataOutput.java index 96f1b64c..33a43cb7 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutput.java +++ b/src/main/java/codechicken/lib/data/MCDataOutput.java @@ -4,16 +4,14 @@ import codechicken.lib.vec.Vector3; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.EncoderException; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.core.Vec3i; -import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.*; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.StreamEncoder; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; import net.neoforged.neoforge.fluids.FluidStack; @@ -869,21 +867,7 @@ default MCDataOutput writeNullableCompoundNBT(@Nullable CompoundTag tag) { * @return The same stream. */ default MCDataOutput writeItemStack(ItemStack stack) { - if (stack.isEmpty()) { - writeBoolean(false); - } else { - writeBoolean(true); - Item item = stack.getItem(); - writeRegistryIdDirect(BuiltInRegistries.ITEM, item); - writeVarInt(stack.getCount()); - writeNullableCompoundNBT(stack.serializeAttachments()); - CompoundTag nbt = null; - if (item.canBeDepleted() || item.shouldOverrideMultiplayerNbt()) { - nbt = stack.getTag(); - } - writeNullableCompoundNBT(nbt); - } - return this; + return writeWithRegistryCodec(ItemStack.OPTIONAL_STREAM_CODEC, stack); } /** @@ -893,15 +877,7 @@ default MCDataOutput writeItemStack(ItemStack stack) { * @return The same stream. */ default MCDataOutput writeFluidStack(FluidStack stack) { - if (stack.isEmpty()) { - writeBoolean(false); - } else { - writeBoolean(true); - writeRegistryIdDirect(BuiltInRegistries.FLUID, stack.getFluid()); - writeVarInt(stack.getAmount()); - writeNullableCompoundNBT(stack.getTag()); - } - return this; + return writeWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC, stack); } /** @@ -911,7 +887,7 @@ default MCDataOutput writeFluidStack(FluidStack stack) { * @return The same stream. */ default MCDataOutput writeTextComponent(Component component) { - return writeString(Component.Serializer.toJson(component), 262144);//32kb + return writeString(Component.Serializer.toJson(component, RegistryAccess.EMPTY), 262144);//32kb } /** @@ -977,6 +953,14 @@ default MCDataOutput writeRegistryId(Registry registry, ResourceLocation writeRegistryIdDirect(registry, entry); return this; } + + default MCDataOutput writeWithCodec(StreamEncoder codec, T thing) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); + } + + default MCDataOutput writeWithRegistryCodec(StreamEncoder codec, T thing) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); + } //endregion //region Netty. diff --git a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java index 1d135291..871f4b60 100644 --- a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java +++ b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java @@ -60,7 +60,7 @@ public void addDynamicTexture(String dynamicInput, String outputTexture, int wid } public void addDynamicTexture(String dynamicInput, String outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { - addDynamicTexture(new ResourceLocation(modid, dynamicInput), new ResourceLocation(modid, outputTexture), width, height, topBorder, leftBorder, bottomBorder, rightBorder); + addDynamicTexture(ResourceLocation.fromNamespaceAndPath(modid, dynamicInput), ResourceLocation.fromNamespaceAndPath(modid, outputTexture), width, height, topBorder, leftBorder, bottomBorder, rightBorder); } public void addDynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputTexture, int width, int height, int border) { @@ -70,10 +70,10 @@ public void addDynamicTexture(ResourceLocation dynamicInput, ResourceLocation ou public void addDynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { try { if (!dynamicInput.getPath().endsWith(".png")) { - dynamicInput = new ResourceLocation(dynamicInput.getNamespace(), dynamicInput.getPath() + ".png"); + dynamicInput = ResourceLocation.fromNamespaceAndPath(dynamicInput.getNamespace(), dynamicInput.getPath() + ".png"); } if (!outputTexture.getPath().endsWith(".png")) { - outputTexture = new ResourceLocation(outputTexture.getNamespace(), outputTexture.getPath() + ".png"); + outputTexture = ResourceLocation.fromNamespaceAndPath(outputTexture.getNamespace(), outputTexture.getPath() + ".png"); } Resource inputResource = fileHelper.getResource(dynamicInput, PackType.CLIENT_RESOURCES); diff --git a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java index ca153916..e6cc11c9 100644 --- a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java +++ b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java @@ -354,7 +354,7 @@ public static class ClassCustomLoaderBuilder extends CustomLoaderBuilder { private @Nullable Class clazz; protected ClassCustomLoaderBuilder(SimpleItemModelBuilder parent) { - super(new ResourceLocation(MOD_ID, "class"), parent); + super(ResourceLocation.fromNamespaceAndPath(MOD_ID, "class"), parent); } public ClassCustomLoaderBuilder clazz(Class clazz) { @@ -388,11 +388,11 @@ protected CompositeLoaderBuilder(ResourceLocation loader, SimpleItemModelBuilder } public static CompositeLoaderBuilder forge(SimpleItemModelBuilder parent) { - return new CompositeLoaderBuilder(new ResourceLocation("forge", "composite"), parent); + return new CompositeLoaderBuilder(ResourceLocation.fromNamespaceAndPath("forge", "composite"), parent); } public static CompositeLoaderBuilder ccl(SimpleItemModelBuilder parent) { - return new CompositeLoaderBuilder(new ResourceLocation(MOD_ID, "item_composite"), parent); + return new CompositeLoaderBuilder(ResourceLocation.fromNamespaceAndPath(MOD_ID, "item_composite"), parent); } public CompositeLoaderBuilder nested(String name, Consumer cons) { diff --git a/src/main/java/codechicken/lib/datagen/LanguageProvider.java b/src/main/java/codechicken/lib/datagen/LanguageProvider.java index bc404c24..150c6d0b 100644 --- a/src/main/java/codechicken/lib/datagen/LanguageProvider.java +++ b/src/main/java/codechicken/lib/datagen/LanguageProvider.java @@ -75,13 +75,11 @@ private void save(CachedOutput cache, Object object, Path target) { public void add(Item key, String name) { add(key.getDescriptionId(), name); } public void add(Supplier key, String name) { add(key.get().asItem(), name); } public void add(ItemStack key, String name) { add(key.getDescriptionId(), name); } - public void add(Enchantment key, String name) { add(key.getDescriptionId(), name); } public void add(MobEffect key, String name) { add(key.getDescriptionId(), name); } public void add(EntityType key, String name) { add(key.getDescriptionId(), name); } public void addBlock(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addItem(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addItemStack(Supplier key, String name) { add(key.get().getDescriptionId(), name); } - public void addEnchantment(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addEffect(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addEntityType(Supplier> key, String name) { add(key.get().getDescriptionId(), name); } //@formatter:on diff --git a/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java index 38f9eaca..cbbf2702 100644 --- a/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java +++ b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java @@ -1,6 +1,9 @@ package codechicken.lib.datagen; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.RegistryAccess; import net.minecraft.data.loot.BlockLootSubProvider; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.item.Item; @@ -16,27 +19,27 @@ */ public abstract class NoValidationBLockLootSubProvider extends BlockLootSubProvider { - private final Map map; + private final Map, LootTable.Builder> map; - protected NoValidationBLockLootSubProvider() { - this(Set.of()); + protected NoValidationBLockLootSubProvider(HolderLookup.Provider registries) { + this(Set.of(), registries); } - protected NoValidationBLockLootSubProvider(Set explosionResistant) { - this(explosionResistant, FeatureFlagSet.of()); + protected NoValidationBLockLootSubProvider(Set explosionResistant, HolderLookup.Provider registries) { + this(explosionResistant, FeatureFlagSet.of(), registries); } - protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags) { - this(explosionResistant, flags, new HashMap<>()); + protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags, HolderLookup.Provider registries) { + this(explosionResistant, flags, new HashMap<>(), registries); } - protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags, Map map) { - super(explosionResistant, flags, map); + protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags, Map, LootTable.Builder> map, HolderLookup.Provider registries) { + super(explosionResistant, flags, map, registries); this.map = map; } @Override - public void generate(BiConsumer cons) { + public void generate(BiConsumer, LootTable.Builder> cons) { generate(); map.forEach(cons); } diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java index 73b779a6..4e871954 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java @@ -79,7 +79,7 @@ public final ResourceLocation getId() { public final BuiltRecipe build() { validate(); if (enableUnlocking) { - advancementBuilder.parent(new ResourceLocation("recipes/root")) + advancementBuilder.parent(ResourceLocation.withDefaultNamespace("recipes/root")) .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(id)) .rewards(AdvancementRewards.Builder.recipe(id)) .requirements(AdvancementRequirements.Strategy.OR); diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java index 4de6e13f..71e93471 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java @@ -7,7 +7,9 @@ import net.minecraft.advancements.critereon.EnterBlockTrigger; import net.minecraft.advancements.critereon.InventoryChangeTrigger; import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.data.CachedOutput; import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; @@ -30,18 +32,24 @@ public abstract class RecipeProvider implements DataProvider { private final Map recipes = new HashMap<>(); + private final CompletableFuture registries; private final PackOutput.PathProvider recipePath; private final PackOutput.PathProvider advancementPath; protected final String modId; - public RecipeProvider(PackOutput output, String modId) { + public RecipeProvider(CompletableFuture registries, PackOutput output, String modId) { + this.registries = registries; this.modId = modId; - recipePath = output.createPathProvider(PackOutput.Target.DATA_PACK, "recipes"); - advancementPath = output.createPathProvider(PackOutput.Target.DATA_PACK, "advancements"); + recipePath = output.createRegistryElementsPathProvider(Registries.RECIPE); + advancementPath = output.createRegistryElementsPathProvider(Registries.ADVANCEMENT); } @Override public final CompletableFuture run(CachedOutput cache) { + return registries.thenCompose(registries -> run(cache, registries)); + } + + private final CompletableFuture run(CachedOutput cache, HolderLookup.Provider registries) { registerRecipes(); List> futures = new LinkedList<>(); for (Map.Entry entry : recipes.entrySet()) { @@ -49,6 +57,7 @@ public final CompletableFuture run(CachedOutput cache) { RecipeBuilder.BuiltRecipe builtRecipe = entry.getValue().build(); futures.add(DataProvider.saveStable( cache, + registries, Recipe.CONDITIONAL_CODEC, Optional.of(new WithConditions<>(builtRecipe.conditions(), builtRecipe.recipe())), recipePath.json(id) @@ -58,6 +67,7 @@ public final CompletableFuture run(CachedOutput cache) { if (advancement != null) { futures.add(DataProvider.saveStable( cache, + registries, Advancement.CONDITIONAL_CODEC, Optional.of(new WithConditions<>(builtRecipe.conditions(), advancement.value())), advancementPath.json(id) diff --git a/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java index 130cdd32..1e0e66e2 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java @@ -36,7 +36,7 @@ public static SpecialCraftingRecipeBuilder builder(ItemStack id, Factory factory } public static SpecialCraftingRecipeBuilder builder(String id, Factory factory) { - return builder(new ResourceLocation(id), factory); + return builder(ResourceLocation.parse(id), factory); } public static SpecialCraftingRecipeBuilder builder(ResourceLocation id, Factory factory) { diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java index 2334b94f..a70097c8 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java @@ -264,7 +264,7 @@ public static void renderEntityInInventory(GuiRender render, double pX, double p public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, boolean flat, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, Entity pEntity) { render.pose().pushPose(); render.pose().translate(pX, pY, 50.0D); - render.pose().mulPoseMatrix((new Matrix4f()).scaling((float) pScale, (float) pScale, flat ? -1 : (float) (-pScale))); + render.pose().scale((float) pScale, (float) pScale, flat ? -1 : (float) (-pScale)); render.pose().mulPose(quat); Lighting.setupForEntityInInventory(); EntityRenderDispatcher entityrenderdispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java index c9c0a62f..1e1083c1 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java @@ -8,7 +8,6 @@ import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.SharedConstants; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; @@ -19,6 +18,7 @@ import net.minecraft.network.chat.Style; import net.minecraft.util.FormattedCharSequence; import net.minecraft.util.Mth; +import net.minecraft.util.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; @@ -36,6 +36,7 @@ * Created by brandon3055 on 03/09/2023 */ public class GuiTextField extends GuiElement implements BackgroundRender { + private static final RenderType HIGHLIGHT_TYPE = RenderType.create("text_field_highlight", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionColorShader)) .setColorLogicState(RenderStateShard.OR_REVERSE_COLOR_LOGIC) @@ -300,7 +301,7 @@ public void insertText(String text) { int selectStart = Math.min(cursorPos, highlightPos); int selectEnd = Math.max(cursorPos, highlightPos); int freeSpace = maxLength - value.length() - (selectStart - selectEnd); - String toInsert = SharedConstants.filterText(text); + String toInsert = StringUtil.filterText(text); int insertLen = toInsert.length(); if (freeSpace < insertLen) { toInsert = toInsert.substring(0, freeSpace); @@ -374,11 +375,17 @@ private int getWordPosition(int i1, int i2, boolean b) { if (i == -1) { i = l; } else { - while (b && i < l && value.charAt(i) == ' ') ++i; + while (b && i < l && value.charAt(i) == ' ') { + ++i; + } } } else { - while (b && i > 0 && value.charAt(i - 1) == ' ') --i; - while (i > 0 && value.charAt(i - 1) != ' ') --i; + while (b && i > 0 && value.charAt(i - 1) == ' ') { + --i; + } + while (i > 0 && value.charAt(i - 1) != ' ') { + --i; + } } } @@ -565,7 +572,7 @@ public boolean keyReleased(int key, int scancode, int modifiers, boolean consume public boolean charTyped(char charTyped, int charCode) { if (!canConsumeInput()) { return false; - } else if (SharedConstants.isAllowedChatCharacter(charTyped)) { + } else if (StringUtil.isAllowedChatCharacter(charTyped)) { if (isEditable()) { insertText(Character.toString(charTyped)); } @@ -672,6 +679,6 @@ public void tick(double mouseX, double mouseY) { tick++; } - public record TextField(GuiRectangle container, GuiTextField field) {} + public record TextField(GuiRectangle container, GuiTextField field) { } } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java index 4ef4cd96..c20a2cee 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java @@ -26,11 +26,11 @@ public class CursorHelper { public static final Logger LOGGER = LogManager.getLogger(); - public static final ResourceLocation DRAG = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/drag.png"); - public static final ResourceLocation RESIZE_H = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_h.png"); - public static final ResourceLocation RESIZE_V = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_v.png"); - public static final ResourceLocation RESIZE_TRBL = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_trbl.png"); - public static final ResourceLocation RESIZE_TLBR = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_tlbr.png"); + public static final ResourceLocation DRAG = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/drag.png"); + public static final ResourceLocation RESIZE_H = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_h.png"); + public static final ResourceLocation RESIZE_V = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_v.png"); + public static final ResourceLocation RESIZE_TRBL = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_trbl.png"); + public static final ResourceLocation RESIZE_TLBR = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_tlbr.png"); private static final Map cursors = new HashMap<>(); private static ResourceLocation active = null; @@ -97,4 +97,4 @@ public static void onResourceReload() { }); cursors.clear(); } -} \ No newline at end of file +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java index ce117c56..68c96a01 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java @@ -218,10 +218,10 @@ public void fill(RenderType type, double xMin, double yMin, double xMax, double Matrix4f mat = pose.last().pose(); VertexConsumer buffer = buffers.getBuffer(type); - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(colour).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(colour).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(colour).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(colour).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(colour); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(colour); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(colour); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(colour); //L-B flushIfUnBatched(); } @@ -246,10 +246,10 @@ public void gradientFillV(RenderType type, double xMin, double yMin, double xMax float eG = g(bottomColour); float eB = b(bottomColour); Matrix4f mat = pose.last().pose(); - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(sR, sG, sB, sA).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(sR, sG, sB, sA).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(eR, eG, eB, eA); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(sR, sG, sB, sA); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(sR, sG, sB, sA); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(eR, eG, eB, eA); //L-B this.flushIfUnBatched(); } @@ -274,10 +274,10 @@ public void gradientFillH(RenderType type, double xMin, double yMin, double xMax float eG = g(rightColour); float eB = b(rightColour); Matrix4f mat = pose.last().pose(); - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(eR, eG, eB, eA).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(eR, eG, eB, eA).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(sR, sG, sB, sA).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(sR, sG, sB, sA).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(eR, eG, eB, eA); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(eR, eG, eB, eA); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(sR, sG, sB, sA); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(sR, sG, sB, sA); //L-B this.flushIfUnBatched(); } @@ -544,10 +544,10 @@ public void sprite(RenderType type, double xMin, double yMin, double xMax, doubl public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { VertexConsumer buffer = buffers().getBuffer(type); Matrix4f mat = pose.last().pose(); - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV1()).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV0()).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV0()).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV1()).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV1()); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV0()); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV0()); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV1()); //L-B flushIfUnBatched(); } @@ -642,10 +642,10 @@ public void sprite(RenderType type, double xMin, double yMin, double xMax, doubl float[] v = { sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0() }; VertexConsumer buffer = buffers().getBuffer(type); Matrix4f mat = pose.last().pose(); - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]); //L-B flushIfUnBatched(); } @@ -759,10 +759,10 @@ public void partialSprite(RenderType type, double xMin, double yMin, double xMax float v1 = sprite.getV1(); float ul = u1 - u0; float vl = v1 - v0; - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u0 + (uMax * ul), v0 + (vMax * vl)).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u0 + (uMax * ul), v0 + (vMin * vl)).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u0 + (uMin * ul), v0 + (vMin * vl)).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u0 + (uMin * ul), v0 + (vMax * vl)).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMax * ul), v0 + (vMax * vl)); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMax * ul), v0 + (vMin * vl)); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMin * ul), v0 + (vMin * vl)); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMin * ul), v0 + (vMax * vl)); //L-B flushIfUnBatched(); } @@ -905,10 +905,10 @@ public void tex(Material material, double xMin, double yMin, double xMax, double TextureAtlasSprite sprite = material.sprite(); VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); Matrix4f mat = pose.last().pose(); - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV1()).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU1(), sprite.getV0()).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV0()).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(sprite.getU0(), sprite.getV1()).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV1()); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV0()); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV0()); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV1()); //L-B flushIfUnBatched(); } @@ -1004,10 +1004,10 @@ public void tex(Material material, double xMin, double yMin, double xMax, double float[] u = { sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0() }; float[] v = { sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0() }; Matrix4f mat = pose.last().pose(); - buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B - buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).endVertex(); //R-T - buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).endVertex(); //L-T - buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).endVertex(); //L-B + buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]); //R-B + buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]); //R-T + buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]); //L-T + buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]); //L-B flushIfUnBatched(); } @@ -1138,10 +1138,10 @@ private void bufferDynamic(VertexConsumer builder, Matrix4f mat, TextureAtlasSpr int w = tex.contents().width(); int h = tex.contents().height(); //@formatter:off - builder.vertex(mat, x, y + height, 0).color(red, green, blue, alpha).uv(tex.getU(textureX / w), tex.getV((textureY + height) / h)).endVertex(); - builder.vertex(mat, x + width, y + height, 0).color(red, green, blue, alpha).uv(tex.getU((textureX + width) / w), tex.getV((textureY + height) / h)).endVertex(); - builder.vertex(mat, x + width, y, 0).color(red, green, blue, alpha).uv(tex.getU((textureX + width) / w), tex.getV((textureY / h))).endVertex(); - builder.vertex(mat, x, y, 0).color(red, green, blue, alpha).uv(tex.getU(textureX / w), tex.getV((textureY / h))).endVertex(); + builder.addVertex(mat, x, y + height, 0).setColor(red, green, blue, alpha).setUv(tex.getU(textureX / w), tex.getV((textureY + height) / h)); + builder.addVertex(mat, x + width, y + height, 0).setColor(red, green, blue, alpha).setUv(tex.getU((textureX + width) / w), tex.getV((textureY + height) / h)); + builder.addVertex(mat, x + width, y, 0).setColor(red, green, blue, alpha).setUv(tex.getU((textureX + width) / w), tex.getV((textureY / h)) ); + builder.addVertex(mat, x, y, 0).setColor(red, green, blue, alpha).setUv(tex.getU(textureX / w), tex.getV((textureY / h)) ); //@formatter:on } @@ -1485,8 +1485,7 @@ public void renderItem(@Nullable LivingEntity entity, @Nullable Level level, Ite pose.pushPose(); pose.translate(x + (size / 2D), y + (size / 2D), size); try { - pose.mulPoseMatrix((new Matrix4f()).scaling(1.0F, -1.0F, 1.0F)); - pose.scale((float) size, (float) size, (float) size); + pose.scale((float) size, (float) -size, (float) size); boolean flag = !bakedmodel.usesBlockLight(); if (flag) Lighting.setupForFlatItems(); mc().getItemRenderer().render(stack, ItemDisplayContext.GUI, false, pose, buffers, 0xf000f0, OverlayTexture.NO_OVERLAY, bakedmodel); @@ -1496,9 +1495,7 @@ public void renderItem(@Nullable LivingEntity entity, @Nullable Level level, Ite CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item"); CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered"); crashreportcategory.setDetail("Item Type", () -> String.valueOf(stack.getItem())); - crashreportcategory.setDetail("Item Stack", () -> String.valueOf(stack.getItem())); - crashreportcategory.setDetail("Item Damage", () -> String.valueOf(stack.getDamageValue())); - crashreportcategory.setDetail("Item NBT", () -> String.valueOf(stack.getTag())); + crashreportcategory.setDetail("Item Components", () -> String.valueOf(stack.getComponents())); crashreportcategory.setDetail("Item Foil", () -> String.valueOf(stack.hasFoil())); throw new ReportedException(crashreport); } @@ -1567,7 +1564,7 @@ public void renderItemDecorations(ItemStack stack, double x, double y, double si } LocalPlayer localplayer = mc().player; - float f = localplayer == null ? 0.0F : localplayer.getCooldowns().getCooldownPercent(stack.getItem(), mc().getFrameTime()); + float f = localplayer == null ? 0.0F : localplayer.getCooldowns().getCooldownPercent(stack.getItem(), mc().getTimer().getGameTimeDeltaPartialTick(true)); if (f > 0.0F) { double i1 = y + Mth.floor(16.0F * (1.0F - f)); double j1 = i1 + Mth.ceil(16.0F * f); @@ -1699,8 +1696,8 @@ public static RenderType texType(ResourceLocation location) { } public static RenderType texColType(ResourceLocation location) { - return RenderType.create("tex_col_type", DefaultVertexFormat.POSITION_COLOR_TEX, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() - .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionColorTexShader)) + return RenderType.create("tex_col_type", DefaultVertexFormat.POSITION_TEX_COLOR, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() + .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionTexColorShader)) .setTextureState(new RenderStateShard.TextureStateShard(location, false, false)) .setTransparencyState(RenderStateShard.TRANSLUCENT_TRANSPARENCY) .setCullState(RenderStateShard.NO_CULL) diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java b/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java index 1b6ff101..9a5ddaa3 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java @@ -4,12 +4,14 @@ import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; import codechicken.lib.inventory.container.modular.ModularSlot; +import net.covers1624.quack.collection.FastStream; import net.minecraft.world.Container; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.EnchantmentEffectComponents; import net.minecraft.world.item.enchantment.EnchantmentHelper; import java.util.ArrayList; @@ -31,6 +33,13 @@ */ public class SlotGroup { + private static final EquipmentSlot[] ARMOR_SLOTS = new EquipmentSlot[] { + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + }; + public final int zone; public final List quickMoveTo; @@ -83,12 +92,12 @@ public void addPlayerBar(Inventory inventory) { public void addPlayerArmor(Inventory inventory) { for (int i = 0; i < 4; ++i) { - EquipmentSlot slot = EquipmentSlot.byTypeAndIndex(EquipmentSlot.Type.ARMOR, 3 - i); + EquipmentSlot slot = ARMOR_SLOTS[i]; addSlot(new ModularSlot(inventory, 39 - i) .onSet((oldStack, newStack) -> onEquipItem(inventory, slot, newStack, oldStack)) .setStackLimit(stack -> 1) - .setValidator(stack -> slot == Mob.getEquipmentSlotForItem(stack)) - .setCanRemove((player, stack) -> stack.isEmpty() || player.isCreative() || !EnchantmentHelper.hasBindingCurse(stack)) + .setValidator(stack -> slot == inventory.player.getEquipmentSlotForItem(stack)) + .setCanRemove((player, stack) -> stack.isEmpty() || player.isCreative() || !EnchantmentHelper.has(stack, EnchantmentEffectComponents.PREVENT_ARMOR_CHANGE)) ); } } diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java b/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java index 8b1fa0b5..dd707fa8 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java @@ -86,6 +86,6 @@ public Supplier getter(Supplier texture) { * @return A new Material for the specified gui texture. */ public Material getUncached(String texture) { - return new Material(getAtlasHolder().atlasLocation(), new ResourceLocation(modId, "gui/" + texture), getAtlasHolder()::getSprite); + return new Material(getAtlasHolder().atlasLocation(), ResourceLocation.fromNamespaceAndPath(modId, "gui/" + texture), getAtlasHolder()::getSprite); } } diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/Material.java b/src/main/java/codechicken/lib/gui/modular/sprite/Material.java index 741c7999..68b45d17 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/Material.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/Material.java @@ -89,7 +89,7 @@ public net.minecraft.client.resources.model.Material getVanillaMat() { * @return an un-cached material from a vanilla atlas. */ public static Material fromAtlas(ResourceLocation atlasLocation, String texture) { - return new Material(atlasLocation, new ResourceLocation(atlasLocation.getNamespace(), texture), e -> Minecraft.getInstance().getTextureAtlas(atlasLocation).apply(e)); + return new Material(atlasLocation, ResourceLocation.fromNamespaceAndPath(atlasLocation.getNamespace(), texture), e -> Minecraft.getInstance().getTextureAtlas(atlasLocation).apply(e)); } /** diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java index 3f2a4cd1..d1ee738d 100644 --- a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java +++ b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java @@ -40,8 +40,8 @@ public class ModAtlasHolder implements PreparableReloadListener, AutoCloseable { * e.g. "gui" will point to modid:atlases/gui.json */ public ModAtlasHolder(String modid, String atlasLocation, String atlasInfoLocation) { - this.atlasInfoLocation = new ResourceLocation(modid, atlasInfoLocation); - this.atlasLocation = new ResourceLocation(modid, atlasLocation); + this.atlasInfoLocation = ResourceLocation.fromNamespaceAndPath(modid, atlasInfoLocation); + this.atlasLocation = ResourceLocation.fromNamespaceAndPath(modid, atlasLocation); this.textureAtlas = new TextureAtlas(this.atlasLocation); this.modid = modid; } diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java index f16dfd95..83f691e3 100644 --- a/src/main/java/codechicken/lib/internal/ClientInit.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -75,8 +75,8 @@ private static void loadClientConfig() { } private static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register(new ResourceLocation(MOD_ID, "item_composite"), new CompositeItemModel()); - event.register(new ResourceLocation(MOD_ID, "class"), new ClassModelLoader()); + event.register(ResourceLocation.fromNamespaceAndPath(MOD_ID, "item_composite"), new CompositeItemModel()); + event.register(ResourceLocation.fromNamespaceAndPath(MOD_ID, "class"), new ClassModelLoader()); } private static void onResourceReload(RegisterClientReloadListenersEvent event) { diff --git a/src/main/java/codechicken/lib/internal/DataGenerators.java b/src/main/java/codechicken/lib/internal/DataGenerators.java index 67016d4d..0f09855d 100644 --- a/src/main/java/codechicken/lib/internal/DataGenerators.java +++ b/src/main/java/codechicken/lib/internal/DataGenerators.java @@ -52,39 +52,39 @@ public BlockTags(PackOutput output, CompletableFuture loo @Override protected void addTags(HolderLookup.Provider pProvider) { - tag(CCLTags.Blocks.WOOL) - .addTag(CCLTags.Blocks.WOOL_WHITE) - .addTag(CCLTags.Blocks.WOOL_ORANGE) - .addTag(CCLTags.Blocks.WOOL_MAGENTA) - .addTag(CCLTags.Blocks.WOOL_LIGHT_BLUE) - .addTag(CCLTags.Blocks.WOOL_YELLOW) - .addTag(CCLTags.Blocks.WOOL_LIME) - .addTag(CCLTags.Blocks.WOOL_PINK) - .addTag(CCLTags.Blocks.WOOL_GRAY) - .addTag(CCLTags.Blocks.WOOL_LIGHT_GRAY) - .addTag(CCLTags.Blocks.WOOL_CYAN) - .addTag(CCLTags.Blocks.WOOL_PURPLE) - .addTag(CCLTags.Blocks.WOOL_BLUE) - .addTag(CCLTags.Blocks.WOOL_BROWN) - .addTag(CCLTags.Blocks.WOOL_GREEN) - .addTag(CCLTags.Blocks.WOOL_RED) - .addTag(CCLTags.Blocks.WOOL_BLACK); - tag(CCLTags.Blocks.WOOL_WHITE).add(Blocks.WHITE_WOOL); - tag(CCLTags.Blocks.WOOL_ORANGE).add(Blocks.ORANGE_WOOL); - tag(CCLTags.Blocks.WOOL_MAGENTA).add(Blocks.MAGENTA_WOOL); - tag(CCLTags.Blocks.WOOL_LIGHT_BLUE).add(Blocks.LIGHT_BLUE_WOOL); - tag(CCLTags.Blocks.WOOL_YELLOW).add(Blocks.YELLOW_WOOL); - tag(CCLTags.Blocks.WOOL_LIME).add(Blocks.LIME_WOOL); - tag(CCLTags.Blocks.WOOL_PINK).add(Blocks.PINK_WOOL); - tag(CCLTags.Blocks.WOOL_GRAY).add(Blocks.GRAY_WOOL); - tag(CCLTags.Blocks.WOOL_LIGHT_GRAY).add(Blocks.LIGHT_GRAY_WOOL); - tag(CCLTags.Blocks.WOOL_CYAN).add(Blocks.CYAN_WOOL); - tag(CCLTags.Blocks.WOOL_PURPLE).add(Blocks.PURPLE_WOOL); - tag(CCLTags.Blocks.WOOL_BLUE).add(Blocks.BLUE_WOOL); - tag(CCLTags.Blocks.WOOL_BROWN).add(Blocks.BROWN_WOOL); - tag(CCLTags.Blocks.WOOL_GREEN).add(Blocks.GREEN_WOOL); - tag(CCLTags.Blocks.WOOL_RED).add(Blocks.RED_WOOL); - tag(CCLTags.Blocks.WOOL_BLACK).add(Blocks.BLACK_WOOL); + tag(CCLTags.Blocks.WOOLS) + .addTag(CCLTags.Blocks.WOOLS_WHITE) + .addTag(CCLTags.Blocks.WOOLS_ORANGE) + .addTag(CCLTags.Blocks.WOOLS_MAGENTA) + .addTag(CCLTags.Blocks.WOOLS_LIGHT_BLUE) + .addTag(CCLTags.Blocks.WOOLS_YELLOW) + .addTag(CCLTags.Blocks.WOOLS_LIME) + .addTag(CCLTags.Blocks.WOOLS_PINK) + .addTag(CCLTags.Blocks.WOOLS_GRAY) + .addTag(CCLTags.Blocks.WOOLS_LIGHT_GRAY) + .addTag(CCLTags.Blocks.WOOLS_CYAN) + .addTag(CCLTags.Blocks.WOOLS_PURPLE) + .addTag(CCLTags.Blocks.WOOLS_BLUE) + .addTag(CCLTags.Blocks.WOOLS_BROWN) + .addTag(CCLTags.Blocks.WOOLS_GREEN) + .addTag(CCLTags.Blocks.WOOLS_RED) + .addTag(CCLTags.Blocks.WOOLS_BLACK); + tag(CCLTags.Blocks.WOOLS_WHITE).add(Blocks.WHITE_WOOL); + tag(CCLTags.Blocks.WOOLS_ORANGE).add(Blocks.ORANGE_WOOL); + tag(CCLTags.Blocks.WOOLS_MAGENTA).add(Blocks.MAGENTA_WOOL); + tag(CCLTags.Blocks.WOOLS_LIGHT_BLUE).add(Blocks.LIGHT_BLUE_WOOL); + tag(CCLTags.Blocks.WOOLS_YELLOW).add(Blocks.YELLOW_WOOL); + tag(CCLTags.Blocks.WOOLS_LIME).add(Blocks.LIME_WOOL); + tag(CCLTags.Blocks.WOOLS_PINK).add(Blocks.PINK_WOOL); + tag(CCLTags.Blocks.WOOLS_GRAY).add(Blocks.GRAY_WOOL); + tag(CCLTags.Blocks.WOOLS_LIGHT_GRAY).add(Blocks.LIGHT_GRAY_WOOL); + tag(CCLTags.Blocks.WOOLS_CYAN).add(Blocks.CYAN_WOOL); + tag(CCLTags.Blocks.WOOLS_PURPLE).add(Blocks.PURPLE_WOOL); + tag(CCLTags.Blocks.WOOLS_BLUE).add(Blocks.BLUE_WOOL); + tag(CCLTags.Blocks.WOOLS_BROWN).add(Blocks.BROWN_WOOL); + tag(CCLTags.Blocks.WOOLS_GREEN).add(Blocks.GREEN_WOOL); + tag(CCLTags.Blocks.WOOLS_RED).add(Blocks.RED_WOOL); + tag(CCLTags.Blocks.WOOLS_BLACK).add(Blocks.BLACK_WOOL); } @Override @@ -101,39 +101,39 @@ public ItemTags(PackOutput output, CompletableFuture look @Override protected void addTags(HolderLookup.Provider pProvider) { - tag(CCLTags.Items.WOOL) - .addTag(CCLTags.Items.WOOL_WHITE) - .addTag(CCLTags.Items.WOOL_ORANGE) - .addTag(CCLTags.Items.WOOL_MAGENTA) - .addTag(CCLTags.Items.WOOL_LIGHT_BLUE) - .addTag(CCLTags.Items.WOOL_YELLOW) - .addTag(CCLTags.Items.WOOL_LIME) - .addTag(CCLTags.Items.WOOL_PINK) - .addTag(CCLTags.Items.WOOL_GRAY) - .addTag(CCLTags.Items.WOOL_LIGHT_GRAY) - .addTag(CCLTags.Items.WOOL_CYAN) - .addTag(CCLTags.Items.WOOL_PURPLE) - .addTag(CCLTags.Items.WOOL_BLUE) - .addTag(CCLTags.Items.WOOL_BROWN) - .addTag(CCLTags.Items.WOOL_GREEN) - .addTag(CCLTags.Items.WOOL_RED) - .addTag(CCLTags.Items.WOOL_BLACK); - tag(CCLTags.Items.WOOL_WHITE).add(Items.WHITE_WOOL); - tag(CCLTags.Items.WOOL_ORANGE).add(Items.ORANGE_WOOL); - tag(CCLTags.Items.WOOL_MAGENTA).add(Items.MAGENTA_WOOL); - tag(CCLTags.Items.WOOL_LIGHT_BLUE).add(Items.LIGHT_BLUE_WOOL); - tag(CCLTags.Items.WOOL_YELLOW).add(Items.YELLOW_WOOL); - tag(CCLTags.Items.WOOL_LIME).add(Items.LIME_WOOL); - tag(CCLTags.Items.WOOL_PINK).add(Items.PINK_WOOL); - tag(CCLTags.Items.WOOL_GRAY).add(Items.GRAY_WOOL); - tag(CCLTags.Items.WOOL_LIGHT_GRAY).add(Items.LIGHT_GRAY_WOOL); - tag(CCLTags.Items.WOOL_CYAN).add(Items.CYAN_WOOL); - tag(CCLTags.Items.WOOL_PURPLE).add(Items.PURPLE_WOOL); - tag(CCLTags.Items.WOOL_BLUE).add(Items.BLUE_WOOL); - tag(CCLTags.Items.WOOL_BROWN).add(Items.BROWN_WOOL); - tag(CCLTags.Items.WOOL_GREEN).add(Items.GREEN_WOOL); - tag(CCLTags.Items.WOOL_RED).add(Items.RED_WOOL); - tag(CCLTags.Items.WOOL_BLACK).add(Items.BLACK_WOOL); + tag(CCLTags.Items.WOOLS) + .addTag(CCLTags.Items.WOOLS_WHITE) + .addTag(CCLTags.Items.WOOLS_ORANGE) + .addTag(CCLTags.Items.WOOLS_MAGENTA) + .addTag(CCLTags.Items.WOOLS_LIGHT_BLUE) + .addTag(CCLTags.Items.WOOLS_YELLOW) + .addTag(CCLTags.Items.WOOLS_LIME) + .addTag(CCLTags.Items.WOOLS_PINK) + .addTag(CCLTags.Items.WOOLS_GRAY) + .addTag(CCLTags.Items.WOOLS_LIGHT_GRAY) + .addTag(CCLTags.Items.WOOLS_CYAN) + .addTag(CCLTags.Items.WOOLS_PURPLE) + .addTag(CCLTags.Items.WOOLS_BLUE) + .addTag(CCLTags.Items.WOOLS_BROWN) + .addTag(CCLTags.Items.WOOLS_GREEN) + .addTag(CCLTags.Items.WOOLS_RED) + .addTag(CCLTags.Items.WOOLS_BLACK); + tag(CCLTags.Items.WOOLS_WHITE).add(Items.WHITE_WOOL); + tag(CCLTags.Items.WOOLS_ORANGE).add(Items.ORANGE_WOOL); + tag(CCLTags.Items.WOOLS_MAGENTA).add(Items.MAGENTA_WOOL); + tag(CCLTags.Items.WOOLS_LIGHT_BLUE).add(Items.LIGHT_BLUE_WOOL); + tag(CCLTags.Items.WOOLS_YELLOW).add(Items.YELLOW_WOOL); + tag(CCLTags.Items.WOOLS_LIME).add(Items.LIME_WOOL); + tag(CCLTags.Items.WOOLS_PINK).add(Items.PINK_WOOL); + tag(CCLTags.Items.WOOLS_GRAY).add(Items.GRAY_WOOL); + tag(CCLTags.Items.WOOLS_LIGHT_GRAY).add(Items.LIGHT_GRAY_WOOL); + tag(CCLTags.Items.WOOLS_CYAN).add(Items.CYAN_WOOL); + tag(CCLTags.Items.WOOLS_PURPLE).add(Items.PURPLE_WOOL); + tag(CCLTags.Items.WOOLS_BLUE).add(Items.BLUE_WOOL); + tag(CCLTags.Items.WOOLS_BROWN).add(Items.BROWN_WOOL); + tag(CCLTags.Items.WOOLS_GREEN).add(Items.GREEN_WOOL); + tag(CCLTags.Items.WOOLS_RED).add(Items.RED_WOOL); + tag(CCLTags.Items.WOOLS_BLACK).add(Items.BLACK_WOOL); } @Override diff --git a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java b/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java index 19bee76d..bab079c9 100644 --- a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java +++ b/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java @@ -1,8 +1,8 @@ package codechicken.lib.internal; import net.covers1624.quack.util.CrashLock; +import net.neoforged.neoforge.client.event.ClientTickEvent; import net.neoforged.neoforge.common.NeoForge; -import net.neoforged.neoforge.event.TickEvent; import java.util.HashSet; import java.util.Set; @@ -23,15 +23,12 @@ public static void init() { NeoForge.EVENT_BUS.addListener(ExceptionMessageEventHandler::clientTick); } - private static void clientTick(TickEvent.ClientTickEvent event) { - if (event.phase == TickEvent.Phase.END) { - //Clear the known exceptions every 5 seconds. - long time = System.nanoTime(); - if (TimeUnit.NANOSECONDS.toSeconds(time - lastExceptionClear) > 5) { - lastExceptionClear = time; - exceptionMessageCache.clear(); - } + private static void clientTick(ClientTickEvent.Post event) { + //Clear the known exceptions every 5 seconds. + long time = System.nanoTime(); + if (TimeUnit.NANOSECONDS.toSeconds(time - lastExceptionClear) > 5) { + lastExceptionClear = time; + exceptionMessageCache.clear(); } } - } diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 14e7bac5..757bd70e 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -17,6 +17,7 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; +import org.joml.Matrix4fStack; import org.lwjgl.opengl.GL11; import javax.imageio.ImageIO; @@ -107,7 +108,7 @@ private RenderTask(ItemStack stack, int resolution, Path path) { protected NativeImage takeItemScreenshot() { long start = System.nanoTime(); Minecraft mc = Minecraft.getInstance(); - PoseStack pStack = RenderSystem.getModelViewStack(); + Matrix4fStack pStack = RenderSystem.getModelViewStack(); GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); if (target == null || target.width < resolution || target.height < resolution) { @@ -120,8 +121,8 @@ protected NativeImage takeItemScreenshot() { Matrix4f ortho = new Matrix4f().setOrtho(0, resolution * 16F / resolution, resolution * 16F / resolution, 0, -3000, 3000); RenderSystem.setProjectionMatrix(ortho, VertexSorting.ORTHOGRAPHIC_Z); - pStack.pushPose(); - pStack.setIdentity(); + pStack.pushMatrix(); + pStack.identity(); RenderSystem.applyModelViewMatrix(); target.bindWrite(true); @@ -145,7 +146,7 @@ protected NativeImage takeItemScreenshot() { image.flipY(); if (DEBUG) LOGGER.info("Screenshot: {}ns", System.nanoTime() - postRender); - pStack.popPose(); + pStack.popMatrix(); RenderSystem.applyModelViewMatrix(); target.unbindWrite(); @@ -276,7 +277,7 @@ private WebpRenderTask(ItemStack stack, int resolution, Path path, int fps, int @Override protected void serialize() throws IOException { Path tempDir = path.getParent().resolve(path.getFileName() + ".tmp"); - Files.createDirectory(tempDir); + Files.createDirectories(tempDir); LOGGER.info("Dumping frames to temp directory.."); int i = 0; List tempFiles = new ArrayList<>(frames.size() + 1); diff --git a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java index 6fe5213e..e93769e9 100644 --- a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java @@ -125,7 +125,7 @@ private static int dumpInfo(CommandContext ctx) { builder.append("Tile at position\n"); builder.append(" Tile Class: ").append(tile != null ? tile.getClass() : null).append("\n"); builder.append(" Tile Id: ").append(tile != null ? BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(tile.getType()) : null).append("\n"); - builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata() : null).append("\n"); + builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata(tile.getLevel().registryAccess()) : null).append("\n"); source.sendSuccess(() -> Component.literal(builder.toString()), false); return 0; diff --git a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java index 67f6b06e..44c2f1d6 100644 --- a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java @@ -30,9 +30,8 @@ private static int execute(CommandContext command) { ItemStack stack = player.hasItemInSlot(EquipmentSlot.MAINHAND) ? player.getMainHandItem() : player.getOffhandItem(); if (stack.isEmpty()) return 0; - String tag = stack.hasTag() ? stack.getTag().toString() : "Item has no NBT."; ctx.sendSuccess(() -> Component.literal("Registry Name: " + BuiltInRegistries.ITEM.getKey(stack.getItem())), false); - ctx.sendSuccess(() -> Component.literal("NBT : " + tag), false); + ctx.sendSuccess(() -> Component.literal("Components : " + stack.getComponents()), false); return 0; } } diff --git a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java index 8155057d..1e7191d0 100644 --- a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java +++ b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java @@ -28,7 +28,7 @@ @JeiPlugin public class JEIPlugin implements IModPlugin { - private static final ResourceLocation ID = new ResourceLocation(CodeChickenLib.MOD_ID, "jei_plugin"); + private static final ResourceLocation ID = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "jei_plugin"); public JEIPlugin() { } diff --git a/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java b/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java index 10976537..0ad56358 100644 --- a/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java +++ b/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java @@ -33,7 +33,7 @@ private ShaderInstance self() { ) private Program onGetOrCreate(ResourceProvider provider, Program.Type type, String s) throws IOException { if (self() instanceof CCShaderInstance instance) { - return instance.compileProgram(provider, type, new ResourceLocation(s)); + return instance.compileProgram(provider, type, ResourceLocation.parse(s)); } return callGetOrCreate(provider, type, s); diff --git a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java index b9665aa1..df072e31 100644 --- a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java +++ b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java @@ -5,12 +5,14 @@ import net.minecraft.resources.ResourceLocation; import net.neoforged.bus.api.IEventBus; +import static codechicken.lib.CodeChickenLib.MOD_ID; + /** * Created by covers1624 on 28/10/19. */ public class CCLNetwork { - public static final ResourceLocation NET_CHANNEL = new ResourceLocation("ccl:internal"); + public static final ResourceLocation NET_CHANNEL = ResourceLocation.fromNamespaceAndPath(MOD_ID, "internal"); public static final PacketCustomChannel channel = new PacketCustomChannel(NET_CHANNEL) .optional() .versioned(CodeChickenLib.container().getModInfo().getVersion().toString()) @@ -20,7 +22,6 @@ public class CCLNetwork { //Client handled. public static final int C_ADD_LANDING_EFFECTS = 1; - public static final int C_OPEN_CONTAINER = 10; public static final int C_GUI_SYNC = 20; //Server handled. diff --git a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java index ab11a8a0..88ddb353 100644 --- a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java +++ b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java @@ -1,25 +1,16 @@ package codechicken.lib.internal.network; -import codechicken.lib.inventory.container.ICCLContainerType; import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; import codechicken.lib.packet.PacketCustom; import codechicken.lib.render.particle.CustomParticleHandler; import codechicken.lib.vec.Vector3; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.MenuScreens; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.MenuAccess; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; import net.minecraft.world.level.block.state.BlockState; -import static codechicken.lib.internal.network.CCLNetwork.*; +import static codechicken.lib.internal.network.CCLNetwork.C_ADD_LANDING_EFFECTS; +import static codechicken.lib.internal.network.CCLNetwork.C_GUI_SYNC; import static java.util.Objects.requireNonNull; /** @@ -37,27 +28,7 @@ public void handlePacket(PacketCustom packet, Minecraft mc) { BlockState state = requireNonNull(mc.level).getBlockState(pos); CustomParticleHandler.addLandingEffects(mc.level, pos, state, vec, numParticles); } - case C_OPEN_CONTAINER -> handleOpenContainer(packet, mc); case C_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromServer(requireNonNull(mc.player), packet); } } - - @SuppressWarnings ("unchecked") - private void handleOpenContainer(PacketCustom packet, Minecraft mc) { - MenuType rawType = packet.readRegistryIdDirect(BuiltInRegistries.MENU); - int windowId = packet.readVarInt(); - Component name = packet.readTextComponent(); - if (rawType instanceof ICCLContainerType type) { - MenuScreens.getScreenFactory(rawType, mc, windowId, name) - .map(e -> (MenuScreens.ScreenConstructor) e) - .ifPresent(screenFactory -> { - LocalPlayer player = requireNonNull(mc.player); - AbstractContainerMenu container = type.create(windowId, player.getInventory(), packet); - Screen screen = screenFactory.create(container, player.getInventory(), name); - mc.player.containerMenu = ((MenuAccess) screen).getMenu(); - mc.setScreen(screen); - }); - - } - } } diff --git a/src/main/java/codechicken/lib/inventory/InventoryNBT.java b/src/main/java/codechicken/lib/inventory/InventoryNBT.java index caaf123d..7656fd07 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryNBT.java +++ b/src/main/java/codechicken/lib/inventory/InventoryNBT.java @@ -1,6 +1,7 @@ package codechicken.lib.inventory; import codechicken.lib.util.ArrayUtils; +import net.minecraft.core.RegistryAccess; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; @@ -14,10 +15,12 @@ */ public class InventoryNBT implements Container { + protected final RegistryAccess registries; protected ItemStack[] items; protected CompoundTag tag; - public InventoryNBT(int size, CompoundTag tag) { + public InventoryNBT(RegistryAccess registries, int size, CompoundTag tag) { + this.registries = registries; this.tag = tag; items = new ItemStack[size]; ArrayUtils.fillArray(items, ItemStack.EMPTY, (Objects::isNull)); @@ -25,12 +28,12 @@ public InventoryNBT(int size, CompoundTag tag) { } private void writeNBT() { - tag.put("items", InventoryUtils.writeItemStacksToTag(items, getMaxStackSize())); + tag.put("items", InventoryUtils.writeItemStacksToTag(registries, items, getMaxStackSize())); } private void readNBT() { if (tag.contains("items")) { - InventoryUtils.readItemStacksFromTag(items, tag.getList("items", 10)); + InventoryUtils.readItemStacksFromTag(registries, items, tag.getList("items", 10)); } } diff --git a/src/main/java/codechicken/lib/inventory/InventoryUtils.java b/src/main/java/codechicken/lib/inventory/InventoryUtils.java index abcf9595..28151919 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryUtils.java +++ b/src/main/java/codechicken/lib/inventory/InventoryUtils.java @@ -2,6 +2,7 @@ import codechicken.lib.util.ItemUtils; import com.google.common.base.Objects; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NumericTag; @@ -77,20 +78,19 @@ public static int incrStackSize(ItemStack base, int addition) { /** * NBT item saving function */ - public static ListTag writeItemStacksToTag(ItemStack[] items) { - return writeItemStacksToTag(items, 64); + public static ListTag writeItemStacksToTag(HolderLookup.Provider registries, ItemStack[] items) { + return writeItemStacksToTag(registries, items, 64); } /** * NBT item saving function with support for stack sizes > 32K */ - public static ListTag writeItemStacksToTag(ItemStack[] items, int maxQuantity) { + public static ListTag writeItemStacksToTag(HolderLookup.Provider registries, ItemStack[] items, int maxQuantity) { ListTag tagList = new ListTag(); for (int i = 0; i < items.length; i++) { CompoundTag tag = new CompoundTag(); tag.putShort("Slot", (short) i); - items[i].save(tag); - + tag.put("Item", items[i].saveOptional(registries)); if (maxQuantity > Short.MAX_VALUE) { tag.putInt("Quantity", items[i].getCount()); } else if (maxQuantity > Byte.MAX_VALUE) { @@ -105,11 +105,11 @@ public static ListTag writeItemStacksToTag(ItemStack[] items, int maxQuantity) { /** * NBT item loading function with support for stack sizes > 32K */ - public static void readItemStacksFromTag(ItemStack[] items, ListTag tagList) { + public static void readItemStacksFromTag(HolderLookup.Provider registries, ItemStack[] items, ListTag tagList) { for (int i = 0; i < tagList.size(); i++) { CompoundTag tag = tagList.getCompound(i); int b = tag.getShort("Slot"); - items[b] = ItemStack.of(tag); + items[b] = ItemStack.parseOptional(registries, tag.getCompound("Item")); Tag quantTag = tag.get("Quantity"); if (quantTag instanceof NumericTag quant) { items[b].setCount(quant.getAsInt()); @@ -210,11 +210,11 @@ public static boolean areStacksIdentical(ItemStack stack1, ItemStack stack2) { return stack1 == stack2; } - return stack1.getItem() == stack2.getItem() && stack1.getDamageValue() == stack2.getDamageValue() && stack1.getCount() == stack2.getCount() && Objects.equal(stack1.getTag(), stack2.getTag()); + return stack1.getItem() == stack2.getItem() && stack1.getDamageValue() == stack2.getDamageValue() && stack1.getCount() == stack2.getCount() && ItemStack.isSameItemSameComponents(stack2, stack1); } public static boolean canStack(ItemStack stack1, ItemStack stack2) { - return stack1.isEmpty() || stack2.isEmpty() || (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameTags(stack2, stack1)) && stack1.isStackable(); + return stack1.isEmpty() || stack2.isEmpty() || (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameComponents(stack2, stack1)) && stack1.isStackable(); } /** diff --git a/src/main/java/codechicken/lib/inventory/container/CCLMenuType.java b/src/main/java/codechicken/lib/inventory/container/CCLMenuType.java new file mode 100644 index 00000000..7e3ceefe --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/CCLMenuType.java @@ -0,0 +1,73 @@ +package codechicken.lib.inventory.container; + +import codechicken.lib.data.MCDataByteBuf; +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.flag.FeatureFlag; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; +import net.neoforged.neoforge.network.IContainerFactory; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; + +/** + * CCL sugared {@link MenuType}. + *

    + * Created by covers1624 on 28/10/19. + */ +public interface CCLMenuType extends IContainerFactory { + + static MenuType create(CCLMenuType factory) { + return new MenuType<>(factory, FeatureFlags.VANILLA_SET); + } + + static MenuType create(CCLMenuType factory, FeatureFlag... featureFlags) { + return new MenuType<>(factory, FeatureFlags.REGISTRY.subset(featureFlags)); + } + + /** + * Open a menu. + * + * @param player The player. + * @param provider The menu to open. + */ + static void openMenu(ServerPlayer player, MenuProvider provider) { + openMenu(player, provider, null); + } + + /** + * Open a menu. + * + * @param player The player. + * @param provider The menu to open. + * @param packet The packet factory for extra data. + */ + static void openMenu(ServerPlayer player, MenuProvider provider, @Nullable Consumer packet) { + if (packet != null) { + player.openMenu(provider, e -> packet.accept(new MCDataByteBuf(e))); + } else { + player.openMenu(provider); + } + } + + /** + * Overload of {@link #create(int, Inventory, RegistryFriendlyByteBuf)} using an {@link MCDataInput} instead. + * + * @param windowId The window id. + * @param inventory The player inventory. + * @param packet The packet. + * @return The new menu. + */ + T create(int windowId, Inventory inventory, @Nullable MCDataInput packet); + + @Override + default T create(int windowId, Inventory inv, @Nullable RegistryFriendlyByteBuf data) { + return create(windowId, inv, data != null ? new MCDataByteBuf(data) : null); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java index 627e5a09..0965cc09 100644 --- a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java +++ b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java @@ -111,7 +111,7 @@ public boolean moveItemStackTo(ItemStack stack, int startIndex, int endIndex, bo Slot slot = slots.get(slotIndex); ItemStack slotStack = slot.getItem(); - if (!slotStack.isEmpty() && ItemStack.isSameItemSameTags(stack, slotStack)) { + if (!slotStack.isEmpty() && ItemStack.isSameItemSameComponents(stack, slotStack)) { int totalStackSize = slotStack.getCount() + stack.getCount(); int maxStackSize = Math.min(stack.getMaxStackSize(), slot.getMaxStackSize()); if (totalStackSize <= maxStackSize) { diff --git a/src/main/java/codechicken/lib/inventory/container/ICCLContainerFactory.java b/src/main/java/codechicken/lib/inventory/container/ICCLContainerFactory.java deleted file mode 100644 index cb4aab03..00000000 --- a/src/main/java/codechicken/lib/inventory/container/ICCLContainerFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -package codechicken.lib.inventory.container; - -import codechicken.lib.data.MCDataInput; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; - -/** - * Created by covers1624 on 28/10/19. - */ -public interface ICCLContainerFactory extends MenuType.MenuSupplier { - - T create(int windowId, Inventory inventory, MCDataInput packet); - - @Override - default T create(int windowId, Inventory inventory) { - return create(windowId, inventory, null); - } -} diff --git a/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java b/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java deleted file mode 100644 index 74a5c9ff..00000000 --- a/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java +++ /dev/null @@ -1,40 +0,0 @@ -package codechicken.lib.inventory.container; - -import codechicken.lib.data.MCDataInput; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.flag.FeatureFlag; -import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.flag.FeatureFlags; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; - -/** - * Created by covers1624 on 28/10/19. - */ -public interface ICCLContainerType { - - static MenuType create(ICCLContainerFactory factory) { - return new CCLContainerType<>(factory, FeatureFlags.VANILLA_SET); - } - - static MenuType create(ICCLContainerFactory factory, FeatureFlag... featureFlags) { - return new CCLContainerType<>(factory, FeatureFlags.REGISTRY.subset(featureFlags)); - } - - T create(int windowId, Inventory inventory, MCDataInput packet); - - class CCLContainerType extends MenuType implements ICCLContainerType { - - public CCLContainerType(MenuType.MenuSupplier factory, FeatureFlagSet featureFlags) { - super(factory, featureFlags); - } - - @Override - public T create(int windowId, Inventory inventory, MCDataInput packet) { - if (constructor instanceof ICCLContainerFactory) { - return ((ICCLContainerFactory) constructor).create(windowId, inventory, packet); - } - return null; - } - } -} diff --git a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java index d08a9c52..3a307c96 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java +++ b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java @@ -2,6 +2,7 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.Tag; import java.util.Objects; @@ -34,9 +35,9 @@ public void markDirty() { } public abstract void fromBytes(MCDataInput buf); - public abstract Tag toTag(); + public abstract Tag toTag(HolderLookup.Provider holders); - public abstract void fromTag(Tag tag); + public abstract void fromTag(HolderLookup.Provider holders, Tag tag); public boolean isSameValue(T newValue) { return Objects.equals(value, newValue); diff --git a/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java index 23bc32c0..4d4222a1 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java @@ -2,10 +2,10 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.ByteTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -31,12 +31,12 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { + public Tag toTag(HolderLookup.Provider holders) { return ByteTag.valueOf(value); } @Override - public void fromTag(Tag tag) { + public void fromTag(HolderLookup.Provider holders, Tag tag) { value = ((NumericTag) tag).getAsByte() != 0; } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/ByteData.java b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java index c438282e..eed9b431 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/ByteData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java @@ -2,10 +2,10 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.ByteTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -31,12 +31,12 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { + public Tag toTag(HolderLookup.Provider holders) { return ByteTag.valueOf(value); } @Override - public void fromTag(Tag tag) { + public void fromTag(HolderLookup.Provider holders, Tag tag) { value = ((NumericTag) tag).getAsByte(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java index 990f9475..bd63e176 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java @@ -2,10 +2,10 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.DoubleTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -31,12 +31,12 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { + public Tag toTag(HolderLookup.Provider holders) { return DoubleTag.valueOf(value); } @Override - public void fromTag(Tag tag) { + public void fromTag(HolderLookup.Provider holders, Tag tag) { value = ((NumericTag) tag).getAsDouble(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/FloatData.java b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java index 6a135bca..be891ae4 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/FloatData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java @@ -2,10 +2,10 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.FloatTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -31,12 +31,12 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { + public Tag toTag(HolderLookup.Provider holders) { return FloatTag.valueOf(value); } @Override - public void fromTag(Tag tag) { + public void fromTag(HolderLookup.Provider holders, Tag tag) { value = ((NumericTag) tag).getAsFloat(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java index 1c2e78bc..8472aece 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java @@ -2,15 +2,20 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.Tag; import net.neoforged.neoforge.fluids.FluidStack; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Created by brandon3055 on 09/09/2023 */ public class FluidData extends AbstractDataStore { + private static final Logger LOGGER = LoggerFactory.getLogger(FluidData.class); + public FluidData() { super(FluidStack.EMPTY); } @@ -36,13 +41,17 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { - return value.writeToNBT(new CompoundTag()); + public Tag toTag(HolderLookup.Provider holders) { + return FluidStack.OPTIONAL_CODEC + .encodeStart(holders.createSerializationContext(NbtOps.INSTANCE), value) + .getOrThrow(); } @Override - public void fromTag(Tag tag) { - value = FluidStack.loadFluidStackFromNBT((CompoundTag) tag); + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = FluidStack.OPTIONAL_CODEC + .parse(holders.createSerializationContext(NbtOps.INSTANCE), tag) + .getOrThrow(); } @Override diff --git a/src/main/java/codechicken/lib/inventory/container/data/IntData.java b/src/main/java/codechicken/lib/inventory/container/data/IntData.java index fe43551a..65a9dbe7 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/IntData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/IntData.java @@ -2,10 +2,10 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.IntTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -31,12 +31,12 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { + public Tag toTag(HolderLookup.Provider holders) { return IntTag.valueOf(value); } @Override - public void fromTag(Tag tag) { + public void fromTag(HolderLookup.Provider holders, Tag tag) { value = ((NumericTag) tag).getAsInt(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/LongData.java b/src/main/java/codechicken/lib/inventory/container/data/LongData.java index 9b928d9a..eab6be8f 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/LongData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/LongData.java @@ -2,10 +2,10 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.LongTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -31,12 +31,12 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { + public Tag toTag(HolderLookup.Provider holders) { return LongTag.valueOf(value); } @Override - public void fromTag(Tag tag) { + public void fromTag(HolderLookup.Provider holders, Tag tag) { value = ((NumericTag) tag).getAsLong(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/ShortData.java b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java index 9a29d0dd..90762caa 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/ShortData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java @@ -2,10 +2,10 @@ import codechicken.lib.data.MCDataInput; import codechicken.lib.data.MCDataOutput; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.ShortTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -31,12 +31,12 @@ public void fromBytes(MCDataInput buf) { } @Override - public Tag toTag() { + public Tag toTag(HolderLookup.Provider holders) { return ShortTag.valueOf(value); } @Override - public void fromTag(Tag tag) { + public void fromTag(HolderLookup.Provider holders, Tag tag) { value = ((NumericTag) tag).getAsShort(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java index 3d8017dd..e4aae084 100644 --- a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java @@ -104,7 +104,7 @@ protected SlotGroup remoteSlotGroup() { */ public void sendPacketToClient(int packetId, Consumer packetWriter) { if (inventory.player instanceof ServerPlayer serverPlayer) { - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_GUI_SYNC); + PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_GUI_SYNC, inventory.player.registryAccess()); packet.writeByte(containerId); packet.writeByte((byte) packetId); packetWriter.accept(packet); @@ -119,7 +119,7 @@ public void sendPacketToClient(int packetId, Consumer packetWriter * @param packetWriter Use this callback to write your data to the packet. */ public void sendPacketToServer(int packetId, Consumer packetWriter) { - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, S_GUI_SYNC); + PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, S_GUI_SYNC, inventory.player.registryAccess()); packet.writeByte(containerId); packet.writeByte((byte) packetId); packetWriter.accept(packet); @@ -242,7 +242,7 @@ protected boolean moveItemStackTo(ItemStack stack, List targets, boolean r slot = targets.get(position); itemStack2 = slot.getItem(); - if (!itemStack2.isEmpty() && ItemStack.isSameItemSameTags(stack, itemStack2)) { + if (!itemStack2.isEmpty() && ItemStack.isSameItemSameComponents(stack, itemStack2)) { int l = itemStack2.getCount() + stack.getCount(); if (l <= Math.min(stack.getMaxStackSize(), slot.getMaxStackSize(stack))) { stack.setCount(0); diff --git a/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java b/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java deleted file mode 100644 index 8aa20e8a..00000000 --- a/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java +++ /dev/null @@ -1,157 +0,0 @@ -package codechicken.lib.item; - -import net.minecraft.sounds.SoundEvent; -import net.minecraft.util.LazyLoadedValue; -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.ArmorItem; -import net.minecraft.world.item.ArmorMaterial; -import net.minecraft.world.item.ArmorMaterials; -import net.minecraft.world.item.crafting.Ingredient; - -import java.util.function.Supplier; - -/** - * Created by covers1624 on 14/12/20. - */ -public class SimpleArmorMaterial implements ArmorMaterial { - - private final int[] durability; - private final int[] damageReduction; - private final int enchantability; - private final SoundEvent soundEvent; - private final LazyLoadedValue repairMaterial; - private final String textureName; - private final float toughness; - private final float knockbackResistance; - - public SimpleArmorMaterial(int[] durability, int[] damageReduction, int enchantability, SoundEvent soundEvent, Supplier repairMaterial, String textureName, float toughness, float knockbackResistance) { - this.durability = durability; - this.damageReduction = damageReduction; - this.enchantability = enchantability; - this.soundEvent = soundEvent; - this.repairMaterial = new LazyLoadedValue<>(repairMaterial); - this.textureName = textureName; - this.toughness = toughness; - this.knockbackResistance = knockbackResistance; - } - - public static Builder builder() { - return new Builder(); - } - - @Override - public int getDurabilityForType(ArmorItem.Type type) { - return durability[type.ordinal()]; - } - - @Override - public int getDefenseForType(ArmorItem.Type type) { - return damageReduction[type.ordinal()]; - } - - @Override - public int getEnchantmentValue() { - return enchantability; - } - - @Override - public SoundEvent getEquipSound() { - return soundEvent; - } - - @Override - public Ingredient getRepairIngredient() { - return repairMaterial.get(); - } - - @Override - public String getName() { - return textureName; - } - - @Override - public float getToughness() { - return toughness; - } - - @Override - public float getKnockbackResistance() { - return knockbackResistance; - } - - public static class Builder { - - private final int[] durability = new int[4]; - private final int[] damageReduction = new int[4]; - private int enchantability; - private SoundEvent soundEvent; - private Supplier repairMaterial; - private String textureName; - private float toughness; - private float knockbackResistance; - - private Builder() { - } - - public Builder durability(EquipmentSlot slot, int value) { - durability[slot.getIndex()] = value; - return this; - } - - public Builder durabilityFactor(int factor) { - for (ArmorItem.Type type : ArmorItem.Type.values()) { - durability[type.ordinal()] = ArmorMaterials.HEALTH_FUNCTION_FOR_TYPE.get(type) * factor; - } - return this; - } - - public Builder durability(int[] durability) { - System.arraycopy(durability, 0, this.durability, 0, 4); - return this; - } - - public Builder damageReduction(EquipmentSlot slot, int value) { - damageReduction[slot.getIndex()] = value; - return this; - } - - public Builder damageReduction(int[] damageReduction) { - System.arraycopy(damageReduction, 0, this.damageReduction, 0, 4); - return this; - } - - public Builder enchantability(int enchantability) { - this.enchantability = enchantability; - return this; - } - - public Builder soundEvent(SoundEvent soundEvent) { - this.soundEvent = soundEvent; - return this; - } - - public Builder repairMaterial(Supplier repairMaterial) { - this.repairMaterial = repairMaterial; - return this; - } - - public Builder textureName(String textureName) { - this.textureName = textureName; - return this; - } - - public Builder toughness(float toughness) { - this.toughness = toughness; - return this; - } - - public Builder knockbackResistance(float knockbackResistance) { - this.knockbackResistance = knockbackResistance; - return this; - } - - public SimpleArmorMaterial build() { - return new SimpleArmorMaterial(durability, damageReduction, enchantability, soundEvent, repairMaterial, textureName, toughness, knockbackResistance); - } - } -} diff --git a/src/main/java/codechicken/lib/item/package-info.java b/src/main/java/codechicken/lib/item/package-info.java deleted file mode 100644 index 7e7f203d..00000000 --- a/src/main/java/codechicken/lib/item/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@NonNullApi -package codechicken.lib.item; - -import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/model/CachedFormat.java b/src/main/java/codechicken/lib/model/CachedFormat.java index ece442e3..dcce52e9 100644 --- a/src/main/java/codechicken/lib/model/CachedFormat.java +++ b/src/main/java/codechicken/lib/model/CachedFormat.java @@ -95,7 +95,7 @@ private CachedFormat(VertexFormat format) { for (int i = 0; i < elementCount; i++) { VertexFormatElement element = elements.get(i); - switch (element.getUsage()) { + switch (element.usage()) { case POSITION: if (hasPosition) { throw new IllegalStateException("Found 2 position elements.."); @@ -118,7 +118,7 @@ private CachedFormat(VertexFormat format) { colorIndex = i; break; case UV: - switch (element.getIndex()) { + switch (element.index()) { case 0 -> { if (hasUV) { throw new IllegalStateException("Found 2 UV elements.."); diff --git a/src/main/java/codechicken/lib/model/ClassModelLoader.java b/src/main/java/codechicken/lib/model/ClassModelLoader.java index 18676f91..627c232a 100644 --- a/src/main/java/codechicken/lib/model/ClassModelLoader.java +++ b/src/main/java/codechicken/lib/model/ClassModelLoader.java @@ -40,7 +40,7 @@ public Geometry read(JsonObject jsonObject, JsonDeserializationContext deseriali public record Geometry(Constructor ctor) implements IUnbakedGeometry { @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { try { return ctor.newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) { diff --git a/src/main/java/codechicken/lib/model/CompositeItemModel.java b/src/main/java/codechicken/lib/model/CompositeItemModel.java index 1bdd8e54..db0efb2d 100644 --- a/src/main/java/codechicken/lib/model/CompositeItemModel.java +++ b/src/main/java/codechicken/lib/model/CompositeItemModel.java @@ -61,13 +61,13 @@ public Geometry read(JsonObject jsonObject, JsonDeserializationContext ctx) thro public record Geometry(Map children, List itemPasses) implements IUnbakedGeometry { @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { TextureAtlasSprite particle = spriteGetter.apply(context.getMaterial("particle")); ModelState effectiveState = composeState(context.getRootTransform(), modelState); ImmutableMap children = FastStream.of(this.children.entrySet()) .filter(e -> context.isComponentVisible(e.getKey(), true)) - .toImmutableMap(Map.Entry::getKey, e -> e.getValue().bake(baker, e.getValue(), spriteGetter, effectiveState, modelLocation, true)); + .toImmutableMap(Map.Entry::getKey, e -> e.getValue().bake(baker, e.getValue(), spriteGetter, effectiveState, true)); ImmutableList itemPasses = FastStream.of(this.itemPasses) .map(children::get) diff --git a/src/main/java/codechicken/lib/model/ItemQuadBakery.java b/src/main/java/codechicken/lib/model/ItemQuadBakery.java index 2cdac73c..6f47991b 100644 --- a/src/main/java/codechicken/lib/model/ItemQuadBakery.java +++ b/src/main/java/codechicken/lib/model/ItemQuadBakery.java @@ -28,7 +28,7 @@ public static List bakeItem(ModelState state, TextureAtlasSprite... s for (int i = 0; i < sprites.length; i++) { TextureAtlasSprite sprite = sprites[i]; List unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite); - quads.addAll(UnbakedGeometryHelper.bakeElements(unbaked, e -> sprite, state, new ResourceLocation("ccl:dynamic"))); + quads.addAll(UnbakedGeometryHelper.bakeElements(unbaked, e -> sprite, state)); } return quads; } diff --git a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java index acfc81c3..40ddeafe 100644 --- a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java @@ -3,7 +3,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ConfigurationTask; -import net.neoforged.neoforge.network.event.OnGameConfigurationEvent; +import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent; import org.jetbrains.annotations.ApiStatus; import java.util.function.Consumer; @@ -36,7 +36,7 @@ interface IServerPacketHandler extends ICustomPacketHandler { } /** - * Used with {@link OnGameConfigurationEvent} to send packets to the client during the configuration phase. + * Used with {@link RegisterConfigurationTasksEvent} to send packets to the client during the configuration phase. */ interface IClientConfigurationPacketHandler extends ICustomPacketHandler { diff --git a/src/main/java/codechicken/lib/packet/PacketCustom.java b/src/main/java/codechicken/lib/packet/PacketCustom.java index 1284fd5f..6425ecf3 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustom.java +++ b/src/main/java/codechicken/lib/packet/PacketCustom.java @@ -1,18 +1,19 @@ package codechicken.lib.packet; import codechicken.lib.data.MCDataByteBuf; +import codechicken.lib.data.MCDataOutput; import codechicken.lib.math.MathHelper; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.core.Vec3i; +import net.minecraft.core.*; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceKey; @@ -25,6 +26,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.network.connection.ConnectionType; import org.jetbrains.annotations.Nullable; import java.nio.*; @@ -36,22 +38,25 @@ public final class PacketCustom extends MCDataByteBuf { private final ResourceLocation channel; private final boolean inbound; private final int type; + private final @Nullable RegistryAccess registryAccess; PacketCustom(Pkt pkt) { - super(pkt.data); - channel = pkt.id; + super(pkt.data, pkt.registryAccess); + channel = pkt.type().id(); inbound = true; type = readUByte(); + registryAccess = pkt.registryAccess(); } - public PacketCustom(ResourceLocation channel, int type) { - super(Unpooled.buffer()); + public PacketCustom(ResourceLocation channel, int type, @Nullable RegistryAccess registryAccess) { + super(Unpooled.buffer(), registryAccess); if (!MathHelper.between(0, type, 255)) { throw new RuntimeException("Invalid packet type, Must be between 0 and 255. Got: " + type); } this.channel = channel; inbound = false; this.type = type; + this.registryAccess = registryAccess; writeByte(type); } @@ -70,7 +75,7 @@ public ResourceLocation getChannel() { public CustomPacketPayload toCustomPayload() { if (isInbound()) throw new RuntimeException("Unable to send an inbound packet."); - return new Pkt(channel, toFriendlyByteBuf()); + return new Pkt(new CustomPacketPayload.Type<>(channel), registryAccess, toFriendlyByteBuf()); } // region Server -> Client @@ -194,13 +199,6 @@ public void sendToServer() { //@formatter:on //endregion - record Pkt(ResourceLocation id, ByteBuf data) implements CustomPacketPayload { - - @Override - public void write(FriendlyByteBuf buf) { - data.markReaderIndex(); - buf.writeBytes(data); - data.resetReaderIndex(); - } + record Pkt(Type type, @Nullable RegistryAccess registryAccess, ByteBuf data) implements CustomPacketPayload { } } diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java index cb96960c..dbc1d3ab 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -5,14 +5,19 @@ import codechicken.lib.packet.ICustomPacketHandler.IServerConfigurationPacketHandler; import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; import net.minecraft.client.Minecraft; +import net.minecraft.core.RegistryAccess; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.loading.FMLEnvironment; -import net.neoforged.neoforge.network.event.RegisterPayloadHandlerEvent; -import net.neoforged.neoforge.network.handling.ISynchronizedWorkHandler; -import net.neoforged.neoforge.network.registration.IPayloadRegistrar; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; +import net.neoforged.neoforge.network.registration.HandlerThread; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,63 +84,70 @@ public void init(IEventBus modBus) { modBus.addListener(this::onRegisterPayloadHandlerEvent); } - private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlerEvent event) { - IPayloadRegistrar registrar = event.registrar(channel.getNamespace()); + private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event) { + PayloadRegistrar registrar = event.registrar(channel.getNamespace()); if (optional) registrar = registrar.optional(); if (version != null) registrar = registrar.versioned(version); - - registrar.play( - channel, - this::read, - handlers -> { - handlers.client((payload, context) -> { - if (client != null) { - enqueue(context.workHandler(), payload, () -> { - client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); - }); - } - }); - handlers.server((payload, context) -> { - if (server != null) { - enqueue(context.workHandler(), payload, () -> { - server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player().orElseThrow()); - }); - } - }); + registrar = registrar.executesOn(HandlerThread.NETWORK); + + CustomPacketPayload.Type type = new CustomPacketPayload.Type<>(channel); + StreamCodec codec = StreamCodec.of( + (buf, p) -> { + p.data().markReaderIndex(); + buf.writeBytes(p.data()); + p.data().resetReaderIndex(); + }, + buf -> { + RegistryAccess access = buf instanceof RegistryFriendlyByteBuf b ? b.registryAccess() : null; + return new PacketCustom.Pkt(type, access, buf.readBytes(buf.readableBytes())); } ); - registrar.configuration( - channel, - this::read, - handlers -> { - handlers.client((payload, context) -> { - if (clientConfiguration != null) { - enqueue(context.workHandler(), payload, () -> { - clientConfiguration.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); - }); + registrar.playBidirectional( + type, + codec, + (payload, context) -> { + switch (context.flow()) { + case CLIENTBOUND -> { + if (client != null) { + enqueue(context, payload, () -> { + client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + } + } + case SERVERBOUND -> { + if (server != null) { + enqueue(context, payload, () -> { + server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player()); + }); + } } - }); + } + } ); - } - - private PacketCustom.Pkt read(FriendlyByteBuf buf) { - return new PacketCustom.Pkt( - channel, - buf.readBytes(buf.readableBytes()) + registrar.configurationToClient( + type, + codec, + (payload, context) -> { + if (clientConfiguration != null) { + enqueue(context, payload, () -> { + clientConfiguration.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + } + } ); } - private static void enqueue(ISynchronizedWorkHandler workHandler, PacketCustom.Pkt payload, Runnable runnable) { - workHandler.submitAsync(() -> { + private static void enqueue(IPayloadContext context, PacketCustom.Pkt payload, Runnable runnable) { + context.enqueueWork(() -> { try { runnable.run(); } finally { payload.data().release(); } }).exceptionally(ex -> { - LOGGER.error("Error processing packet on channel {}", payload.id(), ex); + LOGGER.error("Error processing packet on channel {}", payload.type().id(), ex); return null; }); } diff --git a/src/main/java/codechicken/lib/raytracer/RayTracer.java b/src/main/java/codechicken/lib/raytracer/RayTracer.java index 2fd14b24..563a4075 100644 --- a/src/main/java/codechicken/lib/raytracer/RayTracer.java +++ b/src/main/java/codechicken/lib/raytracer/RayTracer.java @@ -1,10 +1,7 @@ package codechicken.lib.raytracer; import codechicken.lib.vec.Vector3; -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.ClipContext; @@ -13,11 +10,8 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.neoforged.neoforge.common.NeoForgeMod; import org.jetbrains.annotations.Nullable; -import static java.util.Objects.requireNonNull; - public class RayTracer { @Nullable @@ -36,28 +30,16 @@ public static BlockHitResult retraceBlock(BlockGetter level, Player player, Bloc return baseTraceResult; } - private static double getBlockReachDistance_server(Player player) { - return player.getAttributeValue(NeoForgeMod.BLOCK_REACH.value()); - } - - private static double getBlockReachDistance_client(Player player) { - AttributeInstance reach = player.getAttribute(NeoForgeMod.BLOCK_REACH.value()); - if (reach != null) return reach.getValue(); - - // We may not have NeoForge on the client. - return requireNonNull(Minecraft.getInstance().gameMode).getPickRange(); - } - public static BlockHitResult retrace(Player player) { return retrace(player, ClipContext.Block.OUTLINE); } public static BlockHitResult retrace(Player player, ClipContext.Block blockMode) { - return retrace(player, getBlockReachDistance(player), blockMode, ClipContext.Fluid.NONE); + return retrace(player, player.blockInteractionRange(), blockMode, ClipContext.Fluid.NONE); } public static BlockHitResult retrace(Player player, ClipContext.Block blockMode, ClipContext.Fluid fluidMode) { - return retrace(player, getBlockReachDistance(player), blockMode, fluidMode); + return retrace(player, player.blockInteractionRange(), blockMode, fluidMode); } public static BlockHitResult retrace(Player player, double reach, ClipContext.Block blockMode) { @@ -79,17 +61,10 @@ public static Vec3 getStartVec(Player player) { return getCorrectedHeadVec(player); } - public static double getBlockReachDistance(Player player) { - if (player instanceof ServerPlayer) return getBlockReachDistance_server(player); - if (player.level().isClientSide) return getBlockReachDistance_client(player); - // /shrug? we tried? - return 5D; - } - public static Vec3 getEndVec(Player player) { Vec3 headVec = getCorrectedHeadVec(player); Vec3 lookVec = player.getViewVector(1.0F); - double reach = getBlockReachDistance(player); + double reach = player.blockInteractionRange(); return headVec.add(lookVec.x * reach, lookVec.y * reach, lookVec.z * reach); } diff --git a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java index 148a7844..3faeda69 100644 --- a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java +++ b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java @@ -5,9 +5,10 @@ import net.covers1624.quack.util.CrashLock; import net.minecraft.world.phys.BlockHitResult; import net.neoforged.bus.api.EventPriority; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.RenderFrameEvent; import net.neoforged.neoforge.client.event.RenderHighlightEvent; import net.neoforged.neoforge.common.NeoForge; -import net.neoforged.neoforge.event.TickEvent; public class CCRenderEventHandler { @@ -23,16 +24,12 @@ public static void init() { NeoForge.EVENT_BUS.addListener(EventPriority.LOW, CCRenderEventHandler::onBlockHighlight); } - private static void clientTick(TickEvent.ClientTickEvent event) { - if (event.phase == TickEvent.Phase.END) { - renderTime++; - } + private static void clientTick(ClientTickEvent.Post event) { + renderTime++; } - private static void renderTick(TickEvent.RenderTickEvent event) { - if (event.phase == TickEvent.Phase.START) { - renderFrame = event.renderTickTime; - } + private static void renderTick(RenderFrameEvent.Pre event) { + renderFrame = event.getPartialTick().getGameTimeDeltaPartialTick(true); } private static void onBlockHighlight(RenderHighlightEvent.Block event) { diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java index 82dfcfd0..8435d695 100644 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ b/src/main/java/codechicken/lib/render/CCRenderState.java @@ -16,7 +16,6 @@ import codechicken.lib.vec.Matrix4; import codechicken.lib.vec.Vector3; import codechicken.lib.vec.Vertex5; -import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.vertex.*; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LevelRenderer; @@ -31,6 +30,8 @@ import net.neoforged.neoforge.fluids.FluidStack; import org.jetbrains.annotations.Nullable; +import java.util.List; + import static java.util.Objects.requireNonNull; /** @@ -99,36 +100,6 @@ public static CCRenderState instance() { return instances.get(); } - /** - * Bind this {@link CCRenderState} instance to the {@link Tesselator} buffer - * and prepare to start drawing vertices for the given mode and {@link VertexFormat}. - * - * @param mode The Draw Mode. - * @param format The {@link VertexFormat}. - * @return The {@link BufferBuilder} instance from {@link Tesselator}. - */ - public BufferBuilder startDrawing(VertexFormat.Mode mode, VertexFormat format) { - BufferBuilder r = Tesselator.getInstance().getBuilder(); - r.begin(mode, format); - bind(r); - return r; - } - - /** - * Bind this {@link CCRenderState} instance to the given {@link BufferBuilder} - * and prepare to start drawing vertices for the given mode and {@link VertexFormat}. - * - * @param mode The Draw Mode. - * @param format The {@link VertexFormat}. - * @param buffer The {@link BufferBuilder} to bind to. - * @return The same {@link BufferBuilder} that was passed in. - */ - public BufferBuilder startDrawing(VertexFormat.Mode mode, VertexFormat format, BufferBuilder buffer) { - buffer.begin(mode, format); - bind(buffer); - return buffer; - } - /** * Bind this {@link CCRenderState} instance to the given {@link BufferBuilder}. * @@ -261,39 +232,23 @@ public void writeVert() { if (sprite != null && r instanceof ISpriteAwareVertexConsumer cons) { cons.sprite(sprite); } - ImmutableList elements = fmt.getElements(); - for (int e = 0; e < elements.size(); e++) { - VertexFormatElement fmte = elements.get(e); - switch (fmte.getUsage()) { - case POSITION: - r.vertex(vert.vec.x, vert.vec.y, vert.vec.z); - break; - case UV: - int idx = fmte.getIndex(); - switch (idx) { - case 0 -> r.uv((float) vert.uv.u, (float) vert.uv.v); - case 1 -> r.overlayCoords(overlay); - case 2 -> r.uv2(brightness); + List elements = fmt.getElements(); + for (VertexFormatElement fmte : elements) { + switch (fmte.usage()) { + case POSITION -> r.addVertex((float) vert.vec.x, (float) vert.vec.y, (float) vert.vec.z); + case UV -> { + switch (fmte.index()) { + case 0 -> r.setUv((float) vert.uv.u, (float) vert.uv.v); + case 1 -> r.setOverlay(overlay); + case 2 -> r.setLight(brightness); + default -> throw new UnsupportedOperationException("Unknown UV index. " + fmte.index()); } - break; - case COLOR: - if (r instanceof BufferBuilder && ((BufferBuilder) r).defaultColorSet) { - //-_- Fucking mojang.. - ((BufferBuilder) r).nextElement(); - } else { - r.color(colour >>> 24, colour >> 16 & 0xFF, colour >> 8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF); - } - break; - case NORMAL: - r.normal((float) normal.x, (float) normal.y, (float) normal.z); - break; - case PADDING: - break; - default: - throw new UnsupportedOperationException("Generic vertex format element"); + } + case COLOR -> r.setColor(colour >>> 24, colour >> 16 & 0xFF, colour >> 8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF); + case NORMAL -> r.setNormal((float) normal.x, (float) normal.y, (float) normal.z); + default -> throw new UnsupportedOperationException("Generic vertex format element"); } } - r.endVertex(); } public void setBrightness(BlockAndTintGetter world, BlockPos pos) { @@ -327,8 +282,4 @@ public VertexConsumer getConsumer() { public VertexFormat getVertexFormat() { return requireNonNull(fmt, "VertexFormat is not bound."); } - - public void draw() { - Tesselator.getInstance().end(); - } } diff --git a/src/main/java/codechicken/lib/render/RenderUtils.java b/src/main/java/codechicken/lib/render/RenderUtils.java index cd5717cb..0217c4df 100644 --- a/src/main/java/codechicken/lib/render/RenderUtils.java +++ b/src/main/java/codechicken/lib/render/RenderUtils.java @@ -139,35 +139,35 @@ public static void makeFluidQuadVertices(List vertices, Vector3 base, V * @param a Alpha channel. */ public static void bufferCuboidSolid(VertexConsumer builder, Cuboid6 c, float r, float g, float b, float a) { - builder.vertex(c.min.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); - builder.vertex(c.max.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); } public static void bufferHitbox(Matrix4 mat, MultiBufferSource getter, Camera renderInfo, Cuboid6 cuboid) { @@ -215,8 +215,8 @@ private static void bufferLinePair(VertexConsumer builder, double x1, double y1, Vector3 v1 = vectors[0].set(x1, y1, z1).subtract(x2, y2, z2); double d = v1.mag(); v1.divide(d); - builder.vertex(x1, y1, z1).color(r, g, b, a).normal((float) v1.x, (float) v1.y, (float) v1.z).endVertex(); - builder.vertex(x2, y2, z2).color(r, g, b, a).normal((float) v1.x, (float) v1.y, (float) v1.z).endVertex(); + builder.addVertex((float) x1, (float) y1, (float) z1).setColor(r, g, b, a).setNormal((float) v1.x, (float) v1.y, (float) v1.z); + builder.addVertex((float) x2, (float) y2, (float) z2).setColor(r, g, b, a).setNormal((float) v1.x, (float) v1.y, (float) v1.z); } public static Matrix4 getMatrix(Matrix4 in, Vector3 translation, Rotation rotation, double scale) { diff --git a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java index ca2ea884..ecfc11d3 100644 --- a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java +++ b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java @@ -121,7 +121,7 @@ private static void handleCaughtException(Throwable t, BlockState inState, Block builder.append(" Tile at position\n"); builder.append(" Tile Class: ").append(tile != null ? tile.getClass() : null).append("\n"); builder.append(" Tile Id: ").append(tile != null ? BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(tile.getType()) : null).append("\n"); - builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata() : null).append("\n"); + builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata(tile.getLevel().registryAccess()) : null).append("\n"); builder.append("This functionality can be disabled in the CCL config file.\n"); if (ClientInit.messagePlayerOnRenderExceptionCaught) { builder.append("You can also turn off player messages in the CCL config file.\n"); diff --git a/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java index cc2b9f95..eb72096b 100644 --- a/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java @@ -19,7 +19,7 @@ public AlphaOverrideVertexConsumer(VertexConsumer delegate, int alpha) { } @Override - public VertexConsumer color(int r, int g, int b, int a) { - return super.color(r, g, b, alpha); + public VertexConsumer setColor(int r, int g, int b, int a) { + return super.setColor(r, g, b, alpha); } } diff --git a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java index 303f625b..e8acd3e5 100644 --- a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java +++ b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java @@ -1,18 +1,14 @@ package codechicken.lib.render.buffer; -import codechicken.lib.colour.Colour; -import codechicken.lib.colour.ColourRGBA; import codechicken.lib.model.CachedFormat; import codechicken.lib.model.Quad; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * A {@link VertexConsumer} implementation to build {@link BakedQuad}s. @@ -21,14 +17,12 @@ */ public class BakedQuadVertexBuilder implements VertexConsumer, ISpriteAwareVertexConsumer { - private final List quadList = new ArrayList<>(); + private final List quadList = new ArrayList<>(); private final VertexFormat.Mode mode; - private final int vSize; + private final Quad current = new Quad(); private CachedFormat format; - private @Nullable Colour defaultColour; - private @Nullable Quad current; - private int vertex; + private int vertex = -1; public BakedQuadVertexBuilder() { this(VertexFormat.Mode.QUADS); @@ -56,7 +50,6 @@ public BakedQuadVertexBuilder(CachedFormat format, VertexFormat.Mode mode) { } this.mode = mode; this.format = format; - vSize = mode.primitiveLength; } // Provided for interop with other mods that may provide different quad formats. @@ -67,39 +60,34 @@ public void setFormat(VertexFormat format) { // Provided for interop with other mods that may provide different quad formats. public void setFormat(CachedFormat format) { this.format = format; + current.reset(format); } public void reset() { quadList.clear(); - current = null; - vertex = 0; + vertex = -1; } @Override public void sprite(TextureAtlasSprite sprite) { - checkNewQuad(); - assert current != null; current.setTexture(sprite); } @Override - public VertexConsumer vertex(double x, double y, double z) { + public VertexConsumer addVertex(float x, float y, float z) { if (!format.hasPosition) return this; - checkNewQuad(); - assert current != null; - current.vertices[vertex].vec()[0] = (float) x; - current.vertices[vertex].vec()[1] = (float) y; - current.vertices[vertex].vec()[2] = (float) z; + endPrevVertex(); + current.vertices[vertex].vec()[0] = x; + current.vertices[vertex].vec()[1] = y; + current.vertices[vertex].vec()[2] = z; return this; } @Override - public VertexConsumer color(int red, int green, int blue, int alpha) { + public VertexConsumer setColor(int red, int green, int blue, int alpha) { if (!format.hasColor) return this; - checkNewQuad(); - assert current != null; current.vertices[vertex].color()[0] = red / 255F; current.vertices[vertex].color()[1] = green / 255F; current.vertices[vertex].color()[2] = blue / 255F; @@ -108,55 +96,45 @@ public VertexConsumer color(int red, int green, int blue, int alpha) { } @Override - public VertexConsumer uv(float u, float v) { + public VertexConsumer setUv(float u, float v) { if (!format.hasUV) return this; - checkNewQuad(); - assert current != null; current.vertices[vertex].uv()[0] = u; current.vertices[vertex].uv()[1] = v; return this; } @Override - public VertexConsumer overlayCoords(int u, int v) { + public VertexConsumer setUv1(int u, int v) { if (!format.hasOverlay) return this; - checkNewQuad(); - assert current != null; current.vertices[vertex].overlay()[0] = u / (float) 0xF0; current.vertices[vertex].overlay()[1] = v / (float) 0xF0; return this; } @Override - public VertexConsumer uv2(int u, int v) { + public VertexConsumer setUv2(int u, int v) { if (!format.hasLightMap) return this; - checkNewQuad(); - assert current != null; current.vertices[vertex].lightmap()[0] = u / (float) 0xF0; current.vertices[vertex].lightmap()[1] = v / (float) 0xF0; return this; } @Override - public VertexConsumer normal(float x, float y, float z) { + public VertexConsumer setNormal(float x, float y, float z) { if (!format.hasNormal) return this; - checkNewQuad(); - assert current != null; current.vertices[vertex].normal()[0] = x; current.vertices[vertex].normal()[1] = y; current.vertices[vertex].normal()[2] = z; return this; } - @Override - public void endVertex() { - assert current != null; + private void endPrevVertex() { vertex++; - if (vertex == vSize) { + if (vertex == mode.primitiveLength) { if (mode == VertexFormat.Mode.TRIANGLES) { //Quadulate. for (int e = 0; e < current.format().elementCount; e++) { @@ -166,38 +144,14 @@ public void endVertex() { if (current.sprite == null) { throw new IllegalStateException("Sprite not set."); } - if (defaultColour != null) { - float[] colour = defaultColour.getRGBA(); - for (Quad.Vertex v : current.vertices) { - System.arraycopy(colour, 0, v.color(), 0, 4); - } - } - quadList.add(current); - current = null; - vertex = 0; + quadList.add(current.bake()); + current.reset(format); + vertex = -1; } } - @Override - public void defaultColor(int r, int g, int b, int a) { - defaultColour = new ColourRGBA(r, g, b, a); - } - - @Override - public void unsetDefaultColor() { - defaultColour = null; - } - public List bake() { - if (current != null) { - throw new IllegalStateException("Not finished building."); - } - return quadList.stream().map(Quad::bake).collect(Collectors.toList()); - } - - private void checkNewQuad() { - if (current == null) { - current = new Quad(format); - } + endPrevVertex(); + return new ArrayList<>(quadList); } } diff --git a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java index 548a2639..889441b3 100644 --- a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java @@ -1,8 +1,7 @@ package codechicken.lib.render.buffer; -import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexSorting; import net.covers1624.quack.util.SneakyUtils; import net.minecraft.client.renderer.RenderType; @@ -23,8 +22,8 @@ public DelegateRenderType(RenderType parent, VertexFormat format) { } @Override - public void end(BufferBuilder buffer, VertexSorting sorting) { - parent.end(buffer, sorting); + public void draw(MeshData meshData) { + parent.draw(meshData); } @Override diff --git a/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java index b2b28ab6..6207311b 100644 --- a/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java @@ -24,53 +24,38 @@ public void sprite(TextureAtlasSprite sprite) { } @Override - public VertexConsumer vertex(double x, double y, double z) { - delegate.vertex(x, y, z); + public VertexConsumer addVertex(float x, float y, float z) { + delegate.addVertex(x, y, z); return this; } @Override - public VertexConsumer color(int r, int g, int b, int a) { - delegate.color(r, g, b, a); + public VertexConsumer setColor(int r, int g, int b, int a) { + delegate.setColor(r, g, b, a); return this; } @Override - public VertexConsumer uv(float u, float v) { - delegate.uv(u, v); + public VertexConsumer setUv(float u, float v) { + delegate.setUv(u, v); return this; } @Override - public VertexConsumer overlayCoords(int u, int v) { - delegate.overlayCoords(u, v); + public VertexConsumer setUv1(int u, int v) { + delegate.setUv1(u, v); return this; } @Override - public VertexConsumer uv2(int u, int v) { - delegate.uv2(u, v); + public VertexConsumer setUv2(int u, int v) { + delegate.setUv2(u, v); return this; } @Override - public VertexConsumer normal(float x, float y, float z) { - delegate.normal(x, y, z); + public VertexConsumer setNormal(float x, float y, float z) { + delegate.setNormal(x, y, z); return this; } - - @Override - public void endVertex() { - delegate.endVertex(); - } - - @Override - public void defaultColor(int r, int g, int b, int a) { - delegate.defaultColor(r, g, b, a); - } - - @Override - public void unsetDefaultColor() { - delegate.unsetDefaultColor(); - } } diff --git a/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java index 145535b0..e536f99f 100644 --- a/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java @@ -24,16 +24,16 @@ public TransformingVertexConsumer(VertexConsumer delegate, Transformation transf } @Override - public VertexConsumer vertex(double x, double y, double z) { + public VertexConsumer addVertex(float x, float y, float z) { storage.set(x, y, z); transform.apply(storage); - return super.vertex(storage.x, storage.y, storage.z); + return super.addVertex((float) storage.x, (float) storage.y, (float) storage.z); } @Override - public VertexConsumer normal(float x, float y, float z) { + public VertexConsumer setNormal(float x, float y, float z) { storage.set(x, y, z); transform.applyN(storage); - return delegate.normal((float) storage.x, (float) storage.y, (float) storage.z); + return delegate.setNormal((float) storage.x, (float) storage.y, (float) storage.z); } } diff --git a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java index 59077474..44db2728 100644 --- a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java @@ -1,10 +1,7 @@ package codechicken.lib.render.buffer; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.VertexBuffer; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexSorting; +import com.mojang.blaze3d.vertex.*; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; @@ -24,7 +21,7 @@ public class VBORenderType extends DelegateRenderType implements AutoCloseable { private final BiConsumer factory; private final VertexBuffer vertexBuffer = new VertexBuffer(VertexBuffer.Usage.DYNAMIC); - private final BufferBuilder builder; + private final ByteBufferBuilder builder; private boolean dirty = true; /** @@ -37,7 +34,7 @@ public class VBORenderType extends DelegateRenderType implements AutoCloseable { public VBORenderType(RenderType parent, BiConsumer factory) { super(parent, parent.format()); this.factory = factory; - builder = new BufferBuilder(bufferSize()); + builder = new ByteBufferBuilder(bufferSize()); } /** @@ -75,19 +72,17 @@ private void render() { private void rebuild() { if (!dirty) return; - builder.begin(mode(), format()); - factory.accept(format(), builder); + builder.discard(); + BufferBuilder buffer = new BufferBuilder(builder, mode(), format()); + factory.accept(format(), buffer); vertexBuffer.bind(); - vertexBuffer.upload(builder.end()); + vertexBuffer.upload(buffer.build()); builder.clear(); dirty = false; } @Override - public void end(BufferBuilder buffer, VertexSorting sorting) { - // End buffer and discard state, we don't operate like this. - buffer.endOrDiscardIfEmpty(); - + public void draw(MeshData meshData) { setupRenderState(); render(); clearRenderState(); @@ -141,10 +136,7 @@ public void setupRenderState() { } @Override - public void end(BufferBuilder buffer, VertexSorting sorting) { - // End buffer and discard state, we don't operate like this. - buffer.endOrDiscardIfEmpty(); - + public void draw(MeshData meshData) { setupRenderState(); render(); clearRenderState(); diff --git a/src/main/java/codechicken/lib/render/model/OBJParser.java b/src/main/java/codechicken/lib/render/model/OBJParser.java index a20e2b1a..13c57790 100644 --- a/src/main/java/codechicken/lib/render/model/OBJParser.java +++ b/src/main/java/codechicken/lib/render/model/OBJParser.java @@ -298,7 +298,7 @@ private static double[] parseDoubles(String s, String token) { private static ResourceLocation maybeRelative(ResourceLocation other, String resource) { if (resource.contains(":")) { - return new ResourceLocation(resource); + return ResourceLocation.parse(resource); } String path = other.getPath(); int lastSlash = path.lastIndexOf("/"); @@ -307,6 +307,6 @@ private static ResourceLocation maybeRelative(ResourceLocation other, String res } else { path = ""; } - return new ResourceLocation(other.getNamespace(), path + "/" + resource); + return ResourceLocation.fromNamespaceAndPath(other.getNamespace(), path + "/" + resource); } } diff --git a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java index e6a64071..1cb9eba5 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java +++ b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java @@ -51,7 +51,7 @@ public class CustomParticleHandler { * @return Always true for this, basically just return the result of this method inside {@link Block#addLandingEffects} */ public static boolean handleLandingEffects(ServerLevel world, BlockPos pos, LivingEntity entity, int numParticles) { - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_ADD_LANDING_EFFECTS); + PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_ADD_LANDING_EFFECTS, entity.level().registryAccess()); packet.writePos(pos); packet.writeVector(Vector3.fromEntity(entity)); packet.writeVarInt(numParticles); @@ -66,7 +66,7 @@ public static boolean handleRunningEffects(Level world, BlockPos pos, BlockState BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); ParticleEngine particleManager = Minecraft.getInstance().particleEngine; List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); TextureAtlasSprite rolledSprite = sprites.get(world.random.nextInt(sprites.size())); @@ -98,7 +98,7 @@ public static boolean handleHitEffects(BlockState state, Level world, HitResult BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); Cuboid6 bounds = new Cuboid6(); if (hit instanceof VoxelShapeBlockHitResult) { bounds.set(((VoxelShapeBlockHitResult) hit).shape.bounds()); @@ -130,7 +130,7 @@ public static boolean handleDestroyEffects(Level world, BlockPos pos, BlockState BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); Cuboid6 bounds = new Cuboid6(state.getShape(world, pos).bounds()); addBlockDestroyEffects(world, bounds.add(pos), new ArrayList<>(((IModelParticleProvider) model).getDestroyEffects(state, world, pos, modelData)), manager); return true; @@ -147,7 +147,7 @@ public static void addLandingEffects(Level world, BlockPos pos, BlockState state BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); BakedModel model = modelShapes.getBlockModel(state); if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAtOrEmpty(pos); + ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); double speed = 0.15000000596046448D; diff --git a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java b/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java index 2c5c621e..90fd3bf5 100644 --- a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java +++ b/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java @@ -119,7 +119,7 @@ protected void parseUniformNode(JsonElement json) throws ChainedJsonException { } public Program compileProgram(ResourceProvider resourceProvider, Program.Type programType, ResourceLocation loc) throws IOException { - ResourceLocation adjustedLoc = new ResourceLocation(loc.getNamespace(), "shaders/core/" + loc.getPath() + programType.getExtension()); + ResourceLocation adjustedLoc = ResourceLocation.fromNamespaceAndPath(loc.getNamespace(), "shaders/core/" + loc.getPath() + programType.getExtension()); String cacheString = "ccl__" + adjustedLoc; Program program = programType.getPrograms().get(cacheString); if (program != null) return program; diff --git a/src/main/java/codechicken/lib/render/shader/GlslProcessor.java b/src/main/java/codechicken/lib/render/shader/GlslProcessor.java index b9c7deb4..b3d30c20 100644 --- a/src/main/java/codechicken/lib/render/shader/GlslProcessor.java +++ b/src/main/java/codechicken/lib/render/shader/GlslProcessor.java @@ -169,9 +169,9 @@ private static List extractIncludes(List lines, IntSet if (!includeFolder) { match = matcher.group(2); } - ResourceLocation loc = new ResourceLocation(match); + ResourceLocation loc = ResourceLocation.parse(match); if (includeFolder) { - loc = new ResourceLocation(loc.getNamespace(), FilenameUtils.normalize("shaders/include/" + loc.getPath(), true)); + loc = ResourceLocation.fromNamespaceAndPath(loc.getNamespace(), FilenameUtils.normalize("shaders/include/" + loc.getPath(), true)); } imports.add(loc); } diff --git a/src/main/java/codechicken/lib/texture/TextureUtils.java b/src/main/java/codechicken/lib/texture/TextureUtils.java index ee81c516..079abcb7 100644 --- a/src/main/java/codechicken/lib/texture/TextureUtils.java +++ b/src/main/java/codechicken/lib/texture/TextureUtils.java @@ -89,7 +89,7 @@ public static TextureAtlasSprite getMissingSprite() { } public static TextureAtlasSprite getTexture(String location) { - return getTextureMap().getSprite(new ResourceLocation(location)); + return getTextureMap().getSprite(ResourceLocation.parse(location)); } public static TextureAtlasSprite getTexture(ResourceLocation location) { @@ -97,18 +97,18 @@ public static TextureAtlasSprite getTexture(ResourceLocation location) { } public static TextureAtlasSprite getBlockTexture(String string) { - return getBlockTexture(new ResourceLocation(string)); + return getBlockTexture(ResourceLocation.parse(string)); } public static TextureAtlasSprite getBlockTexture(ResourceLocation location) { - return getTexture(new ResourceLocation(location.getNamespace(), "block/" + location.getPath())); + return getTexture(ResourceLocation.fromNamespaceAndPath(location.getNamespace(), "block/" + location.getPath())); } public static TextureAtlasSprite getItemTexture(String string) { - return getItemTexture(new ResourceLocation(string)); + return getItemTexture(ResourceLocation.parse(string)); } public static TextureAtlasSprite getItemTexture(ResourceLocation location) { - return getTexture(new ResourceLocation(location.getNamespace(), "items/" + location.getPath())); + return getTexture(ResourceLocation.fromNamespaceAndPath(location.getNamespace(), "items/" + location.getPath())); } } diff --git a/src/main/java/codechicken/lib/util/CCLTags.java b/src/main/java/codechicken/lib/util/CCLTags.java index d7b4c1cf..9381ec32 100644 --- a/src/main/java/codechicken/lib/util/CCLTags.java +++ b/src/main/java/codechicken/lib/util/CCLTags.java @@ -14,51 +14,51 @@ public class CCLTags { public static class Blocks { - public static TagKey WOOL = forge("wool"); - public static TagKey WOOL_WHITE = forge("wool/white"); - public static TagKey WOOL_ORANGE = forge("wool/orange"); - public static TagKey WOOL_MAGENTA = forge("wool/magenta"); - public static TagKey WOOL_LIGHT_BLUE = forge("wool/light_blue"); - public static TagKey WOOL_YELLOW = forge("wool/yellow"); - public static TagKey WOOL_LIME = forge("wool/lime"); - public static TagKey WOOL_PINK = forge("wool/pink"); - public static TagKey WOOL_GRAY = forge("wool/gray"); - public static TagKey WOOL_LIGHT_GRAY = forge("wool/light_gray"); - public static TagKey WOOL_CYAN = forge("wool/cyan"); - public static TagKey WOOL_PURPLE = forge("wool/purple"); - public static TagKey WOOL_BLUE = forge("wool/blue"); - public static TagKey WOOL_BROWN = forge("wool/brown"); - public static TagKey WOOL_GREEN = forge("wool/green"); - public static TagKey WOOL_RED = forge("wool/red"); - public static TagKey WOOL_BLACK = forge("wool/black"); + public static TagKey WOOLS = common("wools"); + public static TagKey WOOLS_WHITE = common("wools/white"); + public static TagKey WOOLS_ORANGE = common("wools/orange"); + public static TagKey WOOLS_MAGENTA = common("wools/magenta"); + public static TagKey WOOLS_LIGHT_BLUE = common("wools/light_blue"); + public static TagKey WOOLS_YELLOW = common("wools/yellow"); + public static TagKey WOOLS_LIME = common("wools/lime"); + public static TagKey WOOLS_PINK = common("wools/pink"); + public static TagKey WOOLS_GRAY = common("wools/gray"); + public static TagKey WOOLS_LIGHT_GRAY = common("wools/light_gray"); + public static TagKey WOOLS_CYAN = common("wools/cyan"); + public static TagKey WOOLS_PURPLE = common("wools/purple"); + public static TagKey WOOLS_BLUE = common("wools/blue"); + public static TagKey WOOLS_BROWN = common("wools/brown"); + public static TagKey WOOLS_GREEN = common("wools/green"); + public static TagKey WOOLS_RED = common("wools/red"); + public static TagKey WOOLS_BLACK = common("wools/black"); - private static TagKey forge(String path) { - return BlockTags.create(new ResourceLocation("forge", path)); + private static TagKey common(String path) { + return BlockTags.create(ResourceLocation.fromNamespaceAndPath("c", path)); } } public static class Items { - public static TagKey WOOL = forge("wool"); - public static TagKey WOOL_WHITE = forge("wool/white"); - public static TagKey WOOL_ORANGE = forge("wool/orange"); - public static TagKey WOOL_MAGENTA = forge("wool/magenta"); - public static TagKey WOOL_LIGHT_BLUE = forge("wool/light_blue"); - public static TagKey WOOL_YELLOW = forge("wool/yellow"); - public static TagKey WOOL_LIME = forge("wool/lime"); - public static TagKey WOOL_PINK = forge("wool/pink"); - public static TagKey WOOL_GRAY = forge("wool/gray"); - public static TagKey WOOL_LIGHT_GRAY = forge("wool/light_gray"); - public static TagKey WOOL_CYAN = forge("wool/cyan"); - public static TagKey WOOL_PURPLE = forge("wool/purple"); - public static TagKey WOOL_BLUE = forge("wool/blue"); - public static TagKey WOOL_BROWN = forge("wool/brown"); - public static TagKey WOOL_GREEN = forge("wool/green"); - public static TagKey WOOL_RED = forge("wool/red"); - public static TagKey WOOL_BLACK = forge("wool/black"); + public static TagKey WOOLS = common("wools"); + public static TagKey WOOLS_WHITE = common("wools/white"); + public static TagKey WOOLS_ORANGE = common("wools/orange"); + public static TagKey WOOLS_MAGENTA = common("wools/magenta"); + public static TagKey WOOLS_LIGHT_BLUE = common("wools/light_blue"); + public static TagKey WOOLS_YELLOW = common("wools/yellow"); + public static TagKey WOOLS_LIME = common("wools/lime"); + public static TagKey WOOLS_PINK = common("wools/pink"); + public static TagKey WOOLS_GRAY = common("wools/gray"); + public static TagKey WOOLS_LIGHT_GRAY = common("wools/light_gray"); + public static TagKey WOOLS_CYAN = common("wools/cyan"); + public static TagKey WOOLS_PURPLE = common("wools/purple"); + public static TagKey WOOLS_BLUE = common("wools/blue"); + public static TagKey WOOLS_BROWN = common("wools/brown"); + public static TagKey WOOLS_GREEN = common("wools/green"); + public static TagKey WOOLS_RED = common("wools/red"); + public static TagKey WOOLS_BLACK = common("wools/black"); - private static TagKey forge(String path) { - return ItemTags.create(new ResourceLocation("forge", path)); + private static TagKey common(String path) { + return ItemTags.create(ResourceLocation.fromNamespaceAndPath("c", path)); } } } diff --git a/src/main/java/codechicken/lib/util/ItemUtils.java b/src/main/java/codechicken/lib/util/ItemUtils.java index 0966278c..325f6d16 100644 --- a/src/main/java/codechicken/lib/util/ItemUtils.java +++ b/src/main/java/codechicken/lib/util/ItemUtils.java @@ -165,6 +165,7 @@ public static int compareItemStack(ItemStack stack1, ItemStack stack2) { * @return whether the two items are the same in terms of damage and itemID. */ public static boolean areStacksSameType(ItemStack stack1, ItemStack stack2) { - return !stack1.isEmpty() && !stack2.isEmpty() && (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameTags(stack2, stack1)); + // TODO this can likely be replaced with `ItemStack.isSameItemSameComponents` + return !stack1.isEmpty() && !stack2.isEmpty() && (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameComponents(stack2, stack1)); } } diff --git a/src/main/java/codechicken/lib/util/ResourceUtils.java b/src/main/java/codechicken/lib/util/ResourceUtils.java index 9c153cca..60e27ac9 100644 --- a/src/main/java/codechicken/lib/util/ResourceUtils.java +++ b/src/main/java/codechicken/lib/util/ResourceUtils.java @@ -37,17 +37,6 @@ public static ReloadableResourceManager getResourceManager() { return (ReloadableResourceManager) Minecraft.getInstance().getResourceManager(); } - /** - * Get's an IResource from the resource manager. - * - * @param location The resource to get. - * @return The gotten resource. - * @throws IOException If the resource doesn't exist, or some other IO error occurred. - */ - public static Resource getResource(String location) throws IOException { - return getResource(new ResourceLocation(location)); - } - /** * Get's an IResource from the resource manager. * diff --git a/src/main/java/codechicken/lib/util/ServerUtils.java b/src/main/java/codechicken/lib/util/ServerUtils.java index f5b31b77..b61967da 100644 --- a/src/main/java/codechicken/lib/util/ServerUtils.java +++ b/src/main/java/codechicken/lib/util/ServerUtils.java @@ -1,24 +1,10 @@ package codechicken.lib.util; -import codechicken.lib.data.MCDataOutput; -import codechicken.lib.internal.network.CCLNetwork; -import codechicken.lib.packet.PacketCustom; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceKey; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; import net.minecraft.world.level.Level; -import net.neoforged.neoforge.common.NeoForge; -import net.neoforged.neoforge.event.entity.player.PlayerContainerEvent; import net.neoforged.neoforge.server.ServerLifecycleHooks; import java.nio.file.Path; -import java.util.function.Consumer; - -import static codechicken.lib.internal.network.CCLNetwork.C_OPEN_CONTAINER; -import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 22/10/2016. @@ -32,32 +18,4 @@ public static Path getSaveDirectory() { public static Path getSaveDirectory(ResourceKey dimension) { return ServerLifecycleHooks.getCurrentServer().storageSource.getDimensionPath(dimension); } - - public static void openContainer(ServerPlayer player, MenuProvider containerProvider) { - openContainer(player, containerProvider, e -> { - }); - } - - public static void openContainer(ServerPlayer player, MenuProvider containerProvider, Consumer packetConsumer) { - if (player.level().isClientSide()) { - return; - } - player.doCloseContainer(); - player.nextContainerCounter(); - int containerId = player.containerCounter; - - AbstractContainerMenu container = containerProvider.createMenu(containerId, player.getInventory(), player); - MenuType type = requireNonNull(container).getType(); - - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_OPEN_CONTAINER); - packet.writeRegistryIdDirect(BuiltInRegistries.MENU, type); - packet.writeVarInt(containerId); - packet.writeTextComponent(containerProvider.getDisplayName()); - packetConsumer.accept(packet); - - packet.sendToPlayer(player); - player.containerMenu = container; - player.initMenu(player.containerMenu); - NeoForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, container)); - } } diff --git a/src/main/java/codechicken/lib/util/VertexUtils.java b/src/main/java/codechicken/lib/util/VertexUtils.java index 05a35955..fd9d05db 100644 --- a/src/main/java/codechicken/lib/util/VertexUtils.java +++ b/src/main/java/codechicken/lib/util/VertexUtils.java @@ -53,11 +53,11 @@ public static void putQuad(IVertexConsumer consumer, BakedQuad quad) { public static void unpack(int[] from, float[] to, VertexFormat formatFrom, int v, int e) { int length = Math.min(4, to.length); VertexFormatElement element = formatFrom.getElements().get(e); - int vertexStart = v * formatFrom.getVertexSize() + formatFrom.getOffset(e); - int count = element.getElementCount(); - VertexFormatElement.Type type = element.getType(); - VertexFormatElement.Usage usage = element.getUsage(); - int size = type.getSize(); + int vertexStart = v * formatFrom.getVertexSize() + formatFrom.getOffset(element); + int count = element.count(); + VertexFormatElement.Type type = element.type(); + VertexFormatElement.Usage usage = element.usage(); + int size = type.size(); int mask = (256 << (8 * (size - 1))) - 1; for (int i = 0; i < length; i++) { if (i < count) { @@ -91,10 +91,10 @@ public static void unpack(int[] from, float[] to, VertexFormat formatFrom, int v public static void pack(float[] from, int[] to, VertexFormat formatTo, int v, int e) { VertexFormatElement element = formatTo.getElements().get(e); - int vertexStart = v * formatTo.getVertexSize() + formatTo.getOffset(e); - int count = element.getElementCount(); - VertexFormatElement.Type type = element.getType(); - int size = type.getSize(); + int vertexStart = v * formatTo.getVertexSize() + formatTo.getOffset(element); + int count = element.count(); + VertexFormatElement.Type type = element.type(); + int size = type.size(); int mask = (256 << (8 * (size - 1))) - 1; for (int i = 0; i < 4; i++) { if (i < count) { @@ -131,7 +131,7 @@ private static int[] generateMapping(VertexFormat from, VertexFormat to) { int e2; for (e2 = 0; e2 < toCount; e2++) { VertexFormatElement current = to.getElements().get(e2); - if (expected.getUsage() == current.getUsage() && expected.getIndex() == current.getIndex()) { + if (expected.usage() == current.usage() && expected.index() == current.index()) { break; } } diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/neoforge.mods.toml similarity index 97% rename from src/main/resources/META-INF/mods.toml rename to src/main/resources/META-INF/neoforge.mods.toml index 59003ae5..c7b51658 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -24,7 +24,7 @@ It contains libraries for 3D math and transformations, model rendering, packets, [[dependencies.codechickenlib]] modId="minecraft" type="required" - versionRange="[1.20.4]" + versionRange="[1.21.1]" ordering="NONE" side="BOTH" diff --git a/src/test/java/codechicken/lib/render/model/MatLibTests.java b/src/test/java/codechicken/lib/render/model/MatLibTests.java index 8b00ab95..0a59581f 100644 --- a/src/test/java/codechicken/lib/render/model/MatLibTests.java +++ b/src/test/java/codechicken/lib/render/model/MatLibTests.java @@ -15,7 +15,7 @@ public class MatLibTests { @Test public void testMatLibParse() { - MatLib matLib = MatLib.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test.mtl")); + MatLib matLib = MatLib.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test.mtl")); assertEquals(1, matLib.materials.size()); ModelMaterial material = matLib.getMaterial("Material"); assertNotNull(material); diff --git a/src/test/java/codechicken/lib/render/model/OBJParserTests.java b/src/test/java/codechicken/lib/render/model/OBJParserTests.java index 1dafb099..3c9aa71b 100644 --- a/src/test/java/codechicken/lib/render/model/OBJParserTests.java +++ b/src/test/java/codechicken/lib/render/model/OBJParserTests.java @@ -19,7 +19,7 @@ public class OBJParserTests { @Test public void testObject() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -28,7 +28,7 @@ public void testObject() { @Test public void testGroup() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test_group.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test_group.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -37,7 +37,7 @@ public void testGroup() { @Test public void testGroupObject() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test_group_object.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test_group_object.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Group/Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -46,7 +46,7 @@ public void testGroupObject() { @Test public void testMultiObject() { - Map modelMap = new OBJParser(new ResourceLocation("test:model/test_multi_object.obj")) + Map modelMap = new OBJParser(ResourceLocation.parse("test:model/test_multi_object.obj")) .provider(TestResourceProvider.INSTANCE) .ignoreMtl() .quads() From 5e0aaac7c2df12b4b3dfcc63b809c0d16694b9e9 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Tue, 7 Jan 2025 13:44:23 +1030 Subject: [PATCH 61/87] Potentially fix packet writing issues? --- .../java/codechicken/lib/packet/PacketCustomChannel.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java index dbc1d3ab..72f31efe 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -93,11 +93,7 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event) { CustomPacketPayload.Type type = new CustomPacketPayload.Type<>(channel); StreamCodec codec = StreamCodec.of( - (buf, p) -> { - p.data().markReaderIndex(); - buf.writeBytes(p.data()); - p.data().resetReaderIndex(); - }, + (buf, p) -> buf.writeBytes(p.data(), 0, p.data().writerIndex()), buf -> { RegistryAccess access = buf instanceof RegistryFriendlyByteBuf b ? b.registryAccess() : null; return new PacketCustom.Pkt(type, access, buf.readBytes(buf.readableBytes())); From 2b9d617c504da0b0fe6488c16eebf03faa3d736c Mon Sep 17 00:00:00 2001 From: covers1624 Date: Fri, 7 Feb 2025 18:18:01 +1030 Subject: [PATCH 62/87] Workaround JEI not properly handling Neo item passes. --- .../java/codechicken/lib/model/CompositeItemModel.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/codechicken/lib/model/CompositeItemModel.java b/src/main/java/codechicken/lib/model/CompositeItemModel.java index db0efb2d..07b2422c 100644 --- a/src/main/java/codechicken/lib/model/CompositeItemModel.java +++ b/src/main/java/codechicken/lib/model/CompositeItemModel.java @@ -78,8 +78,11 @@ class Overrides extends ItemOverrides { @Nullable @Override public BakedModel resolve(BakedModel pModel, ItemStack pStack, @Nullable ClientLevel pLevel, @Nullable LivingEntity pEntity, int pSeed) { - ImmutableList iPasses = FastStream.of(itemPasses) - .map(e -> e.getOverrides().resolve(e, pStack, pLevel, pEntity, pSeed)) + ImmutableMap mappedChildren = FastStream.of(children.entrySet()) + .toImmutableMap(Map.Entry::getKey, e -> e.getValue().getOverrides().resolve(e.getValue(), pStack, pLevel, pEntity, pSeed)); + + ImmutableList iPasses = FastStream.of(Geometry.this.itemPasses) + .map(mappedChildren::get) .toImmutableList(); return new CompositeModel.Baked( @@ -89,7 +92,7 @@ public BakedModel resolve(BakedModel pModel, ItemStack pStack, @Nullable ClientL particle, context.getTransforms(), this, - children, + mappedChildren, iPasses ); } From ba474611926f79dd8c11bc7674c42123cb181f1f Mon Sep 17 00:00:00 2001 From: covers1624 Date: Wed, 8 Jan 2025 16:53:48 +1030 Subject: [PATCH 63/87] Mark forge as unsupported. --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 9d23645e..c566cf56 100644 --- a/build.gradle +++ b/build.gradle @@ -106,7 +106,7 @@ def publishingMetadataTask = tasks.register("publishingMetadata") { 'mcVersion' : "${mc_version}", 'version' : "${mod_version}", 'classifier' : null, - 'modLoader' : ['neoforge', 'forge'], + 'modLoader' : ['neoforge'], 'curseforgeId': '242818', 'modrinthId' : '2gq0ALnz' ] From f6de12bf154f8655af01e0a98261b17527708a94 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Wed, 8 Jan 2025 16:55:38 +1030 Subject: [PATCH 64/87] Fix Github check workflow. --- .github/workflows/check.yml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index be519ea5..a4afe55b 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -11,10 +11,11 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Setup JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v4 + - name: Setup Java + uses: actions/setup-java@v4 with: - java-version: 1.8 + java-version: 21 + distribution: 'temurin' - name: Build - run: ./gradlew build + run: ./gradlew check From f5b0c01880e166ab9192df850a95598f196a2642 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 1 Feb 2025 14:14:09 +1030 Subject: [PATCH 65/87] Migrate to MDG. - Quack is now jar-in-jared. - AccessTransformer is now published. --- build.gradle | 81 +++++++++++++++++++++++++---------------------- gradle.properties | 2 +- 2 files changed, 45 insertions(+), 38 deletions(-) diff --git a/build.gradle b/build.gradle index c566cf56..9d2e7a48 100644 --- a/build.gradle +++ b/build.gradle @@ -1,11 +1,10 @@ import groovy.json.JsonOutput plugins { - id 'java' + id 'java-library' id 'maven-publish' id 'signing' - id 'com.github.johnrengelman.shadow' version '7.1.2' - id 'net.neoforged.gradle.userdev' version '7.0.165' + id 'net.neoforged.moddev' version '2.0.77' } java { @@ -28,20 +27,33 @@ version = "${mc_version}-${mod_version}" println "Starting build of ${archivesBaseName}, Version: ${mod_version}" println "Using Forge: ${forge_version}, for Minecraft: ${mc_version}" -minecraft { - accessTransformers.file file("src/main/resources/META-INF/accesstransformer.cfg") -} +neoForge { + enable { + version = forge_version + enabledSourceSets += sourceSets.test + } -runs { - client { - workingDirectory file('run') + accessTransformers { + publish file("src/main/resources/META-INF/accesstransformer.cfg") } - server { - workingDirectory file('run') + + runs { + client { + client() + } + server { + server() + } + data { + data() + programArguments.addAll '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated").absolutePath, '--existing', file("src/main/resources").absolutePath + } } - data { - workingDirectory file('run') - arguments.addAll '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated").absolutePath, '--existing', file("src/main/resources").absolutePath + + mods { + codechickenlib { + sourceSet sourceSets.main + } } } @@ -57,11 +69,6 @@ processResources { } } -configurations { - shadow - implementation.extendsFrom shadow -} - repositories { mavenLocal() maven { url "https://maven.covers1624.net/" } @@ -69,16 +76,19 @@ repositories { } dependencies { - implementation "net.neoforged:neoforge:${forge_version}" + jarJar(api('net.covers1624:Quack')) { + version { + strictly '[0.4.10,0.5)' + prefer '0.4.10.105' + } + } - shadow 'net.covers1624:Quack:0.4.10.105' + compileOnly("mezz.jei:jei-${mc_version}-neoforge:${jei_version}") { + transitive false + } testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' - - implementation("mezz.jei:jei-${mc_version}-neoforge:${jei_version}") { - transitive false - } } test { @@ -114,23 +124,19 @@ def publishingMetadataTask = tasks.register("publishingMetadata") { } } -jar.enabled = false -shadowJar { - finalizedBy 'signShadowJar' - archiveClassifier = '' +jar { + finalizedBy 'signJar' manifest commonManifest - configurations = [project.configurations.shadow] from file("LICENSE") } -assemble.dependsOn shadowJar -tasks.register("signShadowJar") { - dependsOn("shadowJar") +tasks.register("signJar") { + dependsOn("jar") doFirst { def args = [:] - args['jar'] = shadowJar.archiveFile.get().asFile + args['jar'] = jar.archiveFile.get().asFile if (System.getenv("KEY_STORE")) { args['keyStore'] = System.getenv("KEY_STORE") file(System.getenv("KEY_STORE_PROPS")).withReader { @@ -169,14 +175,15 @@ publishing { } } } + publications { CodeChickenLib(MavenPublication) { groupId project.group artifactId project.base.archivesName.get() version project.version - artifact shadowJar - artifact sourcesJar - artifact javadocJar + + from components['java'] + artifact(publishingMetadata) { builtBy publishingMetadataTask classifier 'publishing' diff --git a/gradle.properties b/gradle.properties index 2362bae0..a2b57c9c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,5 +2,5 @@ org.gradle.daemon=false mc_version=1.21.1 forge_version=21.1.72 -mod_version=4.6.0 +mod_version=4.6.1 jei_version=19.21.0.246 From 1cffdbecdeba2c3e487b6f8dfc6edccbcfdf2a8c Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 1 Feb 2025 14:15:04 +1030 Subject: [PATCH 66/87] Fix VBORenderType. --- .../lib/render/buffer/VBORenderType.java | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java index 44db2728..34e6d7d7 100644 --- a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java +++ b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java @@ -2,6 +2,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; @@ -13,7 +14,7 @@ import static net.covers1624.quack.util.SneakyUtils.none; /** - * A RenderType that is backed by a VertexBufferObject used for Instanced rendering. + * A RenderType that is backed by a VertexBufferObject used for Cached rendering. *

    * Created by covers1624 on 25/5/20. */ @@ -64,6 +65,23 @@ public WithCallbacks withState(RenderStateShard shard) { return new WithCallbacks().withState(shard); } + /** + * Called to draw a VBORenderType. + * + * @param buffers The buffers instance. + */ + public void draw(MultiBufferSource buffers) { + draw(buffers, this); + } + + private static void draw(MultiBufferSource buffers, RenderType type) { + var cons = buffers.getBuffer(type); + // Add some garbage so a mesh gets generated. + for (int i = 0; i < type.mode().primitiveLength; i++) { + cons.addVertex(0F, 0F, 0F, 0, 0F, 0F, 0, 0, 0F, 0F, 0F); + } + } + private void render() { rebuild(); vertexBuffer.bind(); @@ -83,9 +101,11 @@ private void rebuild() { @Override public void draw(MeshData meshData) { - setupRenderState(); - render(); - clearRenderState(); + try (meshData) { + setupRenderState(); + render(); + clearRenderState(); + } } @Override @@ -137,9 +157,11 @@ public void setupRenderState() { @Override public void draw(MeshData meshData) { - setupRenderState(); - render(); - clearRenderState(); + try (meshData) { + setupRenderState(); + render(); + clearRenderState(); + } } @Override @@ -149,5 +171,9 @@ public void clearRenderState() { } super.clearRenderState(); } + + public void draw(MultiBufferSource buffers) { + VBORenderType.draw(buffers, this); + } } } From c769cbf58d4f0276447c8d5ba08bd845f0d9e781 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 1 Feb 2025 14:15:31 +1030 Subject: [PATCH 67/87] Fix BakedQuadVertexBuilder. --- .../lib/render/buffer/BakedQuadVertexBuilder.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java index e8acd3e5..e9118901 100644 --- a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java +++ b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java @@ -2,6 +2,8 @@ import codechicken.lib.model.CachedFormat; import codechicken.lib.model.Quad; +import codechicken.lib.util.VectorUtils; +import codechicken.lib.vec.Vector3; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -49,7 +51,7 @@ public BakedQuadVertexBuilder(CachedFormat format, VertexFormat.Mode mode) { throw new IllegalArgumentException("Only QUADS or TRIANGLES supported. Got: " + mode); } this.mode = mode; - this.format = format; + setFormat(format); } // Provided for interop with other mods that may provide different quad formats. @@ -144,14 +146,16 @@ private void endPrevVertex() { if (current.sprite == null) { throw new IllegalStateException("Sprite not set."); } + current.setQuadOrientation(VectorUtils.findSideE(Vector3.fromArray(current.vertices[0].normal()))); quadList.add(current.bake()); current.reset(format); - vertex = -1; + vertex = 0; } } public List bake() { endPrevVertex(); + vertex = -1; return new ArrayList<>(quadList); } } From ea41d08b8c1b24d51cf6294467faaf8e38c371b8 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 1 Feb 2025 14:19:03 +1030 Subject: [PATCH 68/87] Add Neo CustomLoaderBuilder for class model loader, for blocks. --- .../lib/datagen/ClassModelLoaderBuilder.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java diff --git a/src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java b/src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java new file mode 100644 index 00000000..f37cc026 --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java @@ -0,0 +1,47 @@ +package codechicken.lib.datagen; + +import com.google.gson.JsonObject; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.resources.ResourceLocation; +import net.neoforged.neoforge.client.model.generators.CustomLoaderBuilder; +import net.neoforged.neoforge.client.model.generators.ModelBuilder; +import net.neoforged.neoforge.common.data.ExistingFileHelper; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; + +import static codechicken.lib.CodeChickenLib.MOD_ID; +import static java.util.Objects.requireNonNull; + +/** + * Created by covers1624 on 1/21/25. + */ +public class ClassModelLoaderBuilder> extends CustomLoaderBuilder { + + private @Nullable Class clazz; + + public ClassModelLoaderBuilder(T parent, ExistingFileHelper existingFileHelper) { + super(ResourceLocation.fromNamespaceAndPath(MOD_ID, "class"), parent, existingFileHelper, false); + } + + public ClassModelLoaderBuilder clazz(Class clazz) { + try { + Constructor ctor = clazz.getConstructor(); + if (!Modifier.isPublic(ctor.getModifiers())) { + throw new IllegalArgumentException("Expected single no-args public constructor."); + } + } catch (NoSuchMethodException ex) { + throw new IllegalStateException("Expected single no-args public constructor.", ex); + } + this.clazz = clazz; + return this; + } + + @Override + public JsonObject toJson(JsonObject json) { + super.toJson(json); + json.addProperty("class", requireNonNull(clazz).getName()); + return json; + } +} From d6667cb693b2b28fb784a2d42987917b06f5114e Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 8 Feb 2025 03:39:33 +1030 Subject: [PATCH 69/87] Deprecate block model bypass hax for removal. Embed embeddium compat. (#465) * Deprecate block model bypass hax for removal. Embed embeddium compat. * Make the mixin safer, smol refactor. --- build.gradle | 3 ++ .../mixin/compat/EmbeddiumCCLMixin.java | 23 ++++++++++++ .../render/block/BlockRenderingRegistry.java | 37 ++++++++++++++++++- .../block/CCBlockRendererDispatcher.java | 3 ++ .../lib/render/block/ICCBlockRenderer.java | 15 ++++++++ src/main/resources/mixins.codechickenlib.json | 3 +- 6 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java diff --git a/build.gradle b/build.gradle index 9d2e7a48..64cd6b72 100644 --- a/build.gradle +++ b/build.gradle @@ -73,6 +73,7 @@ repositories { mavenLocal() maven { url "https://maven.covers1624.net/" } maven { url "https://maven.blamejared.com/" } + maven { url "https://api.modrinth.com/maven" } } dependencies { @@ -83,6 +84,8 @@ dependencies { } } + compileOnly 'maven.modrinth:embeddium:1.0.15+mc1.21.1' + compileOnly("mezz.jei:jei-${mc_version}-neoforge:${jei_version}") { transitive false } diff --git a/src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java b/src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java new file mode 100644 index 00000000..412f1820 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java @@ -0,0 +1,23 @@ +package codechicken.lib.internal.mixin.compat; + +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import org.embeddedt.embeddium.compat.ccl.CCLCompat; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Pseudo; + +/** + * Created by covers1624 on 2/7/25. + */ +@Pseudo +@Mixin (CCLCompat.class) +abstract class EmbeddiumCCLMixin { + + /** + * @author covers1624 + * @reason Its broken and CCL ships its own. + */ + @Overwrite + public static void onClientSetup(FMLClientSetupEvent event) { + } +} diff --git a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java b/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java index 82149dd3..b83bcb57 100644 --- a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java +++ b/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java @@ -1,19 +1,23 @@ package codechicken.lib.render.block; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.BlockRenderDispatcher; -import net.minecraft.core.Holder; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.material.Fluid; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.fml.ModList; +import org.embeddedt.embeddium.api.BlockRendererRegistry; +import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; /** @@ -23,6 +27,8 @@ * * @see ICCBlockRenderer */ +@Deprecated(forRemoval = true) // No replacement. +@ScheduledForRemoval (inVersion = "mc 1.21.2+") public class BlockRenderingRegistry { private static boolean initialized = false; @@ -39,6 +45,10 @@ public static void init() { mc.blockRenderer = new CCBlockRendererDispatcher(parentDispatcher, mc.getBlockColors()); initialized = true; } + + if (ModList.get().isLoaded("embeddium")) { + EmbeddiumSupport.init(); + } } /** @@ -51,6 +61,7 @@ public static void init() { * @param renderer The {@link ICCBlockRenderer}. * @throws IllegalArgumentException If the same Block is registered twice. */ + @Deprecated // No replacement. Use a mixin. public static synchronized void registerRenderer(Block block, ICCBlockRenderer renderer) { ICCBlockRenderer prev = blockRenderers.get(block); if (prev != null) { @@ -69,6 +80,7 @@ public static synchronized void registerRenderer(Block block, ICCBlockRenderer r * @param renderer The {@link ICCBlockRenderer}. * @throws IllegalArgumentException If the same Fluid is registered twice. */ + @Deprecated // No replacement. Use a mixin. public static synchronized void registerRenderer(Fluid fluid, ICCBlockRenderer renderer) { ICCBlockRenderer prev = fluidRenderers.get(fluid); if (prev != null) { @@ -83,6 +95,7 @@ public static synchronized void registerRenderer(Fluid fluid, ICCBlockRenderer r * * @param renderer The {@link ICCBlockRenderer}. */ + @Deprecated // No replacement. Use a mixin. public static synchronized void registerGlobalRenderer(ICCBlockRenderer renderer) { globalRenderers.add(renderer); } @@ -114,4 +127,26 @@ static ICCBlockRenderer findFor(Fluid fluid, Predicate pred) { return null; } + + private static class EmbeddiumSupport { + + private static final Map ADAPTERS = new ConcurrentHashMap<>(); + private static final ThreadLocal POSE_STACK_CACHE = ThreadLocal.withInitial(PoseStack::new); + + private static BlockRendererRegistry.Renderer adapt(ICCBlockRenderer renderer) { + return ADAPTERS.computeIfAbsent(renderer, e -> (ctx, random, consumer) -> { + e.renderBlock(ctx.state(), ctx.pos(), ctx.world(), POSE_STACK_CACHE.get(), consumer, random, ctx.modelData(), ctx.renderLayer()); + return BlockRendererRegistry.RenderResult.OVERRIDE; + }); + } + + public static void init() { + BlockRendererRegistry.instance().registerRenderPopulator((resultList, ctx) -> { + ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(ctx.state().getBlock(), e -> e.canHandleBlock(ctx.world(), ctx.pos(), ctx.state(), ctx.renderLayer())); + if (renderer != null) { + resultList.add(adapt(renderer)); + } + }); + } + } } diff --git a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java index ecfc11d3..051ffe82 100644 --- a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java +++ b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java @@ -26,12 +26,15 @@ import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval; import java.util.concurrent.TimeUnit; /** * Created by covers1624 on 8/09/2016. */ +@Deprecated +@ScheduledForRemoval (inVersion = "mc 1.21.2+") public class CCBlockRendererDispatcher extends BlockRenderDispatcher { private static final Logger logger = LogManager.getLogger(); diff --git a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java b/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java index a07b21a6..1ed00fcf 100644 --- a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java +++ b/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java @@ -14,6 +14,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; import net.neoforged.neoforge.client.model.data.ModelData; +import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval; import org.jetbrains.annotations.Nullable; /** @@ -22,7 +23,14 @@ * Created by covers1624 on 8/09/2016. * * @see BlockRenderingRegistry + * @deprecated Unfortunately, this has become a maintenance and compatability burden. Mods like Sodium + * are in every single modpack, and we can't realistically tell people not to use it. It's possible + * a Neo api may pop up that allows features similar to this API. But I'm not going to hold my breath. + * If someone still requires the functionality that this system provides, they should implement mixins + * themselves, or Sodium/Embeddium compatability. */ +@Deprecated (forRemoval = true) +@ScheduledForRemoval (inVersion = "mc 1.21.2+") public interface ICCBlockRenderer { //region Block @@ -36,6 +44,7 @@ public interface ICCBlockRenderer { * @param renderType The {@link RenderType}, {@code null} for breaking. * @return If you wish to render the BlockState. */ + @Deprecated boolean canHandleBlock(BlockAndTintGetter world, BlockPos pos, BlockState blockState, @Nullable RenderType renderType); /** @@ -53,6 +62,7 @@ public interface ICCBlockRenderer { * @param data Any ModelData. * @param renderType The {@link RenderType}, {@code null} for breaking. */ + @Deprecated void renderBlock(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack mStack, VertexConsumer builder, RandomSource random, ModelData data, @Nullable RenderType renderType); /** @@ -66,6 +76,7 @@ public interface ICCBlockRenderer { * @param builder The {@link VertexConsumer} to add quads to. * @param data Any ModelData. */ + @Deprecated default void renderBreaking(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack mStack, VertexConsumer builder, ModelData data) { CCRenderState ccrs = CCRenderState.instance(); ccrs.overlay = OverlayTexture.NO_OVERLAY; @@ -85,6 +96,7 @@ default void renderBreaking(BlockState state, BlockPos pos, BlockAndTintGetter w * @param state The state. * @return If you wish to render this block. */ + @Deprecated // No replacement. Use a mixin. default boolean canHandleEntity(BlockState state) { return false; } @@ -101,6 +113,7 @@ default boolean canHandleEntity(BlockState state) { * @param data Any ModelData. * @param renderType The {@link RenderType} may be {@code null}. */ + @Deprecated // No replacement. Use a mixin. default void renderEntity(BlockState state, PoseStack nStack, MultiBufferSource builder, int packedLight, int packedOverlay, ModelData data, @Nullable RenderType renderType) { } //endregion @@ -115,6 +128,7 @@ default void renderEntity(BlockState state, PoseStack nStack, MultiBufferSource * @param fluidState The {@link FluidState}. * @return If you wish to render the {@link FluidState}. */ + @Deprecated // No replacement. Use a mixin. default boolean canHandleFluid(BlockAndTintGetter world, BlockPos pos, BlockState blockState, FluidState fluidState) { return false; } @@ -131,6 +145,7 @@ default boolean canHandleFluid(BlockAndTintGetter world, BlockPos pos, BlockStat * @param blockState The {@link BlockState} * @param fluidState The {@link FluidState} */ + @Deprecated // No replacement. Use a mixin. default void renderFluid(BlockPos pos, BlockAndTintGetter world, VertexConsumer builder, BlockState blockState, FluidState fluidState) { } //endregion } diff --git a/src/main/resources/mixins.codechickenlib.json b/src/main/resources/mixins.codechickenlib.json index bd87c7df..3b3388c5 100644 --- a/src/main/resources/mixins.codechickenlib.json +++ b/src/main/resources/mixins.codechickenlib.json @@ -9,6 +9,7 @@ "dev.GameNarratorMixin", "ItemRendererMixin", "MinecraftMixin", - "ShaderInstanceMixin" + "ShaderInstanceMixin", + "compat.EmbeddiumCCLMixin" ] } From 94c894ae2c9de41471498890b399884ebb82bf1d Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 1 Feb 2025 14:23:41 +1030 Subject: [PATCH 70/87] Add mega hack to disable CCRS lighting, for Multipart quad baking. In Multipart we need to build baked quads without lighting, via the existing code paths which usually would emit lighting data. Its common for part implemented code to call `ccrs.reset()` prior to doing any rendering. This resets any attempt at disabling lighting. This hack is the easiest way to prevent these. This auto-baking is going away next mc version anyway. --- src/main/java/codechicken/lib/render/CCRenderState.java | 8 +++++++- .../codechicken/lib/render/pipeline/CCRenderPipeline.java | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java index 8435d695..d0f40a6b 100644 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ b/src/main/java/codechicken/lib/render/CCRenderState.java @@ -80,6 +80,12 @@ public class CCRenderState { */ public LightMatrix lightMatrix = new LightMatrix(); + // TODO, REALLY SERIOUSLY NUKE THIS. + // This was added as a workaround for Multipart to actually seriously disable the lighting engine, + // when building BakedQuads for parts which don't do it themselves. + @Deprecated (forRemoval = true) + public boolean hackyReallyDontComputeLighting; + //vertex outputs public final Vertex5 vert = new Vertex5(); public final Vector3 normal = new Vector3(); @@ -161,7 +167,7 @@ public void bind(RenderType renderType, MultiBufferSource getter, Matrix4 mat) { public void reset() { model = null; pipeline.reset(); - computeLighting = true; + computeLighting = !hackyReallyDontComputeLighting; colour = baseColour = alphaOverride = -1; } diff --git a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java index bf444d34..87af24d3 100644 --- a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java +++ b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java @@ -57,7 +57,7 @@ public void rebuild() { if (renderState.cFmt.hasColor) { addAttribute(renderState.colourAttrib); } - if (renderState.computeLighting) { + if (renderState.computeLighting && !renderState.hackyReallyDontComputeLighting) { addAttribute(renderState.lightingAttrib); } From 867882176fa8d52112914a88b849f0ba7d6fa1a6 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Tue, 27 May 2025 16:59:43 +0930 Subject: [PATCH 71/87] Add codecs for Vector3. --- .../java/codechicken/lib/vec/Vector3.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/main/java/codechicken/lib/vec/Vector3.java b/src/main/java/codechicken/lib/vec/Vector3.java index 830a2a4c..11c4a4bc 100644 --- a/src/main/java/codechicken/lib/vec/Vector3.java +++ b/src/main/java/codechicken/lib/vec/Vector3.java @@ -2,9 +2,15 @@ import codechicken.lib.math.MathHelper; import codechicken.lib.util.Copyable; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.PrimitiveCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; @@ -30,6 +36,20 @@ public class Vector3 implements Copyable { public static final Vector3 Z_NEG = new Vector3( 0, 0,-1); //@formatter:on + public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + PrimitiveCodec.DOUBLE.fieldOf("x").forGetter(e -> e.x), + PrimitiveCodec.DOUBLE.fieldOf("y").forGetter(e -> e.y), + PrimitiveCodec.DOUBLE.fieldOf("z").forGetter(e -> e.z) + ).apply(b, Vector3::new) + ); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.DOUBLE, e -> e.x, + ByteBufCodecs.DOUBLE, e -> e.y, + ByteBufCodecs.DOUBLE, e -> e.z, + Vector3::new + ); + public double x; public double y; public double z; From 55e088b123b1ed3fdcbe363b786fca8a58976c03 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 8 Jun 2025 15:01:48 +0930 Subject: [PATCH 72/87] Align RayTracer.retraceBlock with vanilla path. --- src/main/java/codechicken/lib/raytracer/RayTracer.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/raytracer/RayTracer.java b/src/main/java/codechicken/lib/raytracer/RayTracer.java index 563a4075..b725fad5 100644 --- a/src/main/java/codechicken/lib/raytracer/RayTracer.java +++ b/src/main/java/codechicken/lib/raytracer/RayTracer.java @@ -16,13 +16,19 @@ public class RayTracer { @Nullable public static BlockHitResult retraceBlock(BlockGetter level, Player player, BlockPos pos) { + return retraceBlock(level, player, pos, ClipContext.Block.OUTLINE); + } + + @Nullable + public static BlockHitResult retraceBlock(BlockGetter level, Player player, BlockPos pos, ClipContext.Block context) { Vec3 startVec = getStartVec(player); Vec3 endVec = getEndVec(player); + BlockState state = level.getBlockState(pos); - VoxelShape baseShape = state.getShape(level, pos); + VoxelShape baseShape = context.get(state, level, pos, CollisionContext.of(player)); BlockHitResult baseTraceResult = baseShape.clip(startVec, endVec, pos); if (baseTraceResult != null) { - BlockHitResult raytraceTraceShape = state.getVisualShape(level, pos, CollisionContext.of(player)).clip(startVec, endVec, pos); + BlockHitResult raytraceTraceShape = state.getInteractionShape(level, pos).clip(startVec, endVec, pos); if (raytraceTraceShape != null) { return raytraceTraceShape; } From 52f6b128fa3352369fa414c75397e5603ecc8e72 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 8 Jun 2025 15:02:23 +0930 Subject: [PATCH 73/87] Update Quack. --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 64cd6b72..2a40fb84 100644 --- a/build.gradle +++ b/build.gradle @@ -80,7 +80,7 @@ dependencies { jarJar(api('net.covers1624:Quack')) { version { strictly '[0.4.10,0.5)' - prefer '0.4.10.105' + prefer '0.4.10.115' } } From 0dc334c9c1329b9772471b647d21e8be841bdca9 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 8 Jun 2025 15:02:56 +0930 Subject: [PATCH 74/87] Add nullability annotations to SubHitBlockHitResult. --- .../codechicken/lib/raytracer/SubHitBlockHitResult.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java b/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java index 26d7c195..19bc779d 100644 --- a/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java +++ b/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java @@ -5,6 +5,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; public class SubHitBlockHitResult extends BlockHitResult implements Comparable { @@ -12,18 +13,18 @@ public class SubHitBlockHitResult extends BlockHitResult implements Comparable Date: Wed, 16 Jul 2025 07:47:48 +1000 Subject: [PATCH 75/87] Fix overlays rendering under JEI --- .../codechicken/lib/gui/modular/ModularGuiContainer.java | 6 +++++- .../java/codechicken/lib/gui/modular/ModularGuiScreen.java | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java index 36a2e4d9..d6d23318 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -84,9 +84,13 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float super.render(graphics, mouseX, mouseY, partialTicks); + //Ensure we render overlay on top of things like JEI + render.pose().pushPose(); + render.pose().translate(0, 0, 400); if (!handleFloatingItemRender(render, mouseX, mouseY) && !renderHoveredStackToolTip(render, mouseX, mouseY)) { modularGui.renderOverlay(render, partialTicks); } + render.pose().popPose(); } @Override @@ -139,7 +143,7 @@ protected boolean renderHoveredStackToolTip(GuiRender guiGraphics, int mouseX, i return false; } ItemStack itemStack = this.hoveredSlot.getItem(); - guiGraphics.toolTipWithImage(this.getTooltipFromContainerItem(itemStack), itemStack.getTooltipImage(), mouseX, mouseY); + guiGraphics.toolTipWithImage(this.getTooltipFromContainerItem(itemStack), itemStack.getTooltipImage(), itemStack, mouseX, mouseY); return true; } return false; diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java index 337bb5aa..f905bd86 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java @@ -69,7 +69,11 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float } GuiRender render = GuiRender.convert(graphics); modularGui.render(render, partialTicks); + //Ensure we render overlay on top of things like JEI + render.pose().pushPose(); + render.pose().translate(0, 0, 400); modularGui.renderOverlay(render, partialTicks); + render.pose().popPose(); } @Override From 5b35f50d2f25f4ced359658eb0561f4c0aa07e6c Mon Sep 17 00:00:00 2001 From: covers1624 Date: Thu, 23 Jul 2026 02:20:35 +0930 Subject: [PATCH 76/87] Fix shaders crashing with amd drivers. --- .../java/codechicken/lib/render/shader/CCShaderInstance.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java b/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java index 90fd3bf5..bbcbb7e8 100644 --- a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java +++ b/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java @@ -4,6 +4,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.shaders.Program; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.Util; @@ -127,7 +128,7 @@ public Program compileProgram(ResourceProvider resourceProvider, Program.Type pr ProcessedShader processedShader = new GlslProcessor(resourceProvider, adjustedLoc).process(); int id = GL20.glCreateShader(programType.getGlType()); - GL20.glShaderSource(id, processedShader.processedSource()); + GlStateManager.glShaderSource(id, List.of(processedShader.processedSource())); GL20.glCompileShader(id); if (GL20.glGetShaderi(id, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { String s1 = GL20.glGetShaderInfoLog(id); From cbc26e13543556495cea1d796c4a979dd50ea496 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sat, 25 Jul 2026 21:37:20 +0930 Subject: [PATCH 77/87] Initial port to 1.21.11 --- build.gradle | 19 +- gradle.properties | 8 +- gradle/wrapper/gradle-wrapper.jar | Bin 43583 -> 48462 bytes gradle/wrapper/gradle-wrapper.properties | 4 +- gradlew | 18 +- gradlew.bat | 36 +- .../15d5dd4ace2ad25407a17728f6fbc07b246efd63 | 2 +- .../95d738e2c774c5a4b0452cf55df2775d732b2634 | 2 +- .../f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 | 2 +- .../java/codechicken/lib/CodeChickenLib.java | 17 +- .../codechicken/lib/block/LazyStateBlock.java | 15 + .../lib/block/ModularBlockEntity.java | 86 +- .../lib/block/ModularTileBlock.java | 39 +- .../block/component/DirectionComponent.java | 1 + .../block/component/PropertyComponent.java | 5 + .../component/tile/InventoryComponent.java | 13 +- .../block/component/tile/ValueComponent.java | 109 ++ .../java/codechicken/lib/colour/Colour.java | 72 + .../lib/colour/CustomGradient.java | 4 +- .../codechicken/lib/colour/EnumColour.java | 22 +- .../lib/config/ConfigCategoryImpl.java | 32 +- .../codechicken/lib/config/ConfigFile.java | 5 +- .../lib/config/ConfigSyncManager.java | 53 +- .../codechicken/lib/config/ConfigTag.java | 19 +- .../lib/config/ConfigValueImpl.java | 33 +- .../lib/config/ConfigValueListImpl.java | 50 +- .../config/parser/LegacyConfigSerializer.java | 2 +- .../java/codechicken/lib/data/DataUtils.java | 1 + .../codechicken/lib/data/MCByteStream.java | 1 + .../codechicken/lib/data/MCDataByteBuf.java | 1 + .../codechicken/lib/data/MCDataInput.java | 18 +- .../lib/data/MCDataInputStream.java | 1 + .../codechicken/lib/data/MCDataOutput.java | 20 +- .../lib/data/MCDataOutputStream.java | 1 + .../codechicken/lib/data/package-info.java | 1 + .../lib/datagen/ClassModelLoaderBuilder.java | 47 - .../lib/datagen/ConditionalIngredient.java | 137 -- .../lib/datagen/DynamicTextureProvider.java | 27 +- .../lib/datagen/ItemModelProvider.java | 434 ----- .../lib/datagen/LanguageProvider.java | 42 +- .../NoValidationBLockLootSubProvider.java | 2 - .../AbstractItemStackRecipeBuilder.java | 8 +- .../datagen/recipe/AbstractRecipeBuilder.java | 38 +- .../datagen/recipe/FurnaceRecipeBuilder.java | 169 +- .../lib/datagen/recipe/RecipeBuilder.java | 9 +- .../lib/datagen/recipe/RecipeProvider.java | 201 +- .../datagen/recipe/ShapedRecipeBuilder.java | 61 +- .../recipe/ShapelessRecipeBuilder.java | 66 +- .../recipe/SpecialCraftingRecipeBuilder.java | 21 +- .../lib/gui/modular/ModularGui.java | 119 +- .../lib/gui/modular/ModularGuiContainer.java | 145 +- .../lib/gui/modular/ModularGuiScreen.java | 42 +- .../lib/gui/modular/SpriteSupplier.java | 55 + .../lib/gui/modular/elements/GuiButton.java | 77 +- .../gui/modular/elements/GuiColourPicker.java | 61 +- .../gui/modular/elements/GuiContextMenu.java | 9 +- .../lib/gui/modular/elements/GuiDVD.java | 10 +- .../lib/gui/modular/elements/GuiDialog.java | 25 +- .../lib/gui/modular/elements/GuiElement.java | 102 +- .../gui/modular/elements/GuiEnergyBar.java | 286 +-- .../modular/elements/GuiEntityRenderer.java | 161 +- .../modular/elements/GuiEventProvider.java | 71 +- .../gui/modular/elements/GuiFluidTank.java | 504 +++-- .../gui/modular/elements/GuiItemStack.java | 43 +- .../lib/gui/modular/elements/GuiList.java | 12 +- .../gui/modular/elements/GuiManipulable.java | 29 +- .../gui/modular/elements/GuiProgressIcon.java | 102 +- .../gui/modular/elements/GuiRectangle.java | 77 +- .../gui/modular/elements/GuiScrolling.java | 16 +- .../lib/gui/modular/elements/GuiSlider.java | 26 +- .../lib/gui/modular/elements/GuiSlots.java | 106 +- .../lib/gui/modular/elements/GuiText.java | 63 +- .../gui/modular/elements/GuiTextField.java | 93 +- .../lib/gui/modular/elements/GuiTextList.java | 34 +- .../lib/gui/modular/elements/GuiTexture.java | 59 +- .../modular/elements}/package-info.java | 2 +- .../lib/gui/modular/lib/BackgroundRender.java | 15 +- .../lib/gui/modular/lib/CursorHelper.java | 22 +- .../lib/gui/modular/lib/DynamicTextures.java | 8 +- .../lib/gui/modular/lib/ElementEvents.java | 111 +- .../lib/gui/modular/lib/ForegroundRender.java | 16 +- .../lib/gui/modular/lib/GuiRender.java | 1729 ----------------- .../lib/gui/modular/lib/ScissorHandler.java | 4 +- .../lib/gui/modular/lib/SliderState.java | 4 +- .../lib/gui/modular/lib/TooltipHandler.java | 27 +- .../lib/container/ContainerScreenAccess.java | 4 +- .../gui/modular/lib/container/DataSync.java | 6 +- .../modular/lib/container/package-info.java | 4 + .../lib/geometry/ConstrainedGeometry.java | 2 - .../modular/lib/geometry/package-info.java | 4 + .../map => gui/modular/lib}/package-info.java | 2 +- .../item => gui/modular}/package-info.java | 2 +- .../lib/gui/modular/sprite/GuiTextures.java | 91 - .../lib/gui/modular/sprite/Material.java | 104 - .../gui/modular/sprite/ModAtlasHolder.java | 107 - .../lib/gui/render/CCCustomRenderState.java | 32 + .../lib/gui/render/GuiGraphicsExtension.java | 442 +++++ .../lib/gui/render/RenderStateUtils.java | 141 ++ .../block => gui/render}/package-info.java | 2 +- .../codechicken/lib/internal/CCLNetwork.java | 51 + .../codechicken/lib/internal/ClientInit.java | 56 +- .../lib/internal/DataGenerators.java | 37 +- .../ExceptionMessageEventHandler.java | 34 - .../lib/internal/HighlightHandler.java | 42 +- .../lib/internal/ItemFileRenderer.java | 93 +- .../internal/command/admin/CountCommand.java | 3 +- .../command/admin/KillAllCommand.java | 17 +- .../internal/command/admin/MiscCommands.java | 5 +- .../lib/internal/command/dev/DevCommands.java | 16 +- .../lib/internal/compat/JEIPlugin.java | 6 +- .../lib/internal/mixin/ItemRendererMixin.java | 41 - .../internal/mixin/ShaderInstanceMixin.java | 44 - .../mixin/compat/EmbeddiumCCLMixin.java | 23 - .../internal/mixin/dev/GameNarratorMixin.java | 5 +- .../mixin/network/FriendlyByteBufMixin.java | 12 + .../network/RegistryFriendlyByteBufMixin.java | 12 + .../internal/mixin/network/package-info.java | 4 + .../mixin/render/GuiGraphicsMixin.java | 12 + .../OrderedSubmitNodeCollectorMixin.java | 12 + .../mixin/render}/package-info.java | 2 +- .../lib/internal/network/CCLNetwork.java | 36 - .../ClientConfigurationPacketHandler.java | 21 - .../internal/network/ClientPacketHandler.java | 34 - .../internal/network/ServerPacketHandler.java | 22 - .../lib/inventory/InventoryNBT.java | 86 - .../lib/inventory/InventoryUtils.java | 55 +- .../lib/inventory/MappedInventoryAccess.java | 14 +- .../lib/inventory/container/CCLMenuType.java | 73 - .../container/ContainerExtended.java | 21 +- .../container/data/AbstractDataStore.java | 7 +- .../inventory/container/data/BooleanData.java | 9 +- .../inventory/container/data/ByteData.java | 9 +- .../inventory/container/data/DoubleData.java | 9 +- .../inventory/container/data/FloatData.java | 9 +- .../inventory/container/data/FluidData.java | 11 +- .../lib/inventory/container/data/IntData.java | 9 +- .../inventory/container/data/LongData.java | 9 +- .../inventory/container/data/ShortData.java | 9 +- .../modular/ModularGuiContainerMenu.java | 39 +- .../codechicken/lib/math/InterpHelper.java | 108 +- .../java/codechicken/lib/math/MathHelper.java | 8 + .../codechicken/lib/model/CachedFormat.java | 190 -- .../lib/model/ClassModelLoader.java | 51 - .../lib/model/CompositeItemModel.java | 129 -- .../lib/model/DummyBakedModel.java | 56 - .../lib/model/IVertexConsumer.java | 54 - .../lib/model/IVertexProducer.java | 9 - .../codechicken/lib/model/ItemQuadBakery.java | 36 - .../lib/model/PerspectiveModel.java | 48 - .../lib/model/PerspectiveModelState.java | 42 - src/main/java/codechicken/lib/model/Quad.java | 545 +++--- ...entFactory.java => QuadAlphaOverride.java} | 21 +- .../transformers => }/QuadClamper.java | 45 +- .../transformers => }/QuadCornerKicker.java | 56 +- .../transformers => }/QuadFaceStripper.java | 59 +- .../lib/model/QuadReInterpolator.java | 43 + .../transformers => }/QuadTinter.java | 34 +- .../lib/model/QuadTransformer.java | 82 + .../AbstractBakedPropertiesModel.java | 124 -- .../model/bakedmodels/ModelProperties.java | 242 --- .../model/bakedmodels/OverrideListModel.java | 61 - .../PerspectiveAwareBakedModel.java | 63 - .../PerspectiveAwareLayeredModel.java | 71 - .../model/bakedmodels/WrappedItemModel.java | 119 -- .../lib/model/pipeline/BakedPipeline.java | 388 ---- .../lib/model/pipeline/IPipelineConsumer.java | 60 - .../lib/model/pipeline/QuadTransformer.java | 132 -- .../transformers/QuadAlphaOverride.java | 61 - .../transformers/QuadReInterpolator.java | 82 - .../pipeline/transformers/package-info.java | 4 - .../packet/CCFriendlyByteBufExtension.java | 130 ++ .../CCRegistryFriendlyByteBufExtension.java | 44 + .../lib/packet/CCStreamCodecs.java | 230 +++ .../lib/packet/ConfigurationStreamPacket.java | 36 + .../lib/packet/ICustomPacketHandler.java | 5 + .../codechicken/lib/packet/PacketCustom.java | 15 +- .../lib/packet/PacketCustomChannel.java | 51 +- .../codechicken/lib/packet/PacketSender.java | 6 +- .../codechicken/lib/packet/SignedVarInt.java | 19 + .../codechicken/lib/packet/SignedVarLong.java | 20 + .../lib/packet/SimpleClientPacketHandler.java | 1 + .../lib/packet/SimpleServerPacketHandler.java | 1 + .../lib/packet/StreamNetworkChannel.java | 377 ++++ .../codechicken/lib/packet/StreamPacket.java | 204 ++ .../lib/raytracer/SubHitBlockHitResult.java | 14 +- .../raytracer/VoxelShapeBlockHitResult.java | 20 +- .../lib/render/BakedVertexSource.java | 178 -- .../lib/render/CCModelLibrary.java | 39 +- .../lib/render/CCRenderEventHandler.java | 23 +- .../lib/render/CCRenderPipelines.java | 32 + .../codechicken/lib/render/CCRenderState.java | 38 +- .../codechicken/lib/render/CachedModel.java | 200 ++ .../codechicken/lib/render/RenderUtils.java | 39 +- .../render/block/BlockRenderingRegistry.java | 152 -- .../block/CCBlockRendererDispatcher.java | 147 -- .../lib/render/block/ICCBlockRenderer.java | 151 -- .../buffer/AlphaOverrideVertexConsumer.java | 5 + .../render/buffer/BakedQuadVertexBuilder.java | 90 +- .../lib/render/buffer/DelegateRenderType.java | 38 - .../buffer/DelegatingVertexConsumer.java | 12 + .../lib/render/buffer/ExtentsConsumer.java | 65 + .../lib/render/buffer/VBORenderType.java | 179 -- ...CCOrderedSubmitNodeCollectorExtension.java | 109 ++ .../extension}/package-info.java | 2 +- .../lib/render/item/IItemRenderer.java | 43 - .../lib/render/item/map/IMapRenderer.java | 30 - .../render/item/map/MapRenderRegistry.java | 103 - .../codechicken/lib/render/model/MatLib.java | 4 +- .../lib/render/model/OBJParser.java | 18 +- .../particle/CustomBreakingParticle.java | 13 +- .../particle/CustomParticleHandler.java | 172 +- .../render/particle/ICustomParticleBlock.java | 41 - .../particle/IModelParticleProvider.java | 45 - .../lib/render/pipeline/CCRenderPipeline.java | 6 +- .../pipeline/attribute/LightingAttribute.java | 5 +- .../render/shader/AbstractShaderObject.java | 54 - .../lib/render/shader/AssetShaderObject.java | 44 - .../lib/render/shader/BinaryShaderObject.java | 111 -- .../lib/render/shader/BinaryType.java | 22 - .../lib/render/shader/CCShaderInstance.java | 201 -- .../lib/render/shader/CCUniform.java | 287 --- .../lib/render/shader/ConstantCache.java | 17 - .../lib/render/shader/GlslProcessor.java | 197 -- .../lib/render/shader/ICCUniform.java | 247 --- .../lib/render/shader/NamedShaderObject.java | 37 - .../render/shader/ShaderConstantCache.java | 49 - .../lib/render/shader/ShaderObject.java | 104 - .../lib/render/shader/ShaderProgram.java | 156 -- .../render/shader/ShaderProgramBuilder.java | 186 -- .../lib/render/shader/SimpleShaderObject.java | 21 - .../lib/render/shader/UniformPair.java | 7 - .../lib/render/shader/UniformType.java | 124 -- .../lib/render/shader/package-info.java | 4 - .../codechicken/lib/texture/TextureUtils.java | 53 +- .../java/codechicken/lib/util/CCLTags.java | 6 +- .../java/codechicken/lib/util/ItemUtils.java | 3 +- .../codechicken/lib/util/ResourceUtils.java | 31 +- .../codechicken/lib/util/TransformUtils.java | 170 -- .../codechicken/lib/util/VertexUtils.java | 142 -- .../java/codechicken/lib/vec/Cuboid6.java | 24 +- .../java/codechicken/lib/vec/Matrix4.java | 8 + .../java/codechicken/lib/vec/Vector3.java | 7 +- .../lib/vec/uv/IconTransformation.java | 12 +- .../resources/META-INF/accesstransformer.cfg | 62 +- src/main/resources/META-INF/interfaces.json | 14 + .../resources/META-INF/neoforge.mods.toml | 5 +- .../assets/codechickenlib/atlases/gui.json | 9 - .../gui/{ => sprites}/cursors/drag.png | Bin .../cursors/resize_diag_tlbr.png | Bin .../cursors/resize_diag_trbl.png | Bin .../gui/{ => sprites}/cursors/resize_h.png | Bin .../gui/{ => sprites}/cursors/resize_v.png | Bin .../dynamic/button_borderless.png | Bin .../dynamic/button_borderless_pressed.png | Bin .../dynamic/button_highlight.png | Bin .../dynamic/button_highlight_borderless.png | Bin .../dynamic/button_highlight_pressed.png | Bin .../{ => sprites}/dynamic/button_pressed.png | Bin .../{ => sprites}/dynamic/button_vanilla.png | Bin .../dynamic/button_vanilla_disabled.png | Bin .../{ => sprites}/dynamic/gui_borderless.png | Bin .../gui/{ => sprites}/dynamic/gui_vanilla.png | Bin .../{ => sprites}/widgets/energy_empty.png | Bin .../gui/{ => sprites}/widgets/energy_full.png | Bin .../widgets/progress_arrow_empty.png | Bin .../widgets/progress_arrow_full.png | Bin .../gui/{ => sprites}/widgets/slot.png | Bin .../gui/{ => sprites}/widgets/slot_large.png | Bin src/main/resources/mixins.codechickenlib.json | 9 +- .../codechicken/lib/config/ConfigV3Tests.java | 21 +- .../lib/render/BakedVertexSourceTests.java | 80 - .../lib/render/model/MatLibTests.java | 4 +- .../lib/render/model/OBJParserTests.java | 10 +- .../lib/test/TestResourceProvider.java | 4 +- 274 files changed, 5252 insertions(+), 11656 deletions(-) create mode 100644 src/main/java/codechicken/lib/block/component/tile/ValueComponent.java delete mode 100644 src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java delete mode 100644 src/main/java/codechicken/lib/datagen/ConditionalIngredient.java delete mode 100644 src/main/java/codechicken/lib/datagen/ItemModelProvider.java create mode 100644 src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java rename src/main/java/codechicken/lib/{model/bakedmodels => gui/modular/elements}/package-info.java (58%) delete mode 100644 src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/container/package-info.java create mode 100644 src/main/java/codechicken/lib/gui/modular/lib/geometry/package-info.java rename src/main/java/codechicken/lib/{render/item/map => gui/modular/lib}/package-info.java (60%) rename src/main/java/codechicken/lib/{render/item => gui/modular}/package-info.java (63%) delete mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java delete mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/Material.java delete mode 100644 src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java create mode 100644 src/main/java/codechicken/lib/gui/render/CCCustomRenderState.java create mode 100644 src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java create mode 100644 src/main/java/codechicken/lib/gui/render/RenderStateUtils.java rename src/main/java/codechicken/lib/{render/block => gui/render}/package-info.java (62%) create mode 100644 src/main/java/codechicken/lib/internal/CCLNetwork.java delete mode 100644 src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java delete mode 100644 src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java delete mode 100644 src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java delete mode 100644 src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/network/FriendlyByteBufMixin.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/network/RegistryFriendlyByteBufMixin.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/network/package-info.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/render/GuiGraphicsMixin.java create mode 100644 src/main/java/codechicken/lib/internal/mixin/render/OrderedSubmitNodeCollectorMixin.java rename src/main/java/codechicken/lib/{model/pipeline => internal/mixin/render}/package-info.java (57%) delete mode 100644 src/main/java/codechicken/lib/internal/network/CCLNetwork.java delete mode 100644 src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java delete mode 100644 src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java delete mode 100644 src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java delete mode 100644 src/main/java/codechicken/lib/inventory/InventoryNBT.java delete mode 100644 src/main/java/codechicken/lib/inventory/container/CCLMenuType.java delete mode 100644 src/main/java/codechicken/lib/model/CachedFormat.java delete mode 100644 src/main/java/codechicken/lib/model/ClassModelLoader.java delete mode 100644 src/main/java/codechicken/lib/model/CompositeItemModel.java delete mode 100644 src/main/java/codechicken/lib/model/DummyBakedModel.java delete mode 100644 src/main/java/codechicken/lib/model/IVertexConsumer.java delete mode 100644 src/main/java/codechicken/lib/model/IVertexProducer.java delete mode 100644 src/main/java/codechicken/lib/model/ItemQuadBakery.java delete mode 100644 src/main/java/codechicken/lib/model/PerspectiveModel.java delete mode 100644 src/main/java/codechicken/lib/model/PerspectiveModelState.java rename src/main/java/codechicken/lib/model/{pipeline/IPipelineElementFactory.java => QuadAlphaOverride.java} (61%) rename src/main/java/codechicken/lib/model/{pipeline/transformers => }/QuadClamper.java (59%) rename src/main/java/codechicken/lib/model/{pipeline/transformers => }/QuadCornerKicker.java (75%) rename src/main/java/codechicken/lib/model/{pipeline/transformers => }/QuadFaceStripper.java (63%) create mode 100644 src/main/java/codechicken/lib/model/QuadReInterpolator.java rename src/main/java/codechicken/lib/model/{pipeline/transformers => }/QuadTinter.java (58%) create mode 100644 src/main/java/codechicken/lib/model/QuadTransformer.java delete mode 100644 src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java delete mode 100644 src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java delete mode 100644 src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java delete mode 100644 src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java delete mode 100644 src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java delete mode 100644 src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java delete mode 100644 src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java delete mode 100644 src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java delete mode 100644 src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java delete mode 100644 src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java delete mode 100644 src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java delete mode 100644 src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java create mode 100644 src/main/java/codechicken/lib/packet/CCFriendlyByteBufExtension.java create mode 100644 src/main/java/codechicken/lib/packet/CCRegistryFriendlyByteBufExtension.java create mode 100644 src/main/java/codechicken/lib/packet/CCStreamCodecs.java create mode 100644 src/main/java/codechicken/lib/packet/ConfigurationStreamPacket.java create mode 100644 src/main/java/codechicken/lib/packet/SignedVarInt.java create mode 100644 src/main/java/codechicken/lib/packet/SignedVarLong.java create mode 100644 src/main/java/codechicken/lib/packet/StreamNetworkChannel.java create mode 100644 src/main/java/codechicken/lib/packet/StreamPacket.java delete mode 100644 src/main/java/codechicken/lib/render/BakedVertexSource.java create mode 100644 src/main/java/codechicken/lib/render/CCRenderPipelines.java create mode 100644 src/main/java/codechicken/lib/render/CachedModel.java delete mode 100644 src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java delete mode 100644 src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java delete mode 100644 src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java delete mode 100644 src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java create mode 100644 src/main/java/codechicken/lib/render/buffer/ExtentsConsumer.java delete mode 100644 src/main/java/codechicken/lib/render/buffer/VBORenderType.java create mode 100644 src/main/java/codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension.java rename src/main/java/codechicken/lib/{internal/network => render/extension}/package-info.java (60%) delete mode 100644 src/main/java/codechicken/lib/render/item/IItemRenderer.java delete mode 100644 src/main/java/codechicken/lib/render/item/map/IMapRenderer.java delete mode 100644 src/main/java/codechicken/lib/render/item/map/MapRenderRegistry.java delete mode 100644 src/main/java/codechicken/lib/render/particle/ICustomParticleBlock.java delete mode 100644 src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java delete mode 100644 src/main/java/codechicken/lib/render/shader/AbstractShaderObject.java delete mode 100644 src/main/java/codechicken/lib/render/shader/AssetShaderObject.java delete mode 100644 src/main/java/codechicken/lib/render/shader/BinaryShaderObject.java delete mode 100644 src/main/java/codechicken/lib/render/shader/BinaryType.java delete mode 100644 src/main/java/codechicken/lib/render/shader/CCShaderInstance.java delete mode 100644 src/main/java/codechicken/lib/render/shader/CCUniform.java delete mode 100644 src/main/java/codechicken/lib/render/shader/ConstantCache.java delete mode 100644 src/main/java/codechicken/lib/render/shader/GlslProcessor.java delete mode 100644 src/main/java/codechicken/lib/render/shader/ICCUniform.java delete mode 100644 src/main/java/codechicken/lib/render/shader/NamedShaderObject.java delete mode 100644 src/main/java/codechicken/lib/render/shader/ShaderConstantCache.java delete mode 100644 src/main/java/codechicken/lib/render/shader/ShaderObject.java delete mode 100644 src/main/java/codechicken/lib/render/shader/ShaderProgram.java delete mode 100644 src/main/java/codechicken/lib/render/shader/ShaderProgramBuilder.java delete mode 100644 src/main/java/codechicken/lib/render/shader/SimpleShaderObject.java delete mode 100644 src/main/java/codechicken/lib/render/shader/UniformPair.java delete mode 100644 src/main/java/codechicken/lib/render/shader/UniformType.java delete mode 100644 src/main/java/codechicken/lib/render/shader/package-info.java delete mode 100644 src/main/java/codechicken/lib/util/TransformUtils.java delete mode 100644 src/main/java/codechicken/lib/util/VertexUtils.java create mode 100644 src/main/resources/META-INF/interfaces.json delete mode 100644 src/main/resources/assets/codechickenlib/atlases/gui.json rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/cursors/drag.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/cursors/resize_diag_tlbr.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/cursors/resize_diag_trbl.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/cursors/resize_h.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/cursors/resize_v.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_borderless.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_borderless_pressed.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_highlight.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_highlight_borderless.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_highlight_pressed.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_pressed.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_vanilla.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/button_vanilla_disabled.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/gui_borderless.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/dynamic/gui_vanilla.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/widgets/energy_empty.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/widgets/energy_full.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/widgets/progress_arrow_empty.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/widgets/progress_arrow_full.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/widgets/slot.png (100%) rename src/main/resources/assets/codechickenlib/textures/gui/{ => sprites}/widgets/slot_large.png (100%) delete mode 100644 src/test/java/codechicken/lib/render/BakedVertexSourceTests.java diff --git a/build.gradle b/build.gradle index 2a40fb84..f01f6ca5 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { id 'java-library' id 'maven-publish' id 'signing' - id 'net.neoforged.moddev' version '2.0.77' + id 'net.neoforged.moddev' version '2.0.141' } java { @@ -24,7 +24,7 @@ sourceSets.main.resources.srcDirs += "src/main/generated" mod_version = "${mod_version}." + (System.getenv("BUILD_NUMBER") ?: "1") version = "${mc_version}-${mod_version}" -println "Starting build of ${archivesBaseName}, Version: ${mod_version}" +println "Starting build of ${base.archivesName.get()}, Version: ${mod_version}" println "Using Forge: ${forge_version}, for Minecraft: ${mc_version}" neoForge { @@ -37,6 +37,11 @@ neoForge { publish file("src/main/resources/META-INF/accesstransformer.cfg") } + interfaceInjectionData { + from file('src/main/resources/META-INF/interfaces.json') + publish file('src/main/resources/META-INF/interfaces.json') + } + runs { client { client() @@ -73,25 +78,23 @@ repositories { mavenLocal() maven { url "https://maven.covers1624.net/" } maven { url "https://maven.blamejared.com/" } - maven { url "https://api.modrinth.com/maven" } } dependencies { jarJar(api('net.covers1624:Quack')) { version { strictly '[0.4.10,0.5)' - prefer '0.4.10.115' + prefer '0.4.10.128' } } - compileOnly 'maven.modrinth:embeddium:1.0.15+mc1.21.1' - compileOnly("mezz.jei:jei-${mc_version}-neoforge:${jei_version}") { transitive false } - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' + testImplementation platform('org.junit:junit-bom:6.0.0') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } test { diff --git a/gradle.properties b/gradle.properties index a2b57c9c..628fea70 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ org.gradle.daemon=false -mc_version=1.21.1 -forge_version=21.1.72 -mod_version=4.6.1 -jei_version=19.21.0.246 +mc_version=1.21.11 +forge_version=21.11.42 +mod_version=4.7.0 +jei_version=27.9.0.38 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index a4b76b9530d66f5e68d973ea569d8e19de379189..b1b8ef56b44f16b14dc800fa8103a6d89abb526f 100644 GIT binary patch delta 40229 zcmXVXQ(&EK({&nS$F^-dX>7BxZF`41Y_y}swi~mtZL>jRJN^5--+yu+T}SuKtTnS{ zP46P)^ebe&JqnO{Y6>xo4GntNpX@3TcXjqLL%&=dI#nE4x6x)tHk=s#_)yinVtSMX z+kHWA*`}fB^(cS-JN~B~Vm!?){vAgDl9h~nHicLGAf*{R7Jp}UEbZcQq6)ND>!PDG zJwpLhX3}oGIMX>xfXTj~7v9xk`lq}%HU1O5k7bd{^B4-eTHbys_v3S9-cq(N&d!YZ6Hu0w_=ovW9WKE$6j~oBo@}U7p5D#3SYMW z?G(}RCU4tfwrf!tR|kL+UkY6IRm<^o4Oofbaq!NEA%^{q@bSgJUaB5ZT8?3fr690e z4U$X6&$<5Y^`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~-(suLL21M0EzxY+jSg*{ zdpJ~S9LLX!wU*7e49N+DnX!X$OUWg(n!xcISD{AM>2g`Tc(H`#y8#ec$Jt@Au4M?tX`|llPvE z%pDmy>5%^BPDkJFb{nlm-6P?3<05aN+;pihlI6Vi)oDcj@z&}J+33lnMf)}*Tuw#|cGA1YXckeKU)S|#-)ajAhU z{PRF0(+QTHmn!sDGdt$0|6}%8L1UXRs>URxKh_X+uw^1y@ru_S7aLug*M*Y(pEuv9_9_#4b&c zSIk*3we2l%&zpF9YJj*xVw%5iQB82QD+s_dQgVigFL7adH3?>CLtrTd_xJI(<9i*{ zDK5e-Kzn=ooANo?M-nsBNw=or+~T%|E^ytF8td=Pt=87^fso`Woz5v}za>RNy#{GwB4&tMVE_3;JB& zQ^n&Qhh!c`H__kt2iHD$U{jFi$YimKS@Eq!^hksH$l-Sy$&VYIhB|aa>7sW%v^A65 z4Wi^q4S^h;Ym|JsyBqD$@H_KJfeKc4=(B-vTg~5Gz1njEE$TH-h1|}t((&IXL=K9Q z3*N~6k$nBv`K^5nE>3&an6p2`NLC3EIPr0P!R(c`a9lEfYAor<| zDeiGIf3AyDc+@yx{A%K#cI-!_BHVq|+-k1=MQ*S%Ln2x0mxiHtt2_}ektNYV!Ppkh z$Mo_RBJ41#J2I2dlG?+|zEGwdRF^!K*{N_X6yLY)G;6Oifm8OHT9WDJBRWQNnR@s_ z=RnnT&EvDjr6>SE3j /dev/null && printf '%s -' "$PWD" ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -115,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -173,7 +171,6 @@ fi # 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" ) @@ -206,15 +203,14 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index 9d21a218..a51ec4f5 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -19,12 +19,12 @@ @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @@ -51,7 +51,7 @@ echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -65,30 +65,18 @@ echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :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 %* +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:end -@rem End local scope for the variables with windows NT shell -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! -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 - -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 index 80a10f55..eb39e337 100644 --- a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 +++ b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 @@ -1,3 +1,3 @@ -// 1.21.1 2024-12-06T17:16:20.755131366 codechickenlib Languages: en_us +// 1.21.10 2025-11-01T00:02:49.273916263 codechickenlib Languages: en_us d535acbe9649e564744ed63aef209ce1508ec451 assets/codechickenlib/lang/en_us.json d535acbe9649e564744ed63aef209ce1508ec451 data/codechickenlib/lang/en_us.json diff --git a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 index bc503cb2..299ba6c3 100644 --- a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 +++ b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 @@ -1,4 +1,4 @@ -// 1.21.1 2024-12-06T17:16:20.746404632 CodeChickenLib Block tags. +// 1.21.10 2025-11-01T00:02:49.272952237 CodeChickenLib Block tags. 9b9a1318b746e42366ee1747896a1c61d71bc0ae data/c/tags/block/wools.json dc26d59698d238e0c60c400dbffea2ba82af4365 data/c/tags/block/wools/black.json 4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/c/tags/block/wools/blue.json diff --git a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 index c16bbd75..7d45eab0 100644 --- a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 +++ b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 @@ -1,4 +1,4 @@ -// 1.21.1 2024-12-06T17:16:20.755323336 CodeChickenLib Item tags. +// 1.21.10 2025-11-01T00:02:49.274097985 CodeChickenLib Item tags. 9b9a1318b746e42366ee1747896a1c61d71bc0ae data/c/tags/item/wools.json dc26d59698d238e0c60c400dbffea2ba82af4365 data/c/tags/item/wools/black.json 4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/c/tags/item/wools/blue.json diff --git a/src/main/java/codechicken/lib/CodeChickenLib.java b/src/main/java/codechicken/lib/CodeChickenLib.java index 3886c1e6..31fc2709 100644 --- a/src/main/java/codechicken/lib/CodeChickenLib.java +++ b/src/main/java/codechicken/lib/CodeChickenLib.java @@ -3,22 +3,19 @@ import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigFile; import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.internal.CCLNetwork; import codechicken.lib.internal.ClientInit; import codechicken.lib.internal.DataGenerators; import codechicken.lib.internal.TileChunkLoadHook; import codechicken.lib.internal.command.CCLCommands; -import codechicken.lib.internal.network.CCLNetwork; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.ModContainer; import net.neoforged.fml.common.Mod; import net.neoforged.fml.loading.FMLConfig; import net.neoforged.fml.loading.FMLEnvironment; -import org.jetbrains.annotations.Nullable; import java.nio.file.Paths; -import static java.util.Objects.requireNonNull; - /** * Created by covers1624 on 12/10/2016. */ @@ -33,29 +30,23 @@ public class CodeChickenLib { public static final String MOD_ID = "codechickenlib"; - private static @Nullable ModContainer container; - public static ConfigCategory config; public CodeChickenLib(ModContainer container, IEventBus modBus) { - CodeChickenLib.container = container; config = new ConfigFile(MOD_ID) .path(Paths.get("config/ccl.cfg")) .load(); - if (FMLEnvironment.dist.isClient()) { + + if (FMLEnvironment.getDist().isClient()) { ClientInit.init(modBus); } ConfigSyncManager.init(modBus); CCLCommands.init(); - CCLNetwork.init(modBus); + CCLNetwork.init(modBus, container); TileChunkLoadHook.init(); // ConditionalIngredient.Serializer.init(); DataGenerators.init(modBus); } - - public static ModContainer container() { - return requireNonNull(container); - } } diff --git a/src/main/java/codechicken/lib/block/LazyStateBlock.java b/src/main/java/codechicken/lib/block/LazyStateBlock.java index ab7a0264..38223730 100644 --- a/src/main/java/codechicken/lib/block/LazyStateBlock.java +++ b/src/main/java/codechicken/lib/block/LazyStateBlock.java @@ -4,10 +4,12 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.ApiStatus; import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Function; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; @@ -18,6 +20,7 @@ *

    * Created by covers1624 on 18/7/22. */ +// TODO On Java25 this may not be required anymore as we can do stuff before a super ctor call. @ApiStatus.Experimental public abstract class LazyStateBlock extends Block { @@ -95,4 +98,16 @@ private void computeState() { protected final void createBlockStateDefinition(StateDefinition.Builder builder) { // Explicitly disallowed. } + + @Override + protected Function getShapeForEachState(Function shapeGetter) { + computeState(); + return super.getShapeForEachState(shapeGetter); + } + + @Override + protected Function getShapeForEachState(Function shapeGetter, Property... properties) { + computeState(); + return super.getShapeForEachState(shapeGetter, properties); + } } diff --git a/src/main/java/codechicken/lib/block/ModularBlockEntity.java b/src/main/java/codechicken/lib/block/ModularBlockEntity.java index ab3cfaa9..0a67f4c2 100644 --- a/src/main/java/codechicken/lib/block/ModularBlockEntity.java +++ b/src/main/java/codechicken/lib/block/ModularBlockEntity.java @@ -1,15 +1,22 @@ package codechicken.lib.block; import codechicken.lib.block.ModularTileBlock.TileComponent; +import codechicken.lib.internal.CCLNetwork; import net.minecraft.core.BlockPos; -import net.minecraft.core.HolderLookup; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import net.neoforged.neoforge.network.handling.IPayloadContext; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; @@ -19,6 +26,8 @@ @ApiStatus.Experimental public abstract class ModularBlockEntity extends BlockEntity { + private static final byte COMPONENT_MESSAGE = 1; + private final ModularTileBlock block; private final DataComponent[] components; @@ -44,25 +53,52 @@ public final T getData(TileComponent component) { @Override @MustBeInvokedByOverriders - protected void saveAdditional(CompoundTag tag, HolderLookup.Provider registries) { - super.saveAdditional(tag, registries); + protected void saveAdditional(ValueOutput output) { + super.saveAdditional(output); for (DataComponent component : components) { - CompoundTag componentTag = new CompoundTag(); - component.save(componentTag, registries); - tag.put(component.tileComponent.name, componentTag); + component.save(output.child(component.tileComponent.name)); } } @Override @MustBeInvokedByOverriders - public void loadAdditional(CompoundTag tag, HolderLookup.Provider registries) { - super.loadAdditional(tag, registries); + protected void loadAdditional(ValueInput input) { + super.loadAdditional(input); for (DataComponent component : components) { - if (tag.contains(component.tileComponent.name)) { - component.load(tag.getCompound(component.tileComponent.name), registries); - } + var childIn = input.child(component.tileComponent.name); + childIn.ifPresent(component::load); + } + } + + private void sendServerPacket(Consumer cons) { + var packet = CCLNetwork.TILE_MESSAGE.toServer(); + packet.writeBlockPos(getBlockPos()); + cons.accept(packet); + packet.sendToServer(); + } + + public final void onInternalServerPacket(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + switch (packet.readUnsignedByte()) { + case COMPONENT_MESSAGE -> components[packet.readVarInt()].onServerPacket(packet, ctx); + } + } + + private void sendClientPacket(@Nullable ServerPlayer to, Consumer cons) { + var packet = CCLNetwork.TILE_MESSAGE.toClient(this); + packet.writeBlockPos(getBlockPos()); + cons.accept(packet); + if (to == null) { + packet.sendToChunk(this); + } else { + packet.sendToPlayer(to); + } + } + + public final void onInternalClientPacket(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + switch (packet.readUnsignedByte()) { + case COMPONENT_MESSAGE -> components[packet.readVarInt()].onClientPacket(packet, ctx); } } @@ -76,10 +112,32 @@ protected DataComponent(ModularBlockEntity tile, TileComponent tileComponent) this.tileComponent = tileComponent; } - protected void save(CompoundTag tag, HolderLookup.Provider registries) { + protected final void sendToServer(Consumer cons) { + tile.sendServerPacket(p -> { + p.writeByte(COMPONENT_MESSAGE); + p.writeVarInt(tileComponent.id); + cons.accept(p); + }); + } + + protected void onServerPacket(RegistryFriendlyByteBuf buf, IPayloadContext ctx) { + } + + protected final void sendToClient(@Nullable ServerPlayer to, Consumer cons) { + tile.sendClientPacket(to, p -> { + p.writeByte(COMPONENT_MESSAGE); + p.writeVarInt(tileComponent.id); + cons.accept(p); + }); + } + + protected void onClientPacket(RegistryFriendlyByteBuf buf, IPayloadContext ctx) { + } + + protected void save(ValueOutput output) { } - protected void load(CompoundTag tag, HolderLookup.Provider registries) { + protected void load(ValueInput input) { } } } diff --git a/src/main/java/codechicken/lib/block/ModularTileBlock.java b/src/main/java/codechicken/lib/block/ModularTileBlock.java index 111fd5fa..352ea958 100644 --- a/src/main/java/codechicken/lib/block/ModularTileBlock.java +++ b/src/main/java/codechicken/lib/block/ModularTileBlock.java @@ -24,12 +24,12 @@ public abstract class ModularTileBlock extends ModularBlock implements EntityBlock { final Map> namedComponents = new HashMap<>(); - private final LazyValue> type; + private final Supplier> type; - private final TickList clientTicks = new TickList(); - private final TickList serverTicks = new TickList(); + protected final TickList clientTicks = new TickList<>(); + protected final TickList serverTicks = new TickList<>(); - public ModularTileBlock(Properties props, Supplier> typeSupplier) { + public ModularTileBlock(Properties props, Supplier> typeSupplier) { super(props); type = new LazyValue<>(typeSupplier); } @@ -52,14 +52,21 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Nullable @Override @SuppressWarnings ("unchecked") - public final BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { + public final BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { if (type != this.type.get()) return null; - if (level.isClientSide) { - return (BlockEntityTicker) clientTicks.compileTicker(); + if (level.isClientSide()) { + return (BlockEntityTicker) clientTicks.compileTicker(); } - return (BlockEntityTicker)serverTicks.compileTicker(); + return (BlockEntityTicker) serverTicks.compileTicker(); + } + + @Override + protected boolean triggerEvent(BlockState state, Level level, BlockPos pos, int id, int param) { + super.triggerEvent(state, level, pos, id, param); + BlockEntity be = level.getBlockEntity(pos); + return be != null && be.triggerEvent(id, param); } public static abstract class TileComponent extends Component { @@ -70,26 +77,26 @@ public static abstract class TileComponent extends Comp protected abstract D createData(ModularBlockEntity ent); } - private static class TickList { + public static class TickList { - private final LinkedList> tickers = new LinkedList<>(); + private final LinkedList> tickers = new LinkedList<>(); @Nullable - private BlockEntityTicker compiled; + private BlockEntityTicker compiled; - private void addTickerFirst(BlockEntityTicker pre) { + public void addTickerFirst(BlockEntityTicker pre) { assert compiled == null : "Unable to hot-add new tickers."; tickers.addFirst(pre); } - private void addTicker(BlockEntityTicker ticker) { + public void addTicker(BlockEntityTicker ticker) { assert compiled == null : "Unable to hot-add new tickers."; tickers.add(ticker); } @Nullable - private BlockEntityTicker compileTicker() { + private BlockEntityTicker compileTicker() { if (compiled != null) return compiled; if (tickers.isEmpty()) return null; @@ -98,10 +105,10 @@ private BlockEntityTicker compileTicker() { tickers.clear(); } else { @SuppressWarnings ("unchecked") - BlockEntityTicker[] tickers = this.tickers.toArray(new BlockEntityTicker[0]); + BlockEntityTicker[] tickers = this.tickers.toArray(BlockEntityTicker[]::new); this.tickers.clear(); compiled = (level, pos, state, tile) -> { - for (BlockEntityTicker ticker : tickers) { + for (var ticker : tickers) { ticker.tick(level, pos, state, tile); } }; diff --git a/src/main/java/codechicken/lib/block/component/DirectionComponent.java b/src/main/java/codechicken/lib/block/component/DirectionComponent.java index d145d80b..e5d58c80 100644 --- a/src/main/java/codechicken/lib/block/component/DirectionComponent.java +++ b/src/main/java/codechicken/lib/block/component/DirectionComponent.java @@ -20,6 +20,7 @@ public class DirectionComponent extends PropertyComponent { public static PlacementFunc NONE = (state, ctx) -> null; public static PlacementFunc PLAYER_HORIZONTAL = (state, ctx) -> ctx.getHorizontalDirection(); + public static PlacementFunc PLAYER_HORIZONTAL_OPPOSITE = (state, ctx) -> ctx.getHorizontalDirection().getOpposite(); public static PlacementFunc PLAYER_LOOKING_NEAREST = (state, ctx) -> ctx.getNearestLookingDirection().getOpposite(); public static PlacementFunc FACE_NORMAL = (state, ctx) -> ctx.getClickedFace(); diff --git a/src/main/java/codechicken/lib/block/component/PropertyComponent.java b/src/main/java/codechicken/lib/block/component/PropertyComponent.java index 7f6cf5d3..3d83924f 100644 --- a/src/main/java/codechicken/lib/block/component/PropertyComponent.java +++ b/src/main/java/codechicken/lib/block/component/PropertyComponent.java @@ -1,5 +1,6 @@ package codechicken.lib.block.component; +import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; import org.jetbrains.annotations.ApiStatus; @@ -16,4 +17,8 @@ protected PropertyComponent(Property property, V defaultValue) { this.property = property; this.defaultValue = defaultValue; } + + public final V get(BlockState state) { + return state.getValue(property); + } } diff --git a/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java b/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java index d1237487..b55d6b8e 100644 --- a/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java +++ b/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java @@ -4,12 +4,11 @@ import codechicken.lib.block.ModularTileBlock; import codechicken.lib.inventory.InventoryUtils; import codechicken.lib.util.ArrayUtils; -import net.minecraft.core.HolderLookup; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; import org.jetbrains.annotations.ApiStatus; import java.util.LinkedList; @@ -122,13 +121,13 @@ public int getMaxStackSize() { } @Override - protected void save(CompoundTag tag, HolderLookup.Provider registries) { - tag.put("Items", InventoryUtils.writeItemStacksToTag(registries, items)); + protected void save(ValueOutput output) { + InventoryUtils.writeItemStacksToOutput(output, items); } @Override - protected void load(CompoundTag tag, HolderLookup.Provider registries) { - InventoryUtils.readItemStacksFromTag(registries, items, tag.getList("Items", Tag.TAG_COMPOUND)); + protected void load(ValueInput input) { + InventoryUtils.readItemStacksFromInput(input, items); } } } diff --git a/src/main/java/codechicken/lib/block/component/tile/ValueComponent.java b/src/main/java/codechicken/lib/block/component/tile/ValueComponent.java new file mode 100644 index 00000000..61820a66 --- /dev/null +++ b/src/main/java/codechicken/lib/block/component/tile/ValueComponent.java @@ -0,0 +1,109 @@ +package codechicken.lib.block.component.tile; + +import codechicken.lib.block.ModularBlockEntity; +import codechicken.lib.block.ModularTileBlock; +import com.mojang.serialization.Codec; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import net.neoforged.neoforge.network.handling.IPayloadContext; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +/** + * Created by covers1624 on 3/29/26. + */ +@ApiStatus.Experimental +public class ValueComponent extends ModularTileBlock.TileComponent.Data> { + + private final Codec codec; + private final V defaultValue; + + private @Nullable StreamCodec streamCodec; + + public ValueComponent(Codec codec, V defaultValue) { + this.codec = codec; + this.defaultValue = defaultValue; + } + + public ValueComponent syncToClient(StreamCodec codec) { + streamCodec = codec; + return this; + } + + @Override + protected Data createData(ModularBlockEntity ent) { + return new Data(ent, this); + } + + public class Data extends ModularBlockEntity.DataComponent { + + private final List> onChanged = new ArrayList<>(0); + + private V value = defaultValue; + + protected Data(ModularBlockEntity tile, ModularTileBlock.TileComponent tileComponent) { + super(tile, tileComponent); + } + + public Data onChanged(Consumer cons) { + onChanged.add(cons); + return this; + } + + public V get() { + return value; + } + + public void set(V value) { + if (!this.value.equals(value)) { + forceSet(value); + onChanged(); + } + } + + public void forceSet(V value) { + this.value = value; + } + + public void onChanged() { + onChanged.forEach(e -> e.accept(value)); + + syncToClient(); + } + + public void syncToClient() { + if (tile.getLevel().isClientSide()) return; + if (streamCodec == null) throw new UnsupportedOperationException("No stream codec supplied."); + + sendToClient(null, p -> { + p.cc$writeWithRegistryCodec(streamCodec, value); + }); + } + + @Override + protected void onClientPacket(RegistryFriendlyByteBuf buf, IPayloadContext ctx) { + if (streamCodec == null) throw new IllegalStateException("Somehow received packet for component which does not have a codec.."); + + forceSet(buf.cc$readWithRegistryCodec(streamCodec)); + onChanged(); + } + + @Override + protected void save(ValueOutput output) { + super.save(output); + output.store("value", codec, value); + } + + @Override + protected void load(ValueInput input) { + super.load(input); + value = input.read("value", codec).orElse(defaultValue); + } + } +} diff --git a/src/main/java/codechicken/lib/colour/Colour.java b/src/main/java/codechicken/lib/colour/Colour.java index 07f1c9e9..9a8165e7 100644 --- a/src/main/java/codechicken/lib/colour/Colour.java +++ b/src/main/java/codechicken/lib/colour/Colour.java @@ -269,6 +269,78 @@ public static int packARGB(float[] data) { return packARGB(data[0], data[1], data[2], data[3]); } + public static int replace(int c, int i, float v) { + return replace(c, i, (int) (v * 255F)); + } + + /** + * Replace the packed 8-bit color component at the specified index. + * + * @param c The packed color. + * @param i The index to replace. + * @param v The value to replace with. + * @return The new packed color. + */ + public static int replace(int c, int i, int v) { + int mask = ~(0xFF << i * 8); + return c & mask | (v & 0xFF) << i * 8; + } + + public static int unpack(int c, int i) { + return (c >> (8 * i)) & 0xFF; + } + + public static int pack(int c, int i) { + return (c & 0xFF) << 8 * i; + } + + /** + * For each color component in c1 and c2, adds them together + * clamping to 0 - 255. + *

    + * Agnostic of color packing order. + */ + public static int add(int c1, int c2) { + int r = 0; + for (int i = 0; i < 4; i++) { + int a = unpack(c1, i); + int b = unpack(c2, i); + r |= pack(Math.min(a + b, 255), i); + } + return r; + } + + /** + * For each color component in c1 and c2, subtracts them + * clamping to 0 - 255. + *

    + * Agnostic of color packing order. + */ + public static int sub(int c1, int c2) { + int r = 0; + for (int i = 0; i < 4; i++) { + int a = unpack(c1, i); + int b = unpack(c2, i); + r |= pack(Math.max(a - b, 0), i); + } + return r; + } + + /** + * For each color component in c1 and c2, calculates the midpoint. + *

    + * Agnostic of color packing order. + */ + public static int mid(int c1, int c2) { + int r = 0; + for (int i = 0; i < 4; i++) { + int a = unpack(c1, i); + int b = unpack(c2, i); + r |= pack(b + (a - b) / 2, i); + } + return r; + } + public boolean equals(@Nullable Colour other) { if (other == null) return false; if (r != other.r) return false; diff --git a/src/main/java/codechicken/lib/colour/CustomGradient.java b/src/main/java/codechicken/lib/colour/CustomGradient.java index 85bc6af7..432db882 100644 --- a/src/main/java/codechicken/lib/colour/CustomGradient.java +++ b/src/main/java/codechicken/lib/colour/CustomGradient.java @@ -2,7 +2,7 @@ import codechicken.lib.math.MathHelper; import codechicken.lib.texture.TextureUtils; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import java.awt.image.BufferedImage; @@ -10,7 +10,7 @@ public class CustomGradient { public int[] gradient; - public CustomGradient(ResourceLocation textureFile) { + public CustomGradient(Identifier textureFile) { BufferedImage img = TextureUtils.loadBufferedImage(textureFile); if (img == null) { throw new RuntimeException("File not found: " + textureFile); diff --git a/src/main/java/codechicken/lib/colour/EnumColour.java b/src/main/java/codechicken/lib/colour/EnumColour.java index f9552a3c..bcec7d79 100644 --- a/src/main/java/codechicken/lib/colour/EnumColour.java +++ b/src/main/java/codechicken/lib/colour/EnumColour.java @@ -8,7 +8,7 @@ import net.minecraft.client.resources.language.I18n; import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.util.ByIdMap; import net.minecraft.util.StringRepresentable; @@ -49,8 +49,8 @@ public enum EnumColour implements StringRepresentable { public static final StreamCodec STREAM_CODEC = ByteBufCodecs.idMapper(BY_ID, EnumColour::ordinal); private final String name; - private final ResourceLocation dyeTagName; - private final ResourceLocation woolTagName; + private final Identifier dyeTagName; + private final Identifier woolTagName; private final String unlocalizedName; private final int rgb; @@ -59,10 +59,10 @@ public enum EnumColour implements StringRepresentable { private static final Map nameLookup = FastStream.of(values()) .toMap(e -> e.name, Function.identity()); - private static final Map dyeTagLookup = FastStream.of(values()) + private static final Map dyeTagLookup = FastStream.of(values()) .toMap(e -> e.dyeTagName, Function.identity()); - private static final Map woolTagLookup = FastStream.of(values()) + private static final Map woolTagLookup = FastStream.of(values()) .toMap(e -> e.woolTagName, Function.identity()); static { @@ -96,8 +96,8 @@ public enum EnumColour implements StringRepresentable { EnumColour(String name, String dyeTagName, String woolTagName, String unlocalizedName, int rgb) { this.name = name; - this.dyeTagName = ResourceLocation.parse(dyeTagName); - this.woolTagName = ResourceLocation.parse(woolTagName); + this.dyeTagName = Identifier.parse(dyeTagName); + this.woolTagName = Identifier.parse(woolTagName); this.unlocalizedName = unlocalizedName; this.rgb = rgb; } @@ -107,11 +107,11 @@ public String getSerializedName() { return name; } - public ResourceLocation getDyeTagName() { + public Identifier getDyeTagName() { return dyeTagName; } - public ResourceLocation getWoolTagName() { + public Identifier getWoolTagName() { return woolTagName; } @@ -190,11 +190,11 @@ public static EnumColour fromDyeMeta(int id) { return values()[15 - id]; } - public static @Nullable EnumColour fromDyeTag(ResourceLocation tag) { + public static @Nullable EnumColour fromDyeTag(Identifier tag) { return dyeTagLookup.get(tag); } - public static @Nullable EnumColour fromWoolTag(ResourceLocation tag) { + public static @Nullable EnumColour fromWoolTag(Identifier tag) { return woolTagLookup.get(tag); } diff --git a/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java b/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java index 5d027359..92f3657a 100644 --- a/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java @@ -1,8 +1,7 @@ package codechicken.lib.config; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.covers1624.quack.collection.ColUtils; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.Nullable; import java.util.*; @@ -182,39 +181,35 @@ public ConfigCategoryImpl copy(@Nullable ConfigCategoryImpl parent) { } @Override - public void write(MCDataOutput out) { - out.writeVarInt(tagMap.size()); + public void write(FriendlyByteBuf packet) { + packet.writeVarInt(tagMap.size()); for (AbstractConfigTag child : tagMap.values()) { if (!child.requiresClientSync()) { - out.writeByte(NET_NO_TAG); + packet.writeByte(NET_NO_TAG); continue; } - if (child instanceof ConfigCategory) { - out.writeByte(NET_CAT_TAG); - } else if (child instanceof ConfigValue) { - out.writeByte(NET_VAL_TAG); - } else if (child instanceof ConfigValueList) { - out.writeByte(NET_VAL_LST); - } else { - throw new IllegalStateException("Unknown tag class. " + child.getClass()); + switch (child) { + case ConfigCategory cat -> packet.writeByte(NET_CAT_TAG); + case ConfigValue val -> packet.writeByte(NET_VAL_TAG); + case ConfigValueList list -> packet.writeByte(NET_VAL_LST); + default -> throw new IllegalStateException("Unknown tag class. " + child.getClass()); } - out.writeString(child.getName()); - child.write(out); + packet.writeUtf(child.getName()); + child.write(packet); } } @Override - public void read(MCDataInput in) { + public void read(FriendlyByteBuf in) { int numTags = in.readVarInt(); for (int i = 0; i < numTags; i++) { byte t = in.readByte(); if (t == NET_NO_TAG) continue; - String name = in.readString(); + String name = in.readUtf(); ConfigTag tag = findTag(name); switch (t) { - default -> throw new IllegalStateException("Unknown tag network type: " + t); case NET_CAT_TAG -> { if (tag != null && !(tag instanceof ConfigCategoryImpl)) throw new IllegalStateException("Tried to read category into " + tag.getClass().getSimpleName()); if (tag == null) { @@ -239,6 +234,7 @@ public void read(MCDataInput in) { tag = cat; } } + default -> throw new IllegalStateException("Unknown tag network type: " + t); } tag.read(in); } diff --git a/src/main/java/codechicken/lib/config/ConfigFile.java b/src/main/java/codechicken/lib/config/ConfigFile.java index ef1e9766..1d4cca1b 100644 --- a/src/main/java/codechicken/lib/config/ConfigFile.java +++ b/src/main/java/codechicken/lib/config/ConfigFile.java @@ -1,9 +1,8 @@ package codechicken.lib.config; import codechicken.lib.config.parser.ConfigSerializer; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang3.NotImplementedException; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -38,7 +37,7 @@ public final class ConfigFile { *

    * The {@code rootName} is used when creating translation keys for * a given tag. It is recommended that you use your ModID for this, or - * a {@link ResourceLocation} like string. + * a {@link Identifier} like string. * * @param rootName The root name for the returned config. Usually * your ModID. diff --git a/src/main/java/codechicken/lib/config/ConfigSyncManager.java b/src/main/java/codechicken/lib/config/ConfigSyncManager.java index ca026b18..b45ecfd5 100644 --- a/src/main/java/codechicken/lib/config/ConfigSyncManager.java +++ b/src/main/java/codechicken/lib/config/ConfigSyncManager.java @@ -1,18 +1,19 @@ package codechicken.lib.config; -import codechicken.lib.packet.PacketCustom; +import codechicken.lib.packet.ConfigurationStreamPacket; +import codechicken.lib.packet.StreamNetworkChannel; import com.google.common.base.Joiner; import net.covers1624.quack.util.CrashLock; -import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.network.protocol.configuration.ServerConfigurationPacketListener; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; +import net.minecraft.server.network.ConfigurationTask; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.loading.FMLEnvironment; import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; import net.neoforged.neoforge.common.NeoForge; import net.neoforged.neoforge.network.configuration.ICustomConfigurationTask; -import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.ApiStatus; @@ -21,10 +22,6 @@ import java.util.Map; import java.util.function.Consumer; -import static codechicken.lib.CodeChickenLib.MOD_ID; -import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; -import static codechicken.lib.internal.network.CCLNetwork.NET_CHANNEL; - /** * Created by covers1624 on 19/5/22. */ @@ -33,7 +30,7 @@ public class ConfigSyncManager { private static final Logger LOGGER = LogManager.getLogger(); private static final CrashLock LOCK = new CrashLock("Already Initialized."); - private static final Map SYNC_MAP = new HashMap<>(); + private static final Map SYNC_MAP = new HashMap<>(); /** * Registers the specified {@link ConfigTag} for syncing. @@ -43,7 +40,7 @@ public class ConfigSyncManager { * @param key The unique id to associate this tag. * @param tag The Tag to sync. */ - public static void registerSync(ResourceLocation key, ConfigTag tag) { + public static void registerSync(Identifier key, ConfigTag tag) { ConfigTag prev = SYNC_MAP.put(key, tag); if (prev != null) { throw new IllegalArgumentException("Key '" + key + "' already registered."); @@ -54,18 +51,16 @@ public static void registerSync(ResourceLocation key, ConfigTag tag) { public static void init(IEventBus modBus) { LOCK.lock(); - if (FMLEnvironment.dist.isClient()) { + if (FMLEnvironment.getDist().isClient()) { NeoForge.EVENT_BUS.addListener(ConfigSyncManager::onClientDisconnected); } - - modBus.addListener(ConfigSyncManager::onGameConfigurationEvent); } @ApiStatus.Internal - public static void readSyncPacket(PacketCustom packet) { + public static void readSyncPacket(FriendlyByteBuf packet, IPayloadContext ctx) { int numPackets = packet.readVarInt(); for (int i = 0; i < numPackets; i++) { - ResourceLocation ident = packet.readResourceLocation(); + Identifier ident = packet.readIdentifier(); LOGGER.info("Applying config sync for {}.", ident); ConfigTag config = SYNC_MAP.get(ident); if (config == null) { @@ -78,7 +73,7 @@ public static void readSyncPacket(PacketCustom packet) { } private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut event) { - for (Map.Entry entry : SYNC_MAP.entrySet()) { + for (Map.Entry entry : SYNC_MAP.entrySet()) { LOGGER.info("Client disconnected, rolling back config for {}.", entry.getKey()); ConfigTag config = entry.getValue(); config.resetFromNetwork(); @@ -86,34 +81,24 @@ private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut eve } } - private static void onGameConfigurationEvent(RegisterConfigurationTasksEvent event) { - event.register(new ConfigSyncConfigurationTask(event.getListener())); - } - - private record ConfigSyncConfigurationTask(ServerConfigurationPacketListener listener) implements ICustomConfigurationTask { - - private static final Type TYPE = new Type(ResourceLocation.fromNamespaceAndPath(MOD_ID, "config_sync")); + @ApiStatus.Internal + public record ConfigSyncConfigurationTask(ConfigurationTask.Type type, StreamNetworkChannel.ConfigurationContext ctx) implements ICustomConfigurationTask { @Override public void run(Consumer sender) { if (!SYNC_MAP.isEmpty()) { - PacketCustom packet = new PacketCustom(NET_CHANNEL, L_CONFIG_SYNC, null); + ConfigurationStreamPacket packet = ctx.newPacket(); packet.writeVarInt(SYNC_MAP.size()); - for (Map.Entry entry : SYNC_MAP.entrySet()) { - packet.writeResourceLocation(entry.getKey()); + for (Map.Entry entry : SYNC_MAP.entrySet()) { + packet.writeIdentifier(entry.getKey()); entry.getValue().write(packet); } String mods = Joiner.on(", ").join(SYNC_MAP.keySet()); LOGGER.info("Sending config sync packet for {} to connecting player.", mods); - sender.accept(packet.toCustomPayload()); + sender.accept(packet); } - listener.finishCurrentTask(TYPE); - } - - @Override - public Type type() { - return TYPE; + ctx.packetListener().finishCurrentTask(type); } } } diff --git a/src/main/java/codechicken/lib/config/ConfigTag.java b/src/main/java/codechicken/lib/config/ConfigTag.java index c23da9bd..19da0e64 100644 --- a/src/main/java/codechicken/lib/config/ConfigTag.java +++ b/src/main/java/codechicken/lib/config/ConfigTag.java @@ -1,8 +1,7 @@ package codechicken.lib.config; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.Identifier; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -74,7 +73,7 @@ default String getDesc() { /** * Sets this tag as requiring syncing to the client. *

    - * Register your root tag via {@link ConfigSyncManager#registerSync(ResourceLocation, ConfigTag)}. + * Register your root tag via {@link ConfigSyncManager#registerSync(Identifier, ConfigTag)}. */ ConfigTag syncTagToClient(); @@ -168,16 +167,16 @@ default void delete() { ConfigTag copy(); /** - * Write this tag to a {@link MCDataOutput}. + * Write this tag to a {@link FriendlyByteBuf} packet. * Only categories and/or tags which have {@link #syncTagToClient()} set * will be written. * - * @param out The output stream. + * @param packet The packet to write to. */ - void write(MCDataOutput out); + void write(FriendlyByteBuf packet); /** - * Read this tag from a {@link MCDataInput}. + * Read this tag from a {@link FriendlyByteBuf} packet. * All tags and values will be read and inserted into the tree. *

    * If a tag does not already exist in the tree, one will be added and marked @@ -186,9 +185,9 @@ default void delete() { * All tags with a network value will be reset to default when {@link #resetFromNetwork()} * is called, whilst any 'network only' tags will be deleted. * - * @param in The input stream. + * @param packet The packet to read from. */ - void read(MCDataInput in); + void read(FriendlyByteBuf packet); /** * Resets all network tags back to their original value. diff --git a/src/main/java/codechicken/lib/config/ConfigValueImpl.java b/src/main/java/codechicken/lib/config/ConfigValueImpl.java index 206302b8..4cb07610 100644 --- a/src/main/java/codechicken/lib/config/ConfigValueImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigValueImpl.java @@ -1,7 +1,6 @@ package codechicken.lib.config; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -438,22 +437,22 @@ public AbstractConfigTag copy(@Nullable ConfigCategoryImpl parent) } @Override - public void write(MCDataOutput out) { + public void write(FriendlyByteBuf packet) { if (type == ValueType.UNKNOWN) throw new IllegalStateException("Tried to write UNKNOWN tag to network"); - out.writeEnum(type); + packet.writeEnum(type); switch (type) { - case BOOLEAN -> out.writeBoolean(getBoolean()); - case STRING -> out.writeString(getString()); - case INT -> out.writeInt(getInt()); // TODO varint? signedVarint? - case LONG -> out.writeLong(getLong()); // TODO varlong? signedVarlong? - case HEX -> out.writeInt(getHex()); // TODO varint? signedVarint? - case DOUBLE -> out.writeDouble(getDouble()); + case BOOLEAN -> packet.writeBoolean(getBoolean()); + case STRING -> packet.writeUtf(getString()); + case INT -> packet.writeInt(getInt()); // TODO varint? signedVarint? + case LONG -> packet.writeLong(getLong()); // TODO varlong? signedVarlong? + case HEX -> packet.writeInt(getHex()); // TODO varint? signedVarint? + case DOUBLE -> packet.writeDouble(getDouble()); } } @Override - public void read(MCDataInput in) { - ValueType netType = in.readEnum(ValueType.class); + public void read(FriendlyByteBuf packet) { + ValueType netType = packet.readEnum(ValueType.class); if (networkSynthetic) { type = netType; } @@ -461,11 +460,11 @@ public void read(MCDataInput in) { if (netType != type) throw new IllegalStateException("Tried to read a " + netType + " tag from the network into a " + type + " tag"); switch (type) { - case BOOLEAN -> networkValue = in.readBoolean(); - case STRING -> networkValue = in.readString(); - case INT, HEX -> networkValue = in.readInt(); - case LONG -> networkValue = in.readLong(); - case DOUBLE -> networkValue = in.readDouble(); + case BOOLEAN -> networkValue = packet.readBoolean(); + case STRING -> networkValue = packet.readUtf(); + case INT, HEX -> networkValue = packet.readInt(); + case LONG -> networkValue = packet.readLong(); + case DOUBLE -> networkValue = packet.readDouble(); } } diff --git a/src/main/java/codechicken/lib/config/ConfigValueListImpl.java b/src/main/java/codechicken/lib/config/ConfigValueListImpl.java index 66005a77..a1804100 100644 --- a/src/main/java/codechicken/lib/config/ConfigValueListImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigValueListImpl.java @@ -1,8 +1,7 @@ package codechicken.lib.config; import codechicken.lib.config.ListRestriction.Failure; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; +import codechicken.lib.packet.CCStreamCodecs; import it.unimi.dsi.fastutil.booleans.BooleanArrayList; import it.unimi.dsi.fastutil.booleans.BooleanList; import it.unimi.dsi.fastutil.booleans.BooleanLists; @@ -16,6 +15,8 @@ import it.unimi.dsi.fastutil.longs.LongList; import it.unimi.dsi.fastutil.longs.LongLists; import net.covers1624.quack.collection.FastStream; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -350,28 +351,22 @@ public AbstractConfigTag copy(@Nullable ConfigCategoryImpl pare } @Override - public void write(MCDataOutput out) { + public void write(FriendlyByteBuf packet) { if (type == ValueType.UNKNOWN) throw new IllegalStateException("Tried to write UNKNOWN tag to network"); - out.writeEnum(type); + packet.writeEnum(type); switch (type) { - case STRING -> { - List values = getStrings(); - out.writeVarInt(values.size()); - for (String s : values) { - out.writeString(s); - } - } - case BOOLEAN -> out.writeBooleans(getBooleans().toBooleanArray()); - case INT -> out.writeInts(getInts().toIntArray()); - case LONG -> out.writeLongs(getLongs().toLongArray()); - case HEX -> out.writeInts(getHexs().toIntArray()); - case DOUBLE -> out.writeDoubles(getDoubles().toDoubleArray()); + case STRING -> packet.writeCollection(getStrings(), ByteBufCodecs.STRING_UTF8); + case BOOLEAN -> packet.cc$writeWithCodec(CCStreamCodecs.BOOLEAN_ARRAY, getBooleans().toBooleanArray()); + case INT -> packet.cc$writeWithCodec(CCStreamCodecs.INT_ARRAY, getInts().toIntArray()); + case LONG -> packet.cc$writeWithCodec(CCStreamCodecs.LONG_ARRAY, getLongs().toLongArray()); + case HEX -> packet.cc$writeWithCodec(CCStreamCodecs.INT_ARRAY, getHexs().toIntArray()); + case DOUBLE -> packet.cc$writeWithCodec(CCStreamCodecs.DOUBLE_ARRAY, getDoubles().toDoubleArray()); } } @Override - public void read(MCDataInput in) { - ValueType netType = in.readEnum(ValueType.class); + public void read(FriendlyByteBuf packet) { + ValueType netType = packet.readEnum(ValueType.class); if (networkSynthetic) { type = netType; } @@ -379,11 +374,11 @@ public void read(MCDataInput in) { if (netType != type) throw new IllegalStateException("Tried to read a " + netType + " tag from the network into a " + type + " tag"); switch (type) { - case STRING -> networkValue = readStringList(in); - case BOOLEAN -> networkValue = new BooleanArrayList(in.readBooleans()); - case INT, HEX -> networkValue = new IntArrayList(in.readInts()); - case LONG -> networkValue = new LongArrayList(in.readLongs()); - case DOUBLE -> networkValue = new DoubleArrayList(in.readDoubles()); + case STRING -> networkValue = packet.readList(ByteBufCodecs.STRING_UTF8); + case BOOLEAN -> networkValue = new BooleanArrayList(packet.cc$readWithCodec(CCStreamCodecs.BOOLEAN_ARRAY)); + case INT, HEX -> networkValue = new IntArrayList(packet.cc$readWithCodec(CCStreamCodecs.INT_ARRAY)); + case LONG -> networkValue = new LongArrayList(packet.cc$readWithCodec(CCStreamCodecs.LONG_ARRAY)); + case DOUBLE -> networkValue = new DoubleArrayList(packet.cc$readWithCodec(CCStreamCodecs.DOUBLE_ARRAY)); } } @@ -392,15 +387,6 @@ public void resetFromNetwork() { networkValue = null; } - private List readStringList(MCDataInput in) { - int len = in.readVarInt(); - List values = new ArrayList<>(len); - for (int i = 0; i < len; i++) { - values.add(in.readString()); - } - return values; - } - public ConfigValueList setValue(List value) { this.value = value; if (type != ValueType.UNKNOWN) { diff --git a/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java b/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java index b588df8f..41f13848 100644 --- a/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java +++ b/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java @@ -6,7 +6,7 @@ import it.unimi.dsi.fastutil.objects.Object2CharArrayMap; import it.unimi.dsi.fastutil.objects.Object2CharMap; import net.covers1624.quack.io.IOUtils; -import net.minecraft.Util; +import net.minecraft.util.Util; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/codechicken/lib/data/DataUtils.java b/src/main/java/codechicken/lib/data/DataUtils.java index c29909bf..6436f7f4 100644 --- a/src/main/java/codechicken/lib/data/DataUtils.java +++ b/src/main/java/codechicken/lib/data/DataUtils.java @@ -5,6 +5,7 @@ /** * Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) class DataUtils { /** diff --git a/src/main/java/codechicken/lib/data/MCByteStream.java b/src/main/java/codechicken/lib/data/MCByteStream.java index e7938c7b..988c1a94 100644 --- a/src/main/java/codechicken/lib/data/MCByteStream.java +++ b/src/main/java/codechicken/lib/data/MCByteStream.java @@ -8,6 +8,7 @@ *

    * Created by covers1624 on 4/16/20. */ +@Deprecated (forRemoval = true) public class MCByteStream extends MCDataOutputStream { private final ByteArrayOutputStream bos; diff --git a/src/main/java/codechicken/lib/data/MCDataByteBuf.java b/src/main/java/codechicken/lib/data/MCDataByteBuf.java index 17bd359c..2b835aca 100644 --- a/src/main/java/codechicken/lib/data/MCDataByteBuf.java +++ b/src/main/java/codechicken/lib/data/MCDataByteBuf.java @@ -19,6 +19,7 @@ *

    * Created by covers1624 on 4/16/20. */ +@Deprecated (forRemoval = true) public class MCDataByteBuf implements MCDataInput, MCDataOutput { protected final ByteBuf buf; diff --git a/src/main/java/codechicken/lib/data/MCDataInput.java b/src/main/java/codechicken/lib/data/MCDataInput.java index a85687d7..498ce3bf 100644 --- a/src/main/java/codechicken/lib/data/MCDataInput.java +++ b/src/main/java/codechicken/lib/data/MCDataInput.java @@ -13,9 +13,10 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.codec.StreamDecoder; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; @@ -43,6 +44,7 @@ *

    * Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) public interface MCDataInput { //region Primitives @@ -527,12 +529,12 @@ default Cuboid6 readCuboid() { //region MinecraftObjects /** - * Reads a {@link ResourceLocation} from the stream. + * Reads a {@link Identifier} from the stream. * - * @return The {@link ResourceLocation}. + * @return The {@link Identifier}. */ - default ResourceLocation readResourceLocation() { - return ResourceLocation.parse(readString()); + default Identifier readResourceLocation() { + return Identifier.parse(readString()); } /** @@ -629,8 +631,8 @@ default FluidStack readFluidStack() { * * @return The {@link Component}. */ - default MutableComponent readTextComponent() { - return requireNonNull(Component.Serializer.fromJson(readString(), RegistryAccess.EMPTY)); + default Component readTextComponent() { + return readWithRegistryCodec(ComponentSerialization.STREAM_CODEC); } /** @@ -653,7 +655,7 @@ default T readRegistryIdDirect(Registry registry) { * @see MCDataOutput#writeRegistryId(Registry, ResourceLocation) */ default T readRegistryId() { - ResourceLocation rName = readResourceLocation(); + Identifier rName = readResourceLocation(); return readRegistryIdDirect(unsafeCast(requireNonNull(BuiltInRegistries.REGISTRY.get(rName), "Registry " + rName + " not found."))); } diff --git a/src/main/java/codechicken/lib/data/MCDataInputStream.java b/src/main/java/codechicken/lib/data/MCDataInputStream.java index 0b6e5b86..35a6fa1e 100644 --- a/src/main/java/codechicken/lib/data/MCDataInputStream.java +++ b/src/main/java/codechicken/lib/data/MCDataInputStream.java @@ -14,6 +14,7 @@ *

    * Created by covers1624 on 4/16/20. */ +@Deprecated (forRemoval = true) public class MCDataInputStream implements MCDataInput { private final DataInput in; diff --git a/src/main/java/codechicken/lib/data/MCDataOutput.java b/src/main/java/codechicken/lib/data/MCDataOutput.java index 33a43cb7..9a11a695 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutput.java +++ b/src/main/java/codechicken/lib/data/MCDataOutput.java @@ -10,8 +10,9 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; import net.minecraft.network.codec.StreamEncoder; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; import net.neoforged.neoforge.fluids.FluidStack; @@ -36,6 +37,7 @@ *

    * Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) public interface MCDataOutput { //region Primitives. @@ -758,12 +760,12 @@ default MCDataOutput writeCuboid(Cuboid6 cuboid) { //region Minecraft Objects. /** - * Writes a {@link ResourceLocation} to the stream. + * Writes a {@link Identifier} to the stream. * - * @param loc The {@link ResourceLocation}. + * @param loc The {@link Identifier}. * @return The same stream. */ - default MCDataOutput writeResourceLocation(ResourceLocation loc) { + default MCDataOutput writeResourceLocation(Identifier loc) { return writeString(loc.toString()); } @@ -887,7 +889,7 @@ default MCDataOutput writeFluidStack(FluidStack stack) { * @return The same stream. */ default MCDataOutput writeTextComponent(Component component) { - return writeString(Component.Serializer.toJson(component, RegistryAccess.EMPTY), 262144);//32kb + return writeWithRegistryCodec(ComponentSerialization.STREAM_CODEC, component); } /** @@ -913,7 +915,7 @@ default MCDataOutput writeRegistryIdDirect(Registry registry, T entry) { * @param entry The name of the registry object to write. * @return The same stream. */ - default MCDataOutput writeRegistryIdDirect(Registry registry, ResourceLocation entry) { + default MCDataOutput writeRegistryIdDirect(Registry registry, Identifier entry) { writeVarInt(registry.getId(entry)); return this; } @@ -927,7 +929,7 @@ default MCDataOutput writeRegistryIdDirect(Registry registry, ResourceLoc * @return The same stream. */ default MCDataOutput writeRegistryId(Registry registry, T entry) { - ResourceLocation rName = registry.key().location(); + Identifier rName = registry.key().identifier(); if (!registry.containsValue(entry)) { throw new IllegalArgumentException(String.format("Registry '%s' does not contain entry '%s'", rName, entry)); } @@ -944,8 +946,8 @@ default MCDataOutput writeRegistryId(Registry registry, T entry) { * @param entry The name of the registry object to write. * @return The same stream. */ - default MCDataOutput writeRegistryId(Registry registry, ResourceLocation entry) { - ResourceLocation rName = registry.key().location(); + default MCDataOutput writeRegistryId(Registry registry, Identifier entry) { + Identifier rName = registry.key().identifier(); if (!registry.containsKey(entry)) { throw new IllegalArgumentException(String.format("Registry '%s' does not contain entry '%s'", rName, entry)); } diff --git a/src/main/java/codechicken/lib/data/MCDataOutputStream.java b/src/main/java/codechicken/lib/data/MCDataOutputStream.java index 92a65f98..589d4b72 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutputStream.java +++ b/src/main/java/codechicken/lib/data/MCDataOutputStream.java @@ -14,6 +14,7 @@ *

    * Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) public class MCDataOutputStream implements MCDataOutput { private final DataOutput out; diff --git a/src/main/java/codechicken/lib/data/package-info.java b/src/main/java/codechicken/lib/data/package-info.java index ab241486..107cbc61 100644 --- a/src/main/java/codechicken/lib/data/package-info.java +++ b/src/main/java/codechicken/lib/data/package-info.java @@ -1,4 +1,5 @@ @NonNullApi +@Deprecated (forRemoval = true) package codechicken.lib.data; import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java b/src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java deleted file mode 100644 index f37cc026..00000000 --- a/src/main/java/codechicken/lib/datagen/ClassModelLoaderBuilder.java +++ /dev/null @@ -1,47 +0,0 @@ -package codechicken.lib.datagen; - -import com.google.gson.JsonObject; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.neoforge.client.model.generators.CustomLoaderBuilder; -import net.neoforged.neoforge.client.model.generators.ModelBuilder; -import net.neoforged.neoforge.common.data.ExistingFileHelper; -import org.jetbrains.annotations.Nullable; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; - -import static codechicken.lib.CodeChickenLib.MOD_ID; -import static java.util.Objects.requireNonNull; - -/** - * Created by covers1624 on 1/21/25. - */ -public class ClassModelLoaderBuilder> extends CustomLoaderBuilder { - - private @Nullable Class clazz; - - public ClassModelLoaderBuilder(T parent, ExistingFileHelper existingFileHelper) { - super(ResourceLocation.fromNamespaceAndPath(MOD_ID, "class"), parent, existingFileHelper, false); - } - - public ClassModelLoaderBuilder clazz(Class clazz) { - try { - Constructor ctor = clazz.getConstructor(); - if (!Modifier.isPublic(ctor.getModifiers())) { - throw new IllegalArgumentException("Expected single no-args public constructor."); - } - } catch (NoSuchMethodException ex) { - throw new IllegalStateException("Expected single no-args public constructor.", ex); - } - this.clazz = clazz; - return this; - } - - @Override - public JsonObject toJson(JsonObject json) { - super.toJson(json); - json.addProperty("class", requireNonNull(clazz).getName()); - return json; - } -} diff --git a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java b/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java deleted file mode 100644 index 2f419b2f..00000000 --- a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java +++ /dev/null @@ -1,137 +0,0 @@ -//package codechicken.lib.datagen; -// -//import codechicken.lib.datagen.recipe.ConditionBuilder; -//import com.google.gson.JsonArray; -//import com.google.gson.JsonElement; -//import com.google.gson.JsonObject; -//import net.covers1624.quack.util.CrashLock; -//import net.minecraft.network.FriendlyByteBuf; -//import net.minecraft.resources.ResourceLocation; -//import net.minecraft.util.GsonHelper; -//import net.minecraft.world.item.ItemStack; -//import net.minecraft.world.item.crafting.Ingredient; -//import net.minecraftforge.common.MinecraftForge; -//import net.minecraftforge.common.crafting.AbstractIngredient; -//import net.minecraftforge.common.crafting.CraftingHelper; -//import net.minecraftforge.common.crafting.IIngredientSerializer; -//import net.minecraftforge.common.crafting.conditions.ICondition; -//import net.minecraftforge.event.AddReloadListenerEvent; -//import org.jetbrains.annotations.Nullable; -// -//import java.util.LinkedList; -//import java.util.List; -//import java.util.function.Function; -// -//import static codechicken.lib.CodeChickenLib.MOD_ID; -// -///** -// * Created by covers1624 on 24/9/22. -// */ -//public class ConditionalIngredient extends AbstractIngredient { -// -// private static final ResourceLocation TYPE = new ResourceLocation(MOD_ID, "conditional"); -// -// private final List conditions; -// private final Ingredient pass; -// @Nullable -// private final Ingredient fail; -// -// private ConditionalIngredient(List conditions, Ingredient pass, @Nullable Ingredient fail) { -// this.conditions = conditions; -// this.pass = pass; -// this.fail = fail; -// } -// -// public static ConditionalIngredient.Builder builder() { -// return new ConditionalIngredient.Builder(); -// } -// -// @Override -// public JsonElement toJson() { -// JsonObject obj = new JsonObject(); -// obj.addProperty("type", TYPE.toString()); -// JsonArray conditions = new JsonArray(); -// for (ICondition condition : this.conditions) { -// conditions.add(CraftingHelper.serialize(condition)); -// } -// obj.add("conditions", conditions); -// obj.add("pass", pass.toJson()); -// if (fail != null) { -// obj.add("fail", fail.toJson()); -// } -// return obj; -// } -// -// // @formatter:off -// @Override public ItemStack[] getItems() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } -// @Override public boolean isSimple() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } -// @Override public IIngredientSerializer getSerializer() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } -// // @formatter:on -// -// public static class Builder { -// -// private List conditions = new LinkedList<>(); -// private Ingredient pass = null; -// private Ingredient fail = null; -// -// private Builder() { -// } -// -// public Builder withCondition(Function func) { -// conditions.add(func.apply(ConditionBuilder.INSTANCE)); -// return this; -// } -// -// public Builder withPass(Ingredient ing) { -// if (pass != null) throw new IllegalStateException("Pass Ingredient already specified."); -// this.pass = ing; -// return this; -// } -// -// public Builder withFail(Ingredient ing) { -// if (fail != null) throw new IllegalStateException("Pass Ingredient already specified."); -// this.fail = ing; -// return this; -// } -// -// public ConditionalIngredient build() { -// if (conditions.isEmpty()) throw new IllegalStateException("No conditions specified."); -// if (pass == null) throw new IllegalStateException("Pass Ingredient is required."); -// -// return new ConditionalIngredient(conditions, pass, fail); -// } -// } -// -// public static class Serializer implements IIngredientSerializer { -// -// private static final CrashLock LOCK = new CrashLock("Already Initialized"); -// private static ICondition.IContext conditionContext = ICondition.IContext.EMPTY; -// -// public static void init() { -// LOCK.lock(); -// MinecraftForge.EVENT_BUS.addListener(Serializer::onAddReloadListenerEvent); -// CraftingHelper.register(TYPE, new Serializer()); -// } -// -// private static void onAddReloadListenerEvent(AddReloadListenerEvent event) { -// conditionContext = event.getConditionContext(); -// } -// -// @Override -// public Ingredient parse(JsonObject json) { -// if (!CraftingHelper.processConditions(json, "conditions", conditionContext)) { -// if (json.has("fail")) { -// return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "fail"), true); -// } -// return Ingredient.EMPTY; -// } -// return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "pass"), false); -// } -// -// // We don't operate like this, we always return a different ingredient. -// // @formatter:off -// @Override public Ingredient parse(FriendlyByteBuf buffer) { throw new UnsupportedOperationException(); } -// @Override public void write(FriendlyByteBuf buffer, Ingredient ingredient) { throw new UnsupportedOperationException(); } -// // @formatter:on -// } -//} diff --git a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java index 871f4b60..fba42eb1 100644 --- a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java +++ b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java @@ -3,15 +3,14 @@ import codechicken.lib.gui.modular.lib.DynamicTextures; import com.google.common.hash.Hashing; import com.google.common.hash.HashingOutputStream; -import net.minecraft.Util; +import net.minecraft.util.Util; import net.minecraft.data.CachedOutput; import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.PackType; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.Resource; -import net.neoforged.neoforge.common.data.ExistingFileHelper; +import net.minecraft.server.packs.resources.ResourceManager; import javax.imageio.ImageIO; import java.awt.*; @@ -32,13 +31,13 @@ public class DynamicTextureProvider implements DataProvider { private final DataGenerator gen; - private final ExistingFileHelper fileHelper; + private final ResourceManager resourceManager; private final String modid; private final List results = new ArrayList<>(); - public DynamicTextureProvider(DataGenerator gen, ExistingFileHelper fileHelper, String modid) { + public DynamicTextureProvider(DataGenerator gen, ResourceManager resourceManager, String modid) { this.gen = gen; - this.fileHelper = fileHelper; + this.resourceManager = resourceManager; this.modid = modid; } @@ -60,23 +59,25 @@ public void addDynamicTexture(String dynamicInput, String outputTexture, int wid } public void addDynamicTexture(String dynamicInput, String outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { - addDynamicTexture(ResourceLocation.fromNamespaceAndPath(modid, dynamicInput), ResourceLocation.fromNamespaceAndPath(modid, outputTexture), width, height, topBorder, leftBorder, bottomBorder, rightBorder); + addDynamicTexture(Identifier.fromNamespaceAndPath(modid, dynamicInput), Identifier.fromNamespaceAndPath(modid, outputTexture), width, height, topBorder, leftBorder, bottomBorder, rightBorder); } - public void addDynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputTexture, int width, int height, int border) { + public void addDynamicTexture(Identifier dynamicInput, Identifier outputTexture, int width, int height, int border) { addDynamicTexture(dynamicInput, outputTexture, width, height, border, border, border, border); } - public void addDynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + public void addDynamicTexture(Identifier dynamicInput, Identifier outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { try { if (!dynamicInput.getPath().endsWith(".png")) { - dynamicInput = ResourceLocation.fromNamespaceAndPath(dynamicInput.getNamespace(), dynamicInput.getPath() + ".png"); + dynamicInput = Identifier.fromNamespaceAndPath(dynamicInput.getNamespace(), dynamicInput.getPath() + ".png"); } if (!outputTexture.getPath().endsWith(".png")) { - outputTexture = ResourceLocation.fromNamespaceAndPath(outputTexture.getNamespace(), outputTexture.getPath() + ".png"); + outputTexture = Identifier.fromNamespaceAndPath(outputTexture.getNamespace(), outputTexture.getPath() + ".png"); } - Resource inputResource = fileHelper.getResource(dynamicInput, PackType.CLIENT_RESOURCES); + Resource inputResource = resourceManager.getResource(dynamicInput).orElse(null); + if (inputResource == null) throw new RuntimeException("Dynamic input " + dynamicInput + " does not exist."); + PackOutput packOutput = gen.getPackOutput("assets/" + outputTexture.getNamespace()); Path outputFile = packOutput.getOutputFolder().resolve(outputTexture.getPath()); diff --git a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java deleted file mode 100644 index e6cc11c9..00000000 --- a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java +++ /dev/null @@ -1,434 +0,0 @@ -package codechicken.lib.datagen; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.neoforged.neoforge.client.model.generators.ItemModelBuilder; -import net.neoforged.neoforge.client.model.generators.ModelFile; -import net.neoforged.neoforge.client.model.generators.ModelProvider; -import net.neoforged.neoforge.common.data.ExistingFileHelper; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.Nullable; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.util.*; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -import static codechicken.lib.CodeChickenLib.MOD_ID; -import static java.util.Objects.requireNonNull; - -/** - * Created by covers1624 on 15/10/20. - */ -public abstract class ItemModelProvider extends ModelProvider { - - private static final Logger LOGGER = LogManager.getLogger(); - - protected static final ModelFile.UncheckedModelFile GENERATED = new ModelFile.UncheckedModelFile("item/generated"); - protected static final ModelFile.UncheckedModelFile HANDHELD = new ModelFile.UncheckedModelFile("item/handheld"); - - public ItemModelProvider(PackOutput output, String modid, ExistingFileHelper existingFileHelper) { - super(output, modid, ITEM_FOLDER, WrappedItemModelBuilder::new, existingFileHelper); - } - - //region Location helpers - protected String name(ItemLike item) { - return BuiltInRegistries.ITEM.getKey(item.asItem()).getPath(); - } - - protected ResourceLocation itemTexture(ItemLike item) { - return itemTexture(item, ""); - } - - protected ResourceLocation itemTexture(Supplier item) { - return itemTexture(item, ""); - } - - protected ResourceLocation itemTexture(ItemLike item, String folder) { - String f = ""; - if (!StringUtils.isEmpty(folder)) { - f = StringUtils.appendIfMissing(folder, "/"); - } - return modLoc("item/" + f + name(item)); - } - - protected ResourceLocation itemTexture(Supplier item, String folder) { - return itemTexture(item.get(), folder); - } - - protected ResourceLocation blockTexture(Block block) { - return blockTexture(block, ""); - } - - protected ResourceLocation blockTexture(Supplier block) { - return blockTexture(block, ""); - } - - protected ResourceLocation blockTexture(Block block, String folder) { - String f = ""; - if (!StringUtils.isEmpty(folder)) { - f = StringUtils.appendIfMissing(folder, "/"); - } - return modLoc("block/" + f + name(block)); - } - - protected ResourceLocation blockTexture(Supplier block, String folder) { - return blockTexture(block.get(), folder); - } - //endregion - - //region Builder helpers. - protected ItemModelBuilder getBuilder(ItemLike item) { - return getBuilder(name(item)); - } - - protected ItemModelBuilder getBuilder(Supplier item) { - return getBuilder(name(item.get())); - } - //endregion - - //region Simple builder - protected SimpleItemModelBuilder getSimple(ItemLike item) { - WrappedItemModelBuilder builder = (WrappedItemModelBuilder) getBuilder(item); - if (builder.simpleBuilder == null) { - builder.simpleBuilder = new SimpleItemModelBuilder(this, builder, item.asItem()); - } - return builder.simpleBuilder; - } - - protected SimpleItemModelBuilder getSimple(ItemLike item, String name) { - WrappedItemModelBuilder builder = (WrappedItemModelBuilder) getBuilder(name); - if (builder.simpleBuilder == null) { - builder.simpleBuilder = new SimpleItemModelBuilder(this, builder, item.asItem()); - } - return builder.simpleBuilder; - } - - protected SimpleItemModelBuilder getSimple(Supplier item) { - return getSimple(item.get()); - } - - protected SimpleItemModelBuilder generated(ItemLike item) { - return getSimple(item) - .parent(GENERATED); - } - - protected SimpleItemModelBuilder generated(Supplier item) { - return generated(item.get()); - } - - protected SimpleItemModelBuilder handheld(ItemLike item) { - return getSimple(item) - .parent(HANDHELD); - } - - protected SimpleItemModelBuilder handheld(Supplier item) { - return handheld(item.get()); - } - - protected void simpleItemBlock(Block block) { - getSimple(block) - .parent(new ModelFile.UncheckedModelFile(modLoc("block/" + name(block)))) - .noTexture(); - } - - protected SimpleItemModelBuilder clazz(Supplier item, Class clazz) { - return clazz(item.get(), clazz); - } - - protected SimpleItemModelBuilder clazz(ItemLike item, Class clazz) { - return generated(item) - .noTexture() - .customLoader(ClassCustomLoaderBuilder::new) - .clazz(clazz) - .end(); - } - //endregion - - private SimpleItemModelBuilder makeNested(ItemLike item) { - WrappedItemModelBuilder builder = (WrappedItemModelBuilder) nested(); - builder.simpleBuilder = new SimpleItemModelBuilder(this, builder, item.asItem()); - return builder.simpleBuilder; - } - - private ExistingFileHelper getExistingFileHelper() { - return existingFileHelper; - } - - @Override - public String getName() { - return modid + " Item models."; - } - - public static class SimpleItemModelBuilder { - - private final ItemModelProvider provider; - private final ItemModelBuilder builder; - private final Item item; - private final Map layers = new HashMap<>(); - private @Nullable ModelFile parent; - private boolean noTexture = false; - private String folder = ""; - - @Nullable - private CustomLoaderBuilder loader; - - private boolean built = false; - - private SimpleItemModelBuilder(ItemModelProvider provider, ItemModelBuilder builder, Item item) { - this.provider = provider; - this.builder = builder; - this.item = item; - } - - public SimpleItemModelBuilder parent(ModelFile parent) { - this.parent = requireNonNull(parent); - return this; - } - - public SimpleItemModelBuilder texture(@Nullable ResourceLocation texture) { - if (texture == null) throw new IllegalStateException("Use '.noTexture()' instead of '.texture(null)'"); - return texture("layer0", texture); - } - - public SimpleItemModelBuilder texture(String layer, ResourceLocation texture) { - if (noTexture) throw new IllegalStateException("Unable to set texture. NoTexture set."); - if (!StringUtils.isEmpty(folder)) throw new IllegalArgumentException("Adding texture would ignore existing folder."); - - ResourceLocation existing = layers.put(layer, requireNonNull(texture)); - if (existing != null) { - LOGGER.warn("Overwriting layer '{}' texture '{}' with '{}'", layer, existing, texture); - } - return this; - } - - public SimpleItemModelBuilder folder(String folder) { - if (!layers.isEmpty()) throw new IllegalStateException("Textures set, folder would be ignored."); - if (noTexture) throw new IllegalStateException("No Texture set, folder would be ignored."); - - this.folder = requireNonNull(folder); - return this; - } - - public SimpleItemModelBuilder noTexture() { - if (!layers.isEmpty()) throw new IllegalStateException("Setting No Texture would ignore textures."); - if (!StringUtils.isEmpty(folder)) throw new IllegalArgumentException("Setting No Texture would ignore existing folder."); - this.noTexture = true; - return this; - } - - public SimpleItemModelBuilder override(Consumer cons) { - ItemModelBuilder.OverrideBuilder forgeBuilder = builder.override(); - OverrideBuilder builder = new OverrideBuilder(this, forgeBuilder); - cons.accept(builder); - return this; - } - - public L customLoader(Function factory) { - if (loader != null) throw new IllegalStateException("Loader already set!"); - - L loader = factory.apply(this); - this.loader = loader; - return loader; - } - - public ModelFile getModel() { - return builder; - } - - private void build() { - if (!built) { - builder.parent(requireNonNull(parent, "Model requires a parent.")); - if (!noTexture) { - if (layers.isEmpty()) { - builder.texture("layer0", provider.itemTexture(item, folder)); - } else { - layers.forEach(builder::texture); - } - } - if (loader != null) { - loader.build(builder); - } - built = true; - } - } - } - - private static class WrappedItemModelBuilder extends ItemModelBuilder { - - private @Nullable SimpleItemModelBuilder simpleBuilder; - - public WrappedItemModelBuilder(ResourceLocation outputLocation, ExistingFileHelper existingFileHelper) { - super(outputLocation, existingFileHelper); - } - - @Override - public JsonObject toJson() { - if (simpleBuilder != null) { - simpleBuilder.build(); - if (simpleBuilder.loader != null) { - return simpleBuilder.loader.toJson(super.toJson()); - } - } - return super.toJson(); - } - } - - public static class OverrideBuilder { - - private final SimpleItemModelBuilder parent; - private final ItemModelBuilder.OverrideBuilder forgeBuilder; - - public OverrideBuilder(SimpleItemModelBuilder parent, ItemModelBuilder.OverrideBuilder forgeBuilder) { - this.parent = parent; - this.forgeBuilder = forgeBuilder; - } - - public OverrideBuilder model(String name, Consumer cons) { - SimpleItemModelBuilder model = parent.provider.getSimple(parent.item, name); - forgeBuilder.model(model.getModel()); - cons.accept(model); - return this; - } - - public OverrideBuilder predicate(ResourceLocation key, float value) { - forgeBuilder.predicate(key, value); - return this; - } - } - - public static class CustomLoaderBuilder { - - protected final ResourceLocation loaderId; - protected final SimpleItemModelBuilder parent; - protected final ExistingFileHelper existingFileHelper; - protected final Map visibility = new LinkedHashMap<>(); - - protected CustomLoaderBuilder(ResourceLocation loaderId, SimpleItemModelBuilder parent) { - this.loaderId = loaderId; - this.parent = parent; - existingFileHelper = parent.provider.getExistingFileHelper(); - } - - public CustomLoaderBuilder visibility(String partName, boolean show) { - this.visibility.put(partName, show); - return this; - } - - public SimpleItemModelBuilder end() { - return parent; - } - - protected void build(ItemModelBuilder builder) { - } - - protected JsonObject toJson(JsonObject json) { - json.addProperty("loader", loaderId.toString()); - - if (!visibility.isEmpty()) { - JsonObject visibilityObj = new JsonObject(); - - for (Map.Entry entry : visibility.entrySet()) { - visibilityObj.addProperty(entry.getKey(), entry.getValue()); - } - json.add("visibility", visibilityObj); - } - - return json; - } - } - - public static class ClassCustomLoaderBuilder extends CustomLoaderBuilder { - - private @Nullable Class clazz; - - protected ClassCustomLoaderBuilder(SimpleItemModelBuilder parent) { - super(ResourceLocation.fromNamespaceAndPath(MOD_ID, "class"), parent); - } - - public ClassCustomLoaderBuilder clazz(Class clazz) { - try { - Constructor ctor = clazz.getConstructor(); - if (!Modifier.isPublic(ctor.getModifiers())) { - throw new IllegalArgumentException("Expected single no-args public constructor."); - } - } catch (NoSuchMethodException ex) { - throw new IllegalStateException("Expected single no-args public constructor.", ex); - } - this.clazz = clazz; - return this; - } - - @Override - protected JsonObject toJson(JsonObject json) { - super.toJson(json); - json.addProperty("class", requireNonNull(clazz).getName()); - return json; - } - } - - public static class CompositeLoaderBuilder extends CustomLoaderBuilder { - - private final Map children = new LinkedHashMap<>(); - private final List order = new ArrayList<>(); - - protected CompositeLoaderBuilder(ResourceLocation loader, SimpleItemModelBuilder parent) { - super(loader, parent); - } - - public static CompositeLoaderBuilder forge(SimpleItemModelBuilder parent) { - return new CompositeLoaderBuilder(ResourceLocation.fromNamespaceAndPath("forge", "composite"), parent); - } - - public static CompositeLoaderBuilder ccl(SimpleItemModelBuilder parent) { - return new CompositeLoaderBuilder(ResourceLocation.fromNamespaceAndPath(MOD_ID, "item_composite"), parent); - } - - public CompositeLoaderBuilder nested(String name, Consumer cons) { - if (children.containsKey(name)) throw new IllegalArgumentException("Child with name " + name + " is already registered."); - - SimpleItemModelBuilder nested = parent.provider.makeNested(parent.item); - cons.accept(nested); - children.put(name, nested); - order.add(name); - return this; - } - - public CompositeLoaderBuilder order(String... names) { - for (String name : names) { - if (!children.containsKey(name)) { - throw new IllegalArgumentException("Child with name " + name + " does not exist."); - } - } - order.clear(); - Collections.addAll(order, names); - return this; - } - - @Override - protected JsonObject toJson(JsonObject json) { - super.toJson(json); - - JsonObject children = new JsonObject(); - this.children.forEach((name, child) -> children.add(name, child.builder.toJson())); - json.add("children", children); - - JsonArray order = new JsonArray(); - this.order.forEach(order::add); - json.add("item_render_order", order); - - return json; - } - } -} diff --git a/src/main/java/codechicken/lib/datagen/LanguageProvider.java b/src/main/java/codechicken/lib/datagen/LanguageProvider.java index 150c6d0b..7cb2855a 100644 --- a/src/main/java/codechicken/lib/datagen/LanguageProvider.java +++ b/src/main/java/codechicken/lib/datagen/LanguageProvider.java @@ -9,10 +9,8 @@ import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.neoforged.neoforge.data.event.GatherDataEvent; import java.nio.file.Path; import java.util.LinkedList; @@ -33,26 +31,24 @@ public abstract class LanguageProvider implements DataProvider { private final PackOutput output; private final String modid; private final String locale; - private final Side distFilter; - protected LanguageProvider(PackOutput output, String modid, String locale, Side distFilter) { + protected LanguageProvider(PackOutput output, String modid, String locale) { this.output = output; this.modid = modid; this.locale = locale; - this.distFilter = distFilter; } protected abstract void addTranslations(); @Override - public CompletableFuture run(CachedOutput p_200398_1_) { + public CompletableFuture run(CachedOutput output) { addTranslations(); List> futures = new LinkedList<>(); - if (distFilter.includeClient() && !client.isEmpty()) { - futures.add(DataProvider.saveStable(p_200398_1_, GSON.toJsonTree(client), output.getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(modid + "/lang/" + locale + ".json"))); + if (!client.isEmpty()) { + futures.add(DataProvider.saveStable(output, GSON.toJsonTree(client), this.output.getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(modid + "/lang/" + locale + ".json"))); } - if (distFilter.includeServer() && !server.isEmpty()) { - futures.add(DataProvider.saveStable(p_200398_1_, GSON.toJsonTree(server), output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve(modid + "/lang/" + locale + ".json"))); + if (!server.isEmpty()) { + futures.add(DataProvider.saveStable(output, GSON.toJsonTree(server), this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve(modid + "/lang/" + locale + ".json"))); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } @@ -74,12 +70,12 @@ private void save(CachedOutput cache, Object object, Path target) { public void add(Block key, String name) { add(key.getDescriptionId(), name); } public void add(Item key, String name) { add(key.getDescriptionId(), name); } public void add(Supplier key, String name) { add(key.get().asItem(), name); } - public void add(ItemStack key, String name) { add(key.getDescriptionId(), name); } + public void add(ItemStack key, String name) { add(key.getItem(), name); } public void add(MobEffect key, String name) { add(key.getDescriptionId(), name); } public void add(EntityType key, String name) { add(key.getDescriptionId(), name); } public void addBlock(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addItem(Supplier key, String name) { add(key.get().getDescriptionId(), name); } - public void addItemStack(Supplier key, String name) { add(key.get().getDescriptionId(), name); } + public void addItemStack(Supplier key, String name) { add(key.get(), name); } public void addEffect(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addEntityType(Supplier> key, String name) { add(key.get().getDescriptionId(), name); } //@formatter:on @@ -96,26 +92,4 @@ public void addServer(String key, String name) { throw new IllegalArgumentException("Duplicate translation key :" + key); } } - - public static Side getDist(GatherDataEvent event) { - if (event.includeServer() && event.includeClient()) return Side.BOTH; - if (event.includeServer()) return Side.SERVER; - if (event.includeClient()) return Side.CLIENT; - return Side.NONE; - } - - public enum Side { - CLIENT, - SERVER, - BOTH, - NONE; - - public boolean includeClient() { - return this == CLIENT || this == BOTH; - } - - public boolean includeServer() { - return this == SERVER || this == BOTH; - } - } } diff --git a/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java index cbbf2702..dc0e7d02 100644 --- a/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java +++ b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java @@ -1,10 +1,8 @@ package codechicken.lib.datagen; import net.minecraft.core.HolderLookup; -import net.minecraft.core.RegistryAccess; import net.minecraft.data.loot.BlockLootSubProvider; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.item.Item; import net.minecraft.world.level.storage.loot.LootTable; diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java index d9cbf8cb..fffb276e 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java @@ -1,6 +1,8 @@ package codechicken.lib.datagen.recipe; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.HolderGetter; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; @@ -9,8 +11,8 @@ */ public abstract class AbstractItemStackRecipeBuilder> extends AbstractRecipeBuilder { - protected AbstractItemStackRecipeBuilder(ResourceLocation id, ItemStack result) { - super(id, result); + protected AbstractItemStackRecipeBuilder(Identifier id, HolderGetter items, ItemStack result) { + super(id, items, result); } @Override diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java index 4e871954..50f9a4b4 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java @@ -1,10 +1,15 @@ package codechicken.lib.datagen.recipe; import net.minecraft.advancements.*; -import net.minecraft.advancements.critereon.InventoryChangeTrigger; -import net.minecraft.advancements.critereon.ItemPredicate; -import net.minecraft.advancements.critereon.RecipeUnlockedTrigger; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.advancements.criterion.InventoryChangeTrigger; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.advancements.criterion.RecipeUnlockedTrigger; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.crafting.Recipe; @@ -23,7 +28,9 @@ public abstract class AbstractRecipeBuilder conditions = new LinkedList<>(); - protected final ResourceLocation id; + protected final Identifier id; + protected final ResourceKey> key; + protected final HolderGetter items; protected final R result; private final Set criteriaItems = new HashSet<>(); private final Set> criteriaTags = new HashSet<>(); @@ -32,8 +39,10 @@ public abstract class AbstractRecipeBuilder items, R result) { this.id = id; + key = ResourceKey.create(Registries.RECIPE, id); + this.items = items; this.result = result; } @@ -71,17 +80,22 @@ public T addCriterion(String name, Criterion criterion) { } @Override - public final ResourceLocation getId() { + public final Identifier getId() { return id; } + @Override + public final ResourceKey> getKey() { + return key; + } + @Override public final BuiltRecipe build() { validate(); if (enableUnlocking) { - advancementBuilder.parent(ResourceLocation.withDefaultNamespace("recipes/root")) - .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(id)) - .rewards(AdvancementRewards.Builder.recipe(id)) + advancementBuilder.parent(Identifier.withDefaultNamespace("recipes/root")) + .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(getKey())) + .rewards(AdvancementRewards.Builder.recipe(getKey())) .requirements(AdvancementRequirements.Strategy.OR); } AdvancementHolder advancement = advancementBuilder.build(id.withPrefix("recipes")); @@ -109,11 +123,11 @@ protected void addAutoCriteria(TagKey tag) { } protected Criterion hasItem(ItemLike itemIn) { - return this.hasItem(ItemPredicate.Builder.item().of(itemIn).build()); + return this.hasItem(ItemPredicate.Builder.item().of(items, itemIn).build()); } protected Criterion hasItem(TagKey tagIn) { - return this.hasItem(ItemPredicate.Builder.item().of(tagIn).build()); + return this.hasItem(ItemPredicate.Builder.item().of(items, tagIn).build()); } protected Criterion hasItem(ItemPredicate... predicates) { diff --git a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java index b6f887be..9860554a 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java @@ -1,7 +1,8 @@ package codechicken.lib.datagen.recipe; +import net.minecraft.core.HolderGetter; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -29,182 +30,182 @@ public class FurnaceRecipeBuilder extends AbstractItemStackRecipeBuilder items, ItemStack result, Factory factory) { + super(id, items, result); this.factory = factory; } //region Smelting - public static FurnaceRecipeBuilder smelting(ItemLike result) { - return smelting(result, 1); + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemLike result) { + return smelting(items, result, 1); } - public static FurnaceRecipeBuilder smelting(ItemLike result, int count) { - return smelting(new ItemStack(result, count)); + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemLike result, int count) { + return smelting(items, new ItemStack(result, count)); } - public static FurnaceRecipeBuilder smelting(ItemLike result, int count, ResourceLocation id) { - return smelting(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemLike result, int count, Identifier id) { + return smelting(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder smelting(Supplier result) { - return smelting(result.get(), 1); + public static FurnaceRecipeBuilder smelting(HolderGetter items, Supplier result) { + return smelting(items, result.get(), 1); } - public static FurnaceRecipeBuilder smelting(Supplier result, int count) { - return smelting(new ItemStack(result.get(), count)); + public static FurnaceRecipeBuilder smelting(HolderGetter items, Supplier result, int count) { + return smelting(items, new ItemStack(result.get(), count)); } - public static FurnaceRecipeBuilder smelting(Supplier result, int count, ResourceLocation id) { - return smelting(new ItemStack(result.get(), count), id); + public static FurnaceRecipeBuilder smelting(HolderGetter items, Supplier result, int count, Identifier id) { + return smelting(items, new ItemStack(result.get(), count), id); } - public static FurnaceRecipeBuilder smelting(ItemStack result) { - return smelting(result, BuiltInRegistries.ITEM.getKey(result.getItem())); + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemStack result) { + return smelting(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); } - public static FurnaceRecipeBuilder smelting(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(id, result, SmeltingRecipe::new) + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, SmeltingRecipe::new) .cookingTime(200); } //endregion //region Blasting - public static FurnaceRecipeBuilder blasting(ItemLike result) { - return blasting(result, 1); + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemLike result) { + return blasting(items, result, 1); } - public static FurnaceRecipeBuilder blasting(ItemLike result, int count) { - return blasting(new ItemStack(result, count)); + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemLike result, int count) { + return blasting(items, new ItemStack(result, count)); } - public static FurnaceRecipeBuilder blasting(ItemLike result, int count, ResourceLocation id) { - return blasting(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemLike result, int count, Identifier id) { + return blasting(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder blasting(Supplier result) { - return blasting(result.get(), 1); + public static FurnaceRecipeBuilder blasting(HolderGetter items, Supplier result) { + return blasting(items, result.get(), 1); } - public static FurnaceRecipeBuilder blasting(Supplier result, int count) { - return blasting(new ItemStack(result.get(), count)); + public static FurnaceRecipeBuilder blasting(HolderGetter items, Supplier result, int count) { + return blasting(items, new ItemStack(result.get(), count)); } - public static FurnaceRecipeBuilder blasting(Supplier result, int count, ResourceLocation id) { - return blasting(new ItemStack(result.get(), count), id); + public static FurnaceRecipeBuilder blasting(HolderGetter items, Supplier result, int count, Identifier id) { + return blasting(items, new ItemStack(result.get(), count), id); } - public static FurnaceRecipeBuilder blasting(ItemStack result) { - return blasting(result, BuiltInRegistries.ITEM.getKey(result.getItem())); + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemStack result) { + return blasting(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); } - public static FurnaceRecipeBuilder blasting(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(id, result, BlastingRecipe::new) + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, BlastingRecipe::new) .cookingTime(100); } //endregion //region Smoking - public static FurnaceRecipeBuilder smoking(ItemLike result) { - return smoking(result, 1); + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemLike result) { + return smoking(items, result, 1); } - public static FurnaceRecipeBuilder smoking(ItemLike result, int count) { - return smoking(new ItemStack(result, count)); + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemLike result, int count) { + return smoking(items, new ItemStack(result, count)); } - public static FurnaceRecipeBuilder smoking(ItemLike result, int count, ResourceLocation id) { - return smoking(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemLike result, int count, Identifier id) { + return smoking(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder smoking(Supplier result) { - return smoking(result.get(), 1); + public static FurnaceRecipeBuilder smoking(HolderGetter items, Supplier result) { + return smoking(items, result.get(), 1); } - public static FurnaceRecipeBuilder smoking(Supplier result, int count) { - return smoking(new ItemStack(result.get(), count)); + public static FurnaceRecipeBuilder smoking(HolderGetter items, Supplier result, int count) { + return smoking(items, new ItemStack(result.get(), count)); } - public static FurnaceRecipeBuilder smoking(Supplier result, int count, ResourceLocation id) { - return smoking(new ItemStack(result.get(), count), id); + public static FurnaceRecipeBuilder smoking(HolderGetter items, Supplier result, int count, Identifier id) { + return smoking(items, new ItemStack(result.get(), count), id); } - public static FurnaceRecipeBuilder smoking(ItemStack result) { - return smoking(result, BuiltInRegistries.ITEM.getKey(result.getItem())); + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemStack result) { + return smoking(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); } - public static FurnaceRecipeBuilder smoking(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(id, result, SmokingRecipe::new) + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, SmokingRecipe::new) .cookingTime(100); } //endregion //region Campfire - public static FurnaceRecipeBuilder campfire(ItemLike result) { - return campfire(result, 1); + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemLike result) { + return campfire(items, result, 1); } - public static FurnaceRecipeBuilder campfire(ItemLike result, int count) { - return campfire(new ItemStack(result, count)); + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemLike result, int count) { + return campfire(items, new ItemStack(result, count)); } - public static FurnaceRecipeBuilder campfire(ItemLike result, int count, ResourceLocation id) { - return campfire(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemLike result, int count, Identifier id) { + return campfire(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder campfire(Supplier result) { - return campfire(result.get(), 1); + public static FurnaceRecipeBuilder campfire(HolderGetter items, Supplier result) { + return campfire(items, result.get(), 1); } - public static FurnaceRecipeBuilder campfire(Supplier result, int count) { - return campfire(new ItemStack(result.get(), count)); + public static FurnaceRecipeBuilder campfire(HolderGetter items, Supplier result, int count) { + return campfire(items, new ItemStack(result.get(), count)); } - public static FurnaceRecipeBuilder campfire(Supplier result, int count, ResourceLocation id) { - return campfire(new ItemStack(result.get(), count), id); + public static FurnaceRecipeBuilder campfire(HolderGetter items, Supplier result, int count, Identifier id) { + return campfire(items, new ItemStack(result.get(), count), id); } - public static FurnaceRecipeBuilder campfire(ItemStack result) { - return campfire(result, BuiltInRegistries.ITEM.getKey(result.getItem())); + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemStack result) { + return campfire(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); } - public static FurnaceRecipeBuilder campfire(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(id, result, CampfireCookingRecipe::new) + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, CampfireCookingRecipe::new) .cookingTime(600); } //endregion //region Custom - public static FurnaceRecipeBuilder custom(ItemLike result, Factory factory) { - return custom(result, 1, factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemLike result, Factory factory) { + return custom(items, result, 1, factory); } - public static FurnaceRecipeBuilder custom(ItemLike result, int count, Factory factory) { - return custom(new ItemStack(result, count), factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Factory factory) { + return custom(items, new ItemStack(result, count), factory); } - public static FurnaceRecipeBuilder custom(ItemLike result, int count, ResourceLocation id, Factory factory) { - return custom(new ItemStack(result, count), id, factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result, count), id, factory); } - public static FurnaceRecipeBuilder custom(Supplier result, Factory factory) { - return custom(result.get(), 1, factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, Supplier result, Factory factory) { + return custom(items, result.get(), 1, factory); } - public static FurnaceRecipeBuilder custom(Supplier result, int count, Factory factory) { - return custom(new ItemStack(result.get(), count), factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, Supplier result, int count, Factory factory) { + return custom(items, new ItemStack(result.get(), count), factory); } - public static FurnaceRecipeBuilder custom(Supplier result, int count, ResourceLocation id, Factory factory) { - return custom(new ItemStack(result.get(), count), id, factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, Supplier result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result.get(), count), id, factory); } - public static FurnaceRecipeBuilder custom(ItemStack result, Factory factory) { - return custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemStack result, Factory factory) { + return custom(items, result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static FurnaceRecipeBuilder custom(ItemStack result, ResourceLocation id, Factory factory) { - return new FurnaceRecipeBuilder(id, result, factory); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemStack result, Identifier id, Factory factory) { + return new FurnaceRecipeBuilder(id, items, result, factory); } //endregion @@ -215,7 +216,7 @@ public FurnaceRecipeBuilder category(CookingBookCategory category) { public FurnaceRecipeBuilder ingredient(TagKey tag) { addAutoCriteria(tag); - this.ingredient = Ingredient.of(tag); + this.ingredient = Ingredient.of(items.getOrThrow(tag)); return this; } diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java index e2a9594c..d82b5884 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java @@ -2,7 +2,8 @@ import net.minecraft.advancements.AdvancementHolder; import net.minecraft.data.recipes.RecipeOutput; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.item.crafting.Recipe; import net.neoforged.neoforge.common.conditions.ICondition; import org.jetbrains.annotations.Nullable; @@ -14,14 +15,16 @@ */ public interface RecipeBuilder { - ResourceLocation getId(); + Identifier getId(); + + ResourceKey> getKey(); BuiltRecipe build(); // Compat with vanilla's Recipe Provider. default void build(RecipeOutput output) { BuiltRecipe built = build(); - output.accept(getId(), built.recipe, built.advancement, built.conditions.toArray(ICondition[]::new)); + output.accept(getKey(), built.recipe, built.advancement, built.conditions.toArray(ICondition[]::new)); } record BuiltRecipe( diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java index 71e93471..835177e8 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java @@ -4,16 +4,17 @@ import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.advancements.Criterion; -import net.minecraft.advancements.critereon.EnterBlockTrigger; -import net.minecraft.advancements.critereon.InventoryChangeTrigger; -import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.advancements.criterion.EnterBlockTrigger; +import net.minecraft.advancements.criterion.InventoryChangeTrigger; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.core.HolderGetter; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.data.CachedOutput; import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -21,6 +22,7 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.neoforged.neoforge.common.conditions.WithConditions; +import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.CompletableFuture; @@ -31,13 +33,15 @@ */ public abstract class RecipeProvider implements DataProvider { - private final Map recipes = new HashMap<>(); + private final Map recipes = new HashMap<>(); private final CompletableFuture registries; private final PackOutput.PathProvider recipePath; private final PackOutput.PathProvider advancementPath; protected final String modId; - public RecipeProvider(CompletableFuture registries, PackOutput output, String modId) { + private @Nullable HolderGetter items; + + public RecipeProvider(PackOutput output, CompletableFuture registries, String modId) { this.registries = registries; this.modId = modId; recipePath = output.createRegistryElementsPathProvider(Registries.RECIPE); @@ -49,11 +53,11 @@ public final CompletableFuture run(CachedOutput cache) { return registries.thenCompose(registries -> run(cache, registries)); } - private final CompletableFuture run(CachedOutput cache, HolderLookup.Provider registries) { + private CompletableFuture run(CachedOutput cache, HolderLookup.Provider registries) { registerRecipes(); List> futures = new LinkedList<>(); - for (Map.Entry entry : recipes.entrySet()) { - ResourceLocation id = entry.getKey(); + for (Map.Entry entry : recipes.entrySet()) { + Identifier id = entry.getKey(); RecipeBuilder.BuiltRecipe builtRecipe = entry.getValue().build(); futures.add(DataProvider.saveStable( cache, @@ -87,93 +91,102 @@ protected T builder(T builder) { return builder; } + protected HolderGetter items() { + if (items == null) { + if (!registries.isDone()) throw new RuntimeException("Only available inside registerRecipes() callback."); + + items = registries.join().lookupOrThrow(Registries.ITEM); + } + return items; + } + //@formatter:off - protected ShapedRecipeBuilder shapedRecipe(ItemLike result) { return builder(ShapedRecipeBuilder.builder(result, 1)); } - protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result, count))); } - protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result, count), id)); } - protected ShapedRecipeBuilder shapedRecipe(Supplier result) { return builder(ShapedRecipeBuilder.builder(result.get(), 1)); } - protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result.get(), count))); } - protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result.get(), count), id)); } - protected ShapedRecipeBuilder shapedRecipe(ItemStack result) { return builder(ShapedRecipeBuilder.builder(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } - protected ShapedRecipeBuilder shapedRecipe(ItemStack result, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(result, id)); } - - protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result) { return builder(ShapelessRecipeBuilder.builder(result, 1)); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result, count))); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result, count), id)); } - protected ShapelessRecipeBuilder shapelessRecipe(Supplier result) { return builder(ShapelessRecipeBuilder.builder(result.get(), 1)); } - protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result.get(), count))); } - protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result.get(), count), id)); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result) { return builder(ShapelessRecipeBuilder.builder(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(result, id)); } - - protected FurnaceRecipeBuilder smelting(ItemLike result) { return builder(FurnaceRecipeBuilder.smelting(result, 1)); } - protected FurnaceRecipeBuilder smelting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder smelting(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder smelting(Supplier result) { return builder(FurnaceRecipeBuilder.smelting(result.get(), 1)); } - protected FurnaceRecipeBuilder smelting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result.get(), count))); } - protected FurnaceRecipeBuilder smelting(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder smelting(ItemStack result) { return builder(FurnaceRecipeBuilder.smelting(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder smelting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(result, id)); } - - protected FurnaceRecipeBuilder blasting(ItemLike result) { return builder(FurnaceRecipeBuilder.blasting(result, 1)); } - protected FurnaceRecipeBuilder blasting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder blasting(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder blasting(Supplier result) { return builder(FurnaceRecipeBuilder.blasting(result.get(), 1)); } - protected FurnaceRecipeBuilder blasting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result.get(), count))); } - protected FurnaceRecipeBuilder blasting(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder blasting(ItemStack result) { return builder(FurnaceRecipeBuilder.blasting(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder blasting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(result, id)); } - - protected FurnaceRecipeBuilder smoking(ItemLike result) { return builder(FurnaceRecipeBuilder.smoking(result, 1)); } - protected FurnaceRecipeBuilder smoking(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder smoking(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder smoking(Supplier result) { return builder(FurnaceRecipeBuilder.smoking(result.get(), 1)); } - protected FurnaceRecipeBuilder smoking(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result.get(), count))); } - protected FurnaceRecipeBuilder smoking(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder smoking(ItemStack result) { return builder(FurnaceRecipeBuilder.smoking(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder smoking(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(result, id)); } - - protected FurnaceRecipeBuilder campfire(ItemLike result) { return builder(FurnaceRecipeBuilder.campfire(result, 1)); } - protected FurnaceRecipeBuilder campfire(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder campfire(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder campfire(Supplier result) { return builder(FurnaceRecipeBuilder.campfire(result.get(), 1)); } - protected FurnaceRecipeBuilder campfire(Supplier result, int count) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result.get(), count))); } - protected FurnaceRecipeBuilder campfire(Supplier result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result.get(), count), id)); } - protected FurnaceRecipeBuilder campfire(ItemStack result) { return builder(FurnaceRecipeBuilder.campfire(result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder campfire(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(result, id)); } - - protected ShapedRecipeBuilder customShaped(ItemLike result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result, 1, factory)); } - protected ShapedRecipeBuilder customShaped(ItemLike result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result, count), factory)); } - protected ShapedRecipeBuilder customShaped(ItemLike result, int count, ResourceLocation id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result, count), id, factory)); } - protected ShapedRecipeBuilder customShaped(Supplier result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result.get(), 1, factory)); } - protected ShapedRecipeBuilder customShaped(Supplier result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result.get(), count), factory)); } - protected ShapedRecipeBuilder customShaped(Supplier result, int count, ResourceLocation id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(new ItemStack(result.get(), count), id, factory)); } - protected ShapedRecipeBuilder customShaped(ItemStack result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } - protected ShapedRecipeBuilder customShaped(ItemStack result, ResourceLocation id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(result, id, factory)); } - - protected ShapelessRecipeBuilder customShapeless(ItemLike result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result, 1, factory)); } - protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result, count), factory)); } - protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, ResourceLocation id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result, count), id, factory)); } - protected ShapelessRecipeBuilder customShapeless(Supplier result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result.get(), 1, factory)); } - protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result.get(), count), factory)); } - protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, ResourceLocation id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(new ItemStack(result.get(), count), id, factory)); } - protected ShapelessRecipeBuilder customShapeless(ItemStack result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } - protected ShapelessRecipeBuilder customShapeless(ItemStack result, ResourceLocation id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(result, id, factory)); } - - protected FurnaceRecipeBuilder customFurnace(ItemLike result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result, 1, factory)); } - protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result, count), factory)); } - protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, ResourceLocation id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result, count), id, factory)); } - protected FurnaceRecipeBuilder customFurnace(Supplier result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result.get(), 1, factory)); } - protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result.get(), count), factory)); } - protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, ResourceLocation id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(new ItemStack(result.get(), count), id, factory)); } - protected FurnaceRecipeBuilder customFurnace(ItemStack result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } - protected FurnaceRecipeBuilder customFurnace(ItemStack result, ResourceLocation id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(result, id, factory)); } + protected ShapedRecipeBuilder shapedRecipe(ItemLike result) { return builder(ShapedRecipeBuilder.builder(items(), result, 1)); } + protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result, count))); } + protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count, Identifier id) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result, count), id)); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result) { return builder(ShapedRecipeBuilder.builder(items(), result.get(), 1)); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result.get(), count))); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count, Identifier id) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result.get(), count), id)); } + protected ShapedRecipeBuilder shapedRecipe(ItemStack result) { return builder(ShapedRecipeBuilder.builder(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected ShapedRecipeBuilder shapedRecipe(ItemStack result, Identifier id) { return builder(ShapedRecipeBuilder.builder(items(), result, id)); } + + protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result) { return builder(ShapelessRecipeBuilder.builder(items(), result, 1)); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result, count))); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count, Identifier id) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result, count), id)); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result) { return builder(ShapelessRecipeBuilder.builder(items(), result.get(), 1)); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result.get(), count))); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count, Identifier id) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result.get(), count), id)); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result) { return builder(ShapelessRecipeBuilder.builder(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result, Identifier id) { return builder(ShapelessRecipeBuilder.builder(items(), result, id)); } + + protected FurnaceRecipeBuilder smelting(ItemLike result) { return builder(FurnaceRecipeBuilder.smelting(items(), result, 1)); } + protected FurnaceRecipeBuilder smelting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder smelting(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder smelting(Supplier result) { return builder(FurnaceRecipeBuilder.smelting(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder smelting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder smelting(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder smelting(ItemStack result) { return builder(FurnaceRecipeBuilder.smelting(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder smelting(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.smelting(items(), result, id)); } + + protected FurnaceRecipeBuilder blasting(ItemLike result) { return builder(FurnaceRecipeBuilder.blasting(items(), result, 1)); } + protected FurnaceRecipeBuilder blasting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder blasting(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder blasting(Supplier result) { return builder(FurnaceRecipeBuilder.blasting(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder blasting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder blasting(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder blasting(ItemStack result) { return builder(FurnaceRecipeBuilder.blasting(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder blasting(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.blasting(items(), result, id)); } + + protected FurnaceRecipeBuilder smoking(ItemLike result) { return builder(FurnaceRecipeBuilder.smoking(items(), result, 1)); } + protected FurnaceRecipeBuilder smoking(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder smoking(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder smoking(Supplier result) { return builder(FurnaceRecipeBuilder.smoking(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder smoking(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder smoking(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder smoking(ItemStack result) { return builder(FurnaceRecipeBuilder.smoking(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder smoking(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.smoking(items(), result, id)); } + + protected FurnaceRecipeBuilder campfire(ItemLike result) { return builder(FurnaceRecipeBuilder.campfire(items(), result, 1)); } + protected FurnaceRecipeBuilder campfire(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder campfire(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder campfire(Supplier result) { return builder(FurnaceRecipeBuilder.campfire(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder campfire(Supplier result, int count) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder campfire(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder campfire(ItemStack result) { return builder(FurnaceRecipeBuilder.campfire(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder campfire(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.campfire(items(), result, id)); } + + protected ShapedRecipeBuilder customShaped(ItemLike result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result, 1, factory)); } + protected ShapedRecipeBuilder customShaped(ItemLike result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result, count), factory)); } + protected ShapedRecipeBuilder customShaped(ItemLike result, int count, Identifier id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result, count), id, factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result.get(), 1, factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result.get(), count), factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, int count, Identifier id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result.get(), count), id, factory)); } + protected ShapedRecipeBuilder customShaped(ItemStack result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected ShapedRecipeBuilder customShaped(ItemStack result, Identifier id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result, id, factory)); } + + protected ShapelessRecipeBuilder customShapeless(ItemLike result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result, 1, factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result, count), factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, Identifier id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result, count), id, factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result.get(), 1, factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result.get(), count), factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, Identifier id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result.get(), count), id, factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemStack result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemStack result, Identifier id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result, id, factory)); } + + protected FurnaceRecipeBuilder customFurnace(ItemLike result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result, 1, factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result, count), factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, Identifier id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result, count), id, factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result.get(), 1, factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result.get(), count), factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, Identifier id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result.get(), count), id, factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemStack result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemStack result, Identifier id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result, id, factory)); } protected SpecialCraftingRecipeBuilder special(ItemLike id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } protected SpecialCraftingRecipeBuilder special(Supplier id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id.get(), factory)); } protected SpecialCraftingRecipeBuilder special(ItemStack id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } protected SpecialCraftingRecipeBuilder special(String id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } - protected SpecialCraftingRecipeBuilder special(ResourceLocation id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + protected SpecialCraftingRecipeBuilder special(Identifier id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } //@formatter:on protected Criterion enteredBlock(Block blockIn) { @@ -181,15 +194,15 @@ protected Criterion enteredBlock(Block blockIn) { } protected Criterion hasItem(ItemLike itemIn) { - return hasItem(ItemPredicate.Builder.item().of(itemIn).build()); + return hasItem(ItemPredicate.Builder.item().of(items(), itemIn).build()); } protected Criterion hasItem(Supplier itemIn) { - return hasItem(ItemPredicate.Builder.item().of(itemIn.get()).build()); + return hasItem(ItemPredicate.Builder.item().of(items(), itemIn.get()).build()); } - protected Criterion hasItem(TagKey tagIn) { - return hasItem(ItemPredicate.Builder.item().of(tagIn).build()); + protected Criterion hasItem(TagKey tag) { + return hasItem(ItemPredicate.Builder.item().of(items(), tag).build()); } protected Criterion hasItem(ItemPredicate... predicates) { diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java index 33a6ef37..b3b6e8f0 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java @@ -4,8 +4,9 @@ import it.unimi.dsi.fastutil.chars.Char2ObjectOpenHashMap; import it.unimi.dsi.fastutil.chars.CharOpenHashSet; import it.unimi.dsi.fastutil.chars.CharSet; +import net.minecraft.core.HolderGetter; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -32,68 +33,68 @@ public class ShapedRecipeBuilder extends AbstractItemStackRecipeBuilder items, ItemStack result, Factory factory) { + super(id, items, result); this.factory = factory; } - public static ShapedRecipeBuilder builder(ItemLike result) { - return builder(result, 1); + public static ShapedRecipeBuilder builder(HolderGetter items, ItemLike result) { + return builder(items, result, 1); } - public static ShapedRecipeBuilder builder(ItemLike result, int count) { - return builder(new ItemStack(result, count)); + public static ShapedRecipeBuilder builder(HolderGetter items, ItemLike result, int count) { + return builder(items, new ItemStack(result, count)); } - public static ShapedRecipeBuilder builder(ItemLike result, int count, ResourceLocation id) { - return builder(new ItemStack(result, count), id); + public static ShapedRecipeBuilder builder(HolderGetter items, ItemLike result, int count, Identifier id) { + return builder(items, new ItemStack(result, count), id); } - public static ShapedRecipeBuilder builder(Supplier result) { - return builder(result.get(), 1); + public static ShapedRecipeBuilder builder(HolderGetter items, Supplier result) { + return builder(items, result.get(), 1); } - public static ShapedRecipeBuilder builder(Supplier result, int count) { - return builder(new ItemStack(result.get(), count)); + public static ShapedRecipeBuilder builder(HolderGetter items, Supplier result, int count) { + return builder(items, new ItemStack(result.get(), count)); } - public static ShapedRecipeBuilder builder(Supplier result, int count, ResourceLocation id) { - return builder(new ItemStack(result.get(), count), id); + public static ShapedRecipeBuilder builder(HolderGetter items, Supplier result, int count, Identifier id) { + return builder(items, new ItemStack(result.get(), count), id); } - public static ShapedRecipeBuilder builder(ItemStack result) { - return builder(result, BuiltInRegistries.ITEM.getKey(result.getItem())); + public static ShapedRecipeBuilder builder(HolderGetter items, ItemStack result) { + return builder(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); } - public static ShapedRecipeBuilder builder(ItemStack result, ResourceLocation id) { - return new ShapedRecipeBuilder(id, result, ShapedRecipe::new); + public static ShapedRecipeBuilder builder(HolderGetter items, ItemStack result, Identifier id) { + return new ShapedRecipeBuilder(id, items, result, ShapedRecipe::new); } // region Custom - public static ShapedRecipeBuilder custom(ItemLike result, Factory factory) { - return custom(result, 1, factory); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemLike result, Factory factory) { + return custom(items, result, 1, factory); } - public static ShapedRecipeBuilder custom(ItemLike result, int count, Factory factory) { - return custom(new ItemStack(result, count), factory); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Factory factory) { + return custom(items, new ItemStack(result, count), factory); } - public static ShapedRecipeBuilder custom(ItemLike result, int count, ResourceLocation id, Factory factory) { - return custom(new ItemStack(result, count), id, factory); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result, count), id, factory); } - public static ShapedRecipeBuilder custom(ItemStack result, Factory factory) { - return custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemStack result, Factory factory) { + return custom(items, result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static ShapedRecipeBuilder custom(ItemStack result, ResourceLocation id, Factory factory) { - return new ShapedRecipeBuilder(id, result, factory); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemStack result, Identifier id, Factory factory) { + return new ShapedRecipeBuilder(id, items, result, factory); } // endregion public ShapedRecipeBuilder key(char key, TagKey item) { addAutoCriteria(item); - return keyInternal(key, Ingredient.of(item)); + return keyInternal(key, Ingredient.of(items.getOrThrow(item))); } public ShapedRecipeBuilder key(char key, ItemLike item) { diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java index 915a4a6e..e3372477 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java @@ -1,12 +1,16 @@ package codechicken.lib.datagen.recipe; +import net.minecraft.core.HolderGetter; import net.minecraft.core.NonNullList; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.*; +import net.minecraft.world.item.crafting.CraftingBookCategory; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.ShapelessRecipe; import net.minecraft.world.level.ItemLike; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -25,62 +29,62 @@ public class ShapelessRecipeBuilder extends AbstractItemStackRecipeBuilder items, ItemStack result, Factory factory) { + super(id, items, result); this.factory = factory; } - public static ShapelessRecipeBuilder builder(ItemLike result) { - return builder(result, 1); + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemLike result) { + return builder(items, result, 1); } - public static ShapelessRecipeBuilder builder(ItemLike result, int count) { - return builder(new ItemStack(result, count)); + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemLike result, int count) { + return builder(items, new ItemStack(result, count)); } - public static ShapelessRecipeBuilder builder(ItemLike result, int count, ResourceLocation id) { - return builder(new ItemStack(result, count), id); + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemLike result, int count, Identifier id) { + return builder(items, new ItemStack(result, count), id); } - public static ShapelessRecipeBuilder builder(Supplier result) { - return builder(result.get(), 1); + public static ShapelessRecipeBuilder builder(HolderGetter items, Supplier result) { + return builder(items, result.get(), 1); } - public static ShapelessRecipeBuilder builder(Supplier result, int count) { - return builder(new ItemStack(result.get(), count)); + public static ShapelessRecipeBuilder builder(HolderGetter items, Supplier result, int count) { + return builder(items, new ItemStack(result.get(), count)); } - public static ShapelessRecipeBuilder builder(Supplier result, int count, ResourceLocation id) { - return builder(new ItemStack(result.get(), count), id); + public static ShapelessRecipeBuilder builder(HolderGetter items, Supplier result, int count, Identifier id) { + return builder(items, new ItemStack(result.get(), count), id); } - public static ShapelessRecipeBuilder builder(ItemStack result) { - return builder(result, BuiltInRegistries.ITEM.getKey(result.getItem())); + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemStack result) { + return builder(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); } - public static ShapelessRecipeBuilder builder(ItemStack result, ResourceLocation id) { - return new ShapelessRecipeBuilder(id, result, ShapelessRecipe::new); + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemStack result, Identifier id) { + return new ShapelessRecipeBuilder(id, items, result, ShapelessRecipe::new); } // region Custom - public static ShapelessRecipeBuilder custom(ItemLike result, Factory factory) { - return custom(result, 1, factory); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemLike result, Factory factory) { + return custom(items, result, 1, factory); } - public static ShapelessRecipeBuilder custom(ItemLike result, int count, Factory factory) { - return custom(new ItemStack(result, count), factory); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Factory factory) { + return custom(items, new ItemStack(result, count), factory); } - public static ShapelessRecipeBuilder custom(ItemLike result, int count, ResourceLocation id, Factory factory) { - return custom(new ItemStack(result, count), id, factory); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result, count), id, factory); } - public static ShapelessRecipeBuilder custom(ItemStack result, Factory factory) { - return custom(result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemStack result, Factory factory) { + return custom(items, result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static ShapelessRecipeBuilder custom(ItemStack result, ResourceLocation id, Factory factory) { - return new ShapelessRecipeBuilder(id, result, factory); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemStack result, Identifier id, Factory factory) { + return new ShapelessRecipeBuilder(id, items, result, factory); } // endregion @@ -90,7 +94,7 @@ public ShapelessRecipeBuilder addIngredient(TagKey tag) { public ShapelessRecipeBuilder addIngredient(TagKey tag, int quantity) { addAutoCriteria(tag); - Ingredient ingredient = Ingredient.of(tag); + Ingredient ingredient = Ingredient.of(items.getOrThrow(tag)); for (int i = 0; i < quantity; ++i) { ingredients.add(ingredient); } diff --git a/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java index 1e0e66e2..a794772f 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java @@ -1,7 +1,9 @@ package codechicken.lib.datagen.recipe; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.ItemLike; @@ -14,12 +16,14 @@ */ public class SpecialCraftingRecipeBuilder implements RecipeBuilder { - protected final ResourceLocation id; + protected final Identifier id; + protected final ResourceKey> key; private final Factory factory; - public SpecialCraftingRecipeBuilder(ResourceLocation id, Factory factory) { + public SpecialCraftingRecipeBuilder(Identifier id, Factory factory) { this.id = id; + this.key = ResourceKey.create(Registries.RECIPE, id); this.factory = factory; } @@ -36,18 +40,23 @@ public static SpecialCraftingRecipeBuilder builder(ItemStack id, Factory factory } public static SpecialCraftingRecipeBuilder builder(String id, Factory factory) { - return builder(ResourceLocation.parse(id), factory); + return builder(Identifier.parse(id), factory); } - public static SpecialCraftingRecipeBuilder builder(ResourceLocation id, Factory factory) { + public static SpecialCraftingRecipeBuilder builder(Identifier id, Factory factory) { return new SpecialCraftingRecipeBuilder(id, factory); } @Override - public ResourceLocation getId() { + public final Identifier getId() { return id; } + @Override + public final ResourceKey> getKey() { + return key; + } + @Override public BuiltRecipe build() { return new BuiltRecipe( diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGui.java b/src/main/java/codechicken/lib/gui/modular/ModularGui.java index 3ad8fb93..8e3d26dc 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGui.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGui.java @@ -1,7 +1,10 @@ package codechicken.lib.gui.modular; import codechicken.lib.gui.modular.elements.GuiElement; -import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.gui.modular.lib.CursorHelper; +import codechicken.lib.gui.modular.lib.DynamicTextures; +import codechicken.lib.gui.modular.lib.GuiProvider; import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GeoParam; @@ -10,14 +13,14 @@ import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.world.inventory.Slot; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.util.TriConsumer; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -57,16 +60,16 @@ public class ModularGui implements GuiParent { private Screen parentScreen; private Component guiTitle = Component.empty(); - private ResourceLocation newCursor = null; + private Identifier newCursor = null; private final Map> slotHandlers = new HashMap<>(); private final List tickListeners = new ArrayList<>(); private final List resizeListeners = new ArrayList<>(); private final List closeListeners = new ArrayList<>(); - private final List> preClickListeners = new ArrayList<>(); - private final List> postClickListeners = new ArrayList<>(); - private final List> preKeyPressListeners = new ArrayList<>(); - private final List> postKeyPressListeners = new ArrayList<>(); + private final List> preClickListeners = new ArrayList<>(); + private final List> postClickListeners = new ArrayList<>(); + private final List> preKeyPressListeners = new ArrayList<>(); + private final List> postKeyPressListeners = new ArrayList<>(); private int jeiHighlightTime = 0; @@ -101,11 +104,10 @@ public GuiProvider getProvider() { //=== Modular Gui Setup ===// - public void setGuiTitle(@NotNull Component guiTitle) { + public void setGuiTitle(Component guiTitle) { this.guiTitle = guiTitle; } - @NotNull public Component getGuiTitle() { return guiTitle; } @@ -202,52 +204,30 @@ public boolean vanillaSlotRendering() { //=== Modular Gui Passthrough Methods ===// - /** - * Create a new {@link GuiRender} for the current render call. - * - * @param buffers BufferSource can be retried from {@link GuiGraphics} - * @return A new {@link GuiRender} for the current render call. - */ - @Deprecated //If you have the GuiGraphics, use GuiRender#convert to ensure the underlying PoseStack is carried over. That will ensure things like the JEI overlay will be rendered at a - public GuiRender createRender(MultiBufferSource.BufferSource buffers) { - return new GuiRender(mc, buffers); - } - /** * Primary render method for ModularGui. The screen implementing ModularGui must call this in its render method. - * Followed by the {@link #renderOverlay(GuiRender, float)} method to handle overlay rendering. - * - * @param render GuiRender instance converted from Minecraft's {@link GuiGraphics} via {@link GuiRender#convert(GuiGraphics)} + * Followed by the {@link #renderOverlay(GuiGraphics, float)} method to handle overlay rendering. */ - public void render(GuiRender render, float partialTicks) { + public void render(GuiGraphics graphics, float partialTicks) { root.clearGeometryCache(); double mouseX = computeMouseX(); double mouseY = computeMouseY(); - root.render(render, mouseX, mouseY, partialTicks); - - //Ensure overlay is rendered at a depth of ether 400 or total element depth + 100 (whichever is greater) - double depth = root.getCombinedElementDepth(); - if (depth <= 300) { - render.pose().translate(0, 0, 400 - depth); - } else { - render.pose().translate(0, 0, 100); - } + root.render(graphics, mouseX, mouseY, partialTicks); } /** * Handles gui overlay rendering. This is where things like tool tips are rendered. - * This should be called immediately after {@link #render(GuiRender, float)} + * This should be called immediately after {@link #render(GuiGraphics, float)} *

    - * The reason this is split out from {@link #render(GuiRender, float)} is to allow + * The reason this is split out from {@link #render(GuiGraphics, float)} is to allow * stack tool tips to override gui overlay rendering in {@link ModularGuiContainer} * - * @param render This should be the same render instance that was passed to the previous {@link #render(GuiRender, float)} call. * @return true if an overlay such as a tooltip is currently being drawn. */ - public boolean renderOverlay(GuiRender render, float partialTicks) { + public boolean renderOverlay(GuiGraphics graphics, float partialTicks) { double mouseX = computeMouseX(); double mouseY = computeMouseY(); - return root.renderOverlay(render, mouseX, mouseY, partialTicks, false); + return root.renderOverlay(graphics, mouseX, mouseY, partialTicks, false); } /** @@ -277,16 +257,14 @@ public void mouseMoved(double mouseX, double mouseY) { /** * Pass through for the mouseClicked event. Any screen implementing {@link ModularGui} must pass through this event. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param button Mouse Button + * @param event The mouse button event. Position, Key, and modifiers. * @return true if this event has been consumed. */ - public boolean mouseClicked(double mouseX, double mouseY, int button) { - preClickListeners.forEach(e -> e.accept(mouseX, mouseY, button)); - boolean consumed = root.mouseClicked(mouseX, mouseY, button, false); + public boolean mouseClicked(MouseButtonEvent event) { + preClickListeners.forEach(e -> e.accept(event)); + boolean consumed = root.mouseClicked(event, false); if (!consumed) { - postClickListeners.forEach(e -> e.accept(mouseX, mouseY, button)); + postClickListeners.forEach(e -> e.accept(event)); } return consumed; } @@ -294,28 +272,24 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { /** * Pass through for the mouseReleased event. Any screen implementing {@link ModularGui} must pass through this event. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param button Mouse Button + * @param event The mouse button event. Position, Key, and modifiers. * @return true if this event has been consumed. */ - public boolean mouseReleased(double mouseX, double mouseY, int button) { - return root.mouseReleased(mouseX, mouseY, button, false); + public boolean mouseReleased(MouseButtonEvent event) { + return root.mouseReleased(event, false); } /** * Pass through for the keyPressed event. Any screen implementing {@link ModularGui} must pass through this event. * - * @param key the keyboard key that was pressed. - * @param scancode the system-specific scancode of the key - * @param modifiers bitfield describing which modifier keys were held down. + * @param event The key event. Key, scancode, and modifiers. * @return true if this event has been consumed. */ - public boolean keyPressed(int key, int scancode, int modifiers) { - preKeyPressListeners.forEach(e -> e.accept(key, scancode, modifiers)); - boolean consumed = root.keyPressed(key, scancode, modifiers, false); + public boolean keyPressed(KeyEvent event) { + preKeyPressListeners.forEach(e -> e.accept(event)); + boolean consumed = root.keyPressed(event, false); if (!consumed) { - postKeyPressListeners.forEach(e -> e.accept(key, scancode, modifiers)); + postKeyPressListeners.forEach(e -> e.accept(event)); } return consumed; } @@ -323,24 +297,21 @@ public boolean keyPressed(int key, int scancode, int modifiers) { /** * Pass through for the keyReleased event. Any screen implementing {@link ModularGui} must pass through this event. * - * @param key the keyboard key that was released. - * @param scancode the system-specific scancode of the key - * @param modifiers bitfield describing which modifier keys were held down. + * @param event The key event. Key, scancode, and modifiers. * @return true if this event has been consumed. */ - public boolean keyReleased(int key, int scancode, int modifiers) { - return root.keyReleased(key, scancode, modifiers, false); + public boolean keyReleased(KeyEvent event) { + return root.keyReleased(event, false); } /** * Pass through for the charTyped event. Any screen implementing {@link ModularGui} must pass through this event. * - * @param character The character typed. - * @param modifiers bitfield describing which modifier keys were held down. + * @param event The character event, codepoint and modifiers. * @return true if this event has been consumed. */ - public boolean charTyped(char character, int modifiers) { - return root.charTyped(character, modifiers, false); + public boolean charTyped(CharacterEvent event) { + return root.charTyped(event, false); } /** @@ -523,7 +494,7 @@ public GuiElement getSlotHandler(Slot slot) { * Sets the current mouse cursor. * The cursor is reset at the end of each UI tick so this must be set every tick for as long as you want your custom cursor to be active. */ - public void setCursor(ResourceLocation cursor) { + public void setCursor(Identifier cursor) { this.newCursor = cursor; } @@ -575,7 +546,7 @@ public void onClose(Runnable onClose) { /** * Allows you to attach a callback that will be fired on mouse click, before the click is handled by the rest of the gui. */ - public void onMouseClickPre(TriConsumer onClick) { + public void onMouseClickPre(Consumer onClick) { preClickListeners.add(onClick); } @@ -583,14 +554,14 @@ public void onMouseClickPre(TriConsumer onClick) { * Allows you to attach a callback that will be fired on mouse click, after the click has been handled by the rest of the gui. * Will only be fired if the event was not consumed by an element. */ - public void onMouseClickPost(TriConsumer onClick) { + public void onMouseClickPost(Consumer onClick) { postClickListeners.add(onClick); } /** * Allows you to attach a callback that will be fired on key press, before the is handled by the rest of the gui. */ - public void onKeyPressPre(TriConsumer preKeyPress) { + public void onKeyPressPre(Consumer preKeyPress) { preKeyPressListeners.add(preKeyPress); } @@ -598,7 +569,7 @@ public void onKeyPressPre(TriConsumer preKeyPress) { * Allows you to attach a callback that will be fired on key press, after it has been handled by the rest of the gui. * Will only be fired if the event was not consumed by an element. */ - public void onKeyPressPost(TriConsumer postKeyPress) { + public void onKeyPressPost(Consumer postKeyPress) { postKeyPressListeners.add(postKeyPress); } } diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java index d6d23318..9d8a1977 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -1,15 +1,18 @@ package codechicken.lib.gui.modular; import codechicken.lib.gui.modular.elements.GuiElement; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; import codechicken.lib.gui.modular.lib.geometry.GeoParam; import net.minecraft.ChatFormatting; -import net.minecraft.Util; +import net.minecraft.util.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.core.component.DataComponents; import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; import net.minecraft.world.entity.player.Inventory; @@ -17,7 +20,6 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** @@ -31,7 +33,8 @@ public class ModularGuiContainer extends Abstra public final ModularGui modularGui; /** * Flag used to disable vanilla slot highlight rendering. - * */ + * + */ private boolean renderingSlots = false; public ModularGuiContainer(T containerMenu, Inventory inventory, ContainerGuiProvider provider) { @@ -39,13 +42,19 @@ public ModularGuiContainer(T containerMenu, Inventory inventory, ContainerGuiPro provider.setMenuAccess(this); this.modularGui = new ModularGui(provider); this.modularGui.setScreen(this); + addRenderableOnly(this::renderModularGui); + } + + @Override + protected void clearWidgets() { + super.clearWidgets(); + addRenderableOnly(this::renderModularGui); } public ModularGui getModularGui() { return modularGui; } - @NotNull @Override public Component getTitle() { return modularGui.getGuiTitle(); @@ -62,43 +71,50 @@ protected void init() { } @Override - public void resize(@NotNull Minecraft minecraft, int width, int height) { - super.resize(minecraft, width, height); + public void resize(int width, int height) { + super.resize(width, height); modularGui.onScreenInit(minecraft, font, width, height); } @Override - public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { GuiElement root = modularGui.getRoot(); topPos = (int) root.getValue(GeoParam.TOP); leftPos = (int) root.getValue(GeoParam.LEFT); imageWidth = (int) root.getValue(GeoParam.WIDTH); imageHeight = (int) root.getValue(GeoParam.HEIGHT); - if (modularGui.renderBackground()) { - //Called here to ensure background renders before modularGui elements. - super.renderBackground(graphics, mouseX, mouseY, partialTicks); - } - GuiRender render = GuiRender.convert(graphics); - modularGui.render(render, partialTicks); - super.render(graphics, mouseX, mouseY, partialTicks); - //Ensure we render overlay on top of things like JEI - render.pose().pushPose(); - render.pose().translate(0, 0, 400); - if (!handleFloatingItemRender(render, mouseX, mouseY) && !renderHoveredStackToolTip(render, mouseX, mouseY)) { - modularGui.renderOverlay(render, partialTicks); + if (!handleFloatingItemRender(graphics, mouseX, mouseY) && !renderHoveredStackToolTip(graphics, mouseX, mouseY)) { + modularGui.renderOverlay(graphics, partialTicks); } - render.pose().popPose(); + } + + private void renderModularGui(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + modularGui.render(graphics, partialTicks); } @Override public void renderBackground(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { - //Stubbed to avoid the above super.render() call from rendering the background again. + if (modularGui.renderBackground()) { + super.renderBackground(graphics, mouseX, mouseY, partialTick); + } } - protected boolean handleFloatingItemRender(GuiRender render, int mouseX, int mouseY) { + @Override + public void renderCarriedItem(GuiGraphics guiGraphics, int mouseX, int mouseY) { + if (modularGui.vanillaSlotRendering()) return; + super.renderCarriedItem(guiGraphics, mouseX, mouseY); + } + + @Override + public void renderSnapbackItem(GuiGraphics guiGraphics) { + if (modularGui.vanillaSlotRendering()) return; + super.renderSnapbackItem(guiGraphics); + } + + protected boolean handleFloatingItemRender(GuiGraphics graphics, int mouseX, int mouseY) { if (modularGui.vanillaSlotRendering()) return false; boolean ret = false; @@ -114,36 +130,42 @@ protected boolean handleFloatingItemRender(GuiRender render, int mouseX, int mou countOverride = ChatFormatting.YELLOW + "0"; } } - renderFloatingItem(render, stack, mouseX - 8, mouseY - yOffset, countOverride); + renderFloatingItem(graphics, stack, mouseX - 8, mouseY - yOffset, countOverride); ret = modularGui.doesFloatingItemDisableToolTips(); } - if (!this.snapbackItem.isEmpty()) { - float anim = (float) (Util.getMillis() - this.snapbackTime) / 100.0F; + if (snapbackData != null) { + float anim = Mth.clamp((float) (Util.getMillis() - snapbackData.time()) / 100.0F, 0F, 1F); + int xDist = snapbackData.end().x - snapbackData.start().x; + int yDist = snapbackData.end().y - snapbackData.start().y; + int xPos = snapbackData.start().x + (int) ((float) xDist * anim); + int yPos = snapbackData.start().y + (int) ((float) yDist * anim); + renderFloatingItem(graphics, snapbackData.item(), xPos + leftPos, yPos + topPos, null); if (anim >= 1.0F) { - anim = 1.0F; - this.snapbackItem = ItemStack.EMPTY; + this.snapbackData = null; } - - int xDist = snapbackEnd.x - snapbackStartX; - int yDist = snapbackEnd.y - snapbackStartY; - int xPos = snapbackStartX + (int) ((float) xDist * anim); - int yPos = snapbackStartY + (int) ((float) yDist * anim); - renderFloatingItem(render, snapbackItem, xPos + leftPos, yPos + topPos, null); ret = modularGui.doesFloatingItemDisableToolTips(); } return ret; } - protected boolean renderHoveredStackToolTip(GuiRender guiGraphics, int mouseX, int mouseY) { - if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem()) { + protected boolean renderHoveredStackToolTip(GuiGraphics guiGraphics, int mouseX, int mouseY) { + if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem() && showTooltipWithItemInHand(hoveredSlot.getItem())) { GuiElement handler = modularGui.getSlotHandler(hoveredSlot); if (handler != null && (handler.blockMouseOver(handler, mouseX, mouseY) || !handler.isMouseOver())) { return false; } ItemStack itemStack = this.hoveredSlot.getItem(); - guiGraphics.toolTipWithImage(this.getTooltipFromContainerItem(itemStack), itemStack.getTooltipImage(), itemStack, mouseX, mouseY); + guiGraphics.setTooltipForNextFrame( + this.font, + this.getTooltipFromContainerItem(itemStack), + itemStack.getTooltipImage(), + itemStack, + mouseX, + mouseY, + itemStack.get(DataComponents.TOOLTIP_STYLE) + ); return true; } return false; @@ -168,13 +190,13 @@ public void mouseMoved(double mouseX, double mouseY) { } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - return modularGui.mouseClicked(mouseX, mouseY, button) || super.mouseClicked(mouseX, mouseY, button); + public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + return modularGui.mouseClicked(event) || super.mouseClicked(event, doubleClick); } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { - return modularGui.mouseReleased(mouseX, mouseY, button) || super.mouseReleased(mouseX, mouseY, button); + public boolean mouseReleased(MouseButtonEvent event) { + return modularGui.mouseReleased(event) || super.mouseReleased(event); } @Override @@ -183,18 +205,18 @@ public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, doubl } @Override - public boolean keyPressed(int key, int scancode, int modifiers) { - return modularGui.keyPressed(key, scancode, modifiers) || super.keyPressed(key, scancode, modifiers); + public boolean keyPressed(KeyEvent event) { + return modularGui.keyPressed(event) || super.keyPressed(event); } @Override - public boolean keyReleased(int key, int scancode, int modifiers) { - return modularGui.keyReleased(key, scancode, modifiers) || super.keyReleased(key, scancode, modifiers); + public boolean keyReleased(KeyEvent event) { + return modularGui.keyReleased(event) || super.keyReleased(event); } @Override - public boolean charTyped(char character, int modifiers) { - return modularGui.charTyped(character, modifiers) || super.charTyped(character, modifiers); + public boolean charTyped(CharacterEvent event) { + return modularGui.charTyped(event) || super.charTyped(event); } //=== AbstractContainerMenu Overrides ===// @@ -204,9 +226,9 @@ protected void renderBg(GuiGraphics guiGraphics, float f, int i, int j) { } @Override - public void renderSlot(GuiGraphics guiGraphics, Slot slot) { + protected void renderSlot(GuiGraphics guiGraphics, Slot slot, int mouseX, int mouseY) { if (modularGui.vanillaSlotRendering()) { - super.renderSlot(guiGraphics, slot); + super.renderSlot(guiGraphics, slot, mouseX, mouseY); } else { renderingSlots = true; } @@ -214,7 +236,7 @@ public void renderSlot(GuiGraphics guiGraphics, Slot slot) { //Modular gui friendly version of the slot render @Override - public void renderSlot(GuiRender render, Slot slot) { + public void doRenderSlot(GuiGraphics graphics, Slot slot) { if (modularGui.vanillaSlotRendering()) return; int slotX = slot.x + leftPos; int slotY = slot.y + topPos; @@ -251,10 +273,9 @@ public void renderSlot(GuiRender render, Slot slot) { if (!dontRenderItem) { if (dragingToSlot) { //Highlights slots when doing a drag place operation. - render.fill(slotX, slotY, slotX + 16, slotY + 16, 0x80ffffff); + graphics.fill(slotX, slotY, slotX + 16, slotY + 16, 0x80ffffff); } - render.renderItem(slotStack, slotX, slotY, 16, slot.x + (slot.y * this.imageWidth)); //TODO May want a random that does not change if the slot is moved. - render.renderItemDecorations(slotStack, slotX, slotY, countString); + renderSlotContents(graphics, slotStack, slot, countString); } } @@ -275,24 +296,12 @@ protected void renderLabels(GuiGraphics guiGraphics, int i, int j) { renderingSlots = false; } - @Override - public void renderFloatingItem(GuiGraphics guiGraphics, ItemStack itemStack, int i, int j, String string) { - if (modularGui.vanillaSlotRendering()) super.renderFloatingItem(guiGraphics, itemStack, i, j, string); - } - - public void renderFloatingItem(GuiRender render, ItemStack itemStack, int x, int y, String string) { - render.pose().pushPose(); - render.pose().translate(0.0F, 0.0F, 50F); - render.renderItem(itemStack, x, y); - render.renderItemDecorations(itemStack, x, y - (this.draggingItem.isEmpty() ? 0 : 8), string); - render.pose().popPose(); - } - @Nullable @Override - public Slot findSlot(double mouseX, double mouseY) { - Slot slot = super.findSlot(mouseX, mouseY); + public Slot getHoveredSlot(double mouseX, double mouseY) { + Slot slot = super.getHoveredSlot(mouseX, mouseY); if (slot == null) return null; + GuiElement handler = modularGui.getSlotHandler(slot); if (handler != null && (!handler.isEnabled() || !handler.isMouseOver())) { return null; diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java index f905bd86..0fa7f79e 100644 --- a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java @@ -1,12 +1,13 @@ package codechicken.lib.gui.modular; import codechicken.lib.gui.modular.lib.GuiProvider; -import codechicken.lib.gui.modular.lib.GuiRender; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; /** * A simple ModularGui screen implementation. @@ -35,7 +36,6 @@ public ModularGui getModularGui() { return modularGui; } - @NotNull @Override public Component getTitle() { return modularGui.getGuiTitle(); @@ -57,23 +57,19 @@ protected void init() { } @Override - public void resize(@NotNull Minecraft minecraft, int width, int height) { - super.resize(minecraft, width, height); + public void resize(int width, int height) { + super.resize(width, height); modularGui.onScreenInit(minecraft, font, width, height); } @Override - public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { if (modularGui.renderBackground()) { renderBackground(graphics, mouseX, mouseY, partialTicks); } - GuiRender render = GuiRender.convert(graphics); - modularGui.render(render, partialTicks); - //Ensure we render overlay on top of things like JEI - render.pose().pushPose(); - render.pose().translate(0, 0, 400); - modularGui.renderOverlay(render, partialTicks); - render.pose().popPose(); + modularGui.render(graphics, partialTicks); + // TODO do we render atop JEI? Whats the event ordering here? + modularGui.renderOverlay(graphics, partialTicks); } @Override @@ -94,13 +90,13 @@ public void mouseMoved(double mouseX, double mouseY) { } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - return modularGui.mouseClicked(mouseX, mouseY, button) || super.mouseClicked(mouseX, mouseY, button); + public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + return modularGui.mouseClicked(event) || super.mouseClicked(event, doubleClick); } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { - return modularGui.mouseReleased(mouseX, mouseY, button) || super.mouseReleased(mouseX, mouseY, button); + public boolean mouseReleased(MouseButtonEvent event) { + return modularGui.mouseReleased(event) || super.mouseReleased(event); } @Override @@ -109,17 +105,17 @@ public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, doubl } @Override - public boolean keyPressed(int key, int scancode, int modifiers) { - return modularGui.keyPressed(key, scancode, modifiers) || super.keyPressed(key, scancode, modifiers); + public boolean keyPressed(KeyEvent event) { + return modularGui.keyPressed(event) || super.keyPressed(event); } @Override - public boolean keyReleased(int key, int scancode, int modifiers) { - return modularGui.keyReleased(key, scancode, modifiers) || super.keyReleased(key, scancode, modifiers); + public boolean keyReleased(KeyEvent event) { + return modularGui.keyReleased(event) || super.keyReleased(event); } @Override - public boolean charTyped(char character, int modifiers) { - return modularGui.charTyped(character, modifiers) || super.charTyped(character, modifiers); + public boolean charTyped(CharacterEvent event) { + return modularGui.charTyped(event) || super.charTyped(event); } } diff --git a/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java b/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java new file mode 100644 index 00000000..1818b77a --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java @@ -0,0 +1,55 @@ +package codechicken.lib.gui.modular; + +import com.google.common.base.Suppliers; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.Material; +import net.minecraft.data.AtlasIds; +import net.minecraft.resources.Identifier; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * A supplier for sprites. + *

    + * May return null to indicate the sprite is not available. This will usually disable + * the thing being rendered. + *

    + * Created by covers1624 on 4/1/26. + */ +@FunctionalInterface +public interface SpriteSupplier extends Supplier { + + SpriteSupplier EMPTY = () -> null; + + @Override + @Nullable + TextureAtlasSprite get(); + + default void ifPresent(Consumer cons) { + var tex = get(); + if (tex != null) { + cons.accept(tex); + } + } + + static SpriteSupplier gui(Identifier spriteLoc) { + return of(AtlasIds.GUI, spriteLoc); + } + + static SpriteSupplier of(Identifier atlasLoc, Identifier spriteLoc) { + var memo = Suppliers.memoize(() -> Minecraft.getInstance().getAtlasManager().get(new Material(atlasLoc, spriteLoc))); + return memo::get; + } + + static SpriteSupplier gui(Supplier sup) { + return of(() -> new Material(AtlasIds.GUI, sup.get())); + } + + static SpriteSupplier of(Supplier sup) { + var atlasManager = Minecraft.getInstance().getAtlasManager(); + return () -> atlasManager.get(sup.get()); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java index f4434224..d16ccf3b 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java @@ -3,13 +3,14 @@ import codechicken.lib.gui.modular.lib.Constraints; import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.GuiTextures; +import codechicken.lib.gui.modular.SpriteSupplier; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.core.Holder; import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; @@ -17,12 +18,14 @@ import java.util.function.Function; import java.util.function.Supplier; +import static codechicken.lib.CodeChickenLib.MOD_ID; import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; /** * Created by brandon3055 on 28/08/2023 */ public class GuiButton extends GuiElement { + public static final int LEFT_CLICK = 0; public static final int RIGHT_CLICK = 1; public static final int MIDDLE_CLICK = 2; @@ -30,11 +33,11 @@ public class GuiButton extends GuiElement { private final Map onClick = new HashMap<>(); private final Map onPress = new HashMap<>(); private boolean pressed = false; - private Holder pressSound = SoundEvents.UI_BUTTON_CLICK; - private Holder releaseSound = null; + private @Nullable Holder pressSound = SoundEvents.UI_BUTTON_CLICK; + private @Nullable Holder releaseSound = null; private Supplier disabled = () -> false; - private Supplier toggleState; - private GuiText label = null; + private @Nullable Supplier toggleState; + private @Nullable GuiText label = null; private boolean resetHoverOnPress = true; /** @@ -44,23 +47,23 @@ public class GuiButton extends GuiElement { * * @param parent parent {@link GuiParent}. */ - public GuiButton(@NotNull GuiParent parent) { + public GuiButton(GuiParent parent) { super(parent); } /** * Creates a new gui button that looks and acts exactly like a standard vanilla button. */ - public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Component label, Runnable onClick) { + public static GuiButton vanilla(GuiParent parent, @Nullable Component label, Runnable onClick) { return vanilla(parent, label).onClick(onClick); } /** * Creates a new gui button that looks and acts exactly like a standard vanilla button. */ - public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Component label) { + public static GuiButton vanilla(GuiParent parent, @Nullable Component label) { GuiButton button = new GuiButton(parent); - GuiTexture texture = new GuiTexture(button, GuiTextures.CCL.getter(() -> button.toggleState() ? "dynamic/button_highlight" : "dynamic/button_vanilla")); + GuiTexture texture = new GuiTexture(button, SpriteSupplier.gui(() -> Identifier.fromNamespaceAndPath(MOD_ID, button.toggleState() ? "dynamic/button_highlight" : "dynamic/button_vanilla"))); texture.dynamicTexture(); GuiRectangle highlight = new GuiRectangle(button).border(() -> button.hoverTime() > 0 ? 0xFFFFFFFF : 0); @@ -68,8 +71,9 @@ public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Componen Constraints.bind(highlight, button); if (label != null) { - button.setLabel(new GuiText(button, label)); - Constraints.bind(button.getLabel(), button, 0, 2, 0, 2); + var buttonLabel = new GuiText(button, label); + button.setLabel(buttonLabel); + Constraints.bind(buttonLabel, button, 0, 2, 0, 2); } return button; @@ -78,14 +82,14 @@ public static GuiButton vanilla(@NotNull GuiParent parent, @Nullable Componen /** * Creates a vanilla button with a "press" animation. */ - public static GuiButton vanillaAnimated(@NotNull GuiParent parent, Component label, Runnable onPress) { + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Component label, Runnable onPress) { return vanillaAnimated(parent, label == null ? null : () -> label, onPress); } /** * Creates a vanilla button with a "press" animation. */ - public static GuiButton vanillaAnimated(@NotNull GuiParent parent, @Nullable Supplier label, Runnable onPress) { + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Supplier label, Runnable onPress) { return vanillaAnimated(parent, label).onPress(onPress); } @@ -94,16 +98,16 @@ public static GuiButton vanillaAnimated(@NotNull GuiParent parent, @Nullable /** * Creates a vanilla button with a "press" animation. */ - public static GuiButton vanillaAnimated(@NotNull GuiParent parent, Component label) { + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Component label) { return vanillaAnimated(parent, label == null ? null : () -> label); } /** * Creates a vanilla button with a "press" animation. */ - public static GuiButton vanillaAnimated(@NotNull GuiParent parent, @Nullable Supplier label) { + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Supplier label) { GuiButton button = new GuiButton(parent); - GuiTexture texture = new GuiTexture(button, GuiTextures.CCL.getter(() -> button.toggleState() || button.isPressed() ? "dynamic/button_pressed" : "dynamic/button_vanilla")); + GuiTexture texture = new GuiTexture(button, SpriteSupplier.gui(() -> Identifier.fromNamespaceAndPath(MOD_ID, button.toggleState() || button.isPressed() ? "dynamic/button_pressed" : "dynamic/button_vanilla"))); texture.dynamicTexture(); GuiRectangle highlight = new GuiRectangle(button).border(() -> button.isMouseOver() ? 0xFFFFFFFF : 0); @@ -125,14 +129,14 @@ public static GuiButton vanillaAnimated(@NotNull GuiParent parent, @Nullable /** * Super simple button that is just a coloured rectangle with a label. */ - public static GuiButton flatColourButton(@NotNull GuiParent parent, @Nullable Supplier label, Function buttonColour) { + public static GuiButton flatColourButton(GuiParent parent, @Nullable Supplier label, Function buttonColour) { return flatColourButton(parent, label, buttonColour, null); } /** * Super simple button that is just a coloured rectangle with a label. */ - public static GuiButton flatColourButton(@NotNull GuiParent parent, @Nullable Supplier label, Function buttonColour, @Nullable Function borderColour) { + public static GuiButton flatColourButton(GuiParent parent, @Nullable Supplier label, Function buttonColour, @Nullable Function borderColour) { GuiButton button = new GuiButton(parent); GuiRectangle background = new GuiRectangle(button) .fill(() -> buttonColour.apply(button.isMouseOver() || button.toggleState() || button.isPressed())) @@ -153,7 +157,7 @@ public static GuiButton flatColourButton(@NotNull GuiParent parent, @Nullable * * @param label The button label. */ - public GuiButton setLabel(GuiText label) { + public GuiButton setLabel(@Nullable GuiText label) { this.label = label; return this; } @@ -161,7 +165,7 @@ public GuiButton setLabel(GuiText label) { /** * @return The buttons label element, If it has one. */ - public GuiText getLabel() { + public @Nullable GuiText getLabel() { return label; } @@ -276,7 +280,7 @@ public boolean toggleState() { /** * Sets the sound to be played when this button is pressed. */ - public GuiButton setPressSound(Holder pressSound) { + public GuiButton setPressSound(@Nullable Holder pressSound) { this.pressSound = pressSound; return this; } @@ -284,50 +288,47 @@ public GuiButton setPressSound(Holder pressSound) { /** * Sets the sound to be played when this button is released. */ - public GuiButton setReleaseSound(Holder releaseSound) { + public GuiButton setReleaseSound(@Nullable Holder releaseSound) { this.releaseSound = releaseSound; return this; } - public Holder getPressSound() { + public @Nullable Holder getPressSound() { return pressSound; } - public Holder getReleaseSound() { + public @Nullable Holder getReleaseSound() { return releaseSound; } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { + public boolean mouseClicked(MouseButtonEvent event) { if (!isMouseOver() || isDisabled()) return false; - Runnable onClick = this.onClick.get(button); - Runnable onPress = this.onPress.get(button); + Runnable onClick = this.onClick.get(event.button()); + Runnable onPress = this.onPress.get(event.button()); if (onClick == null && onPress == null) return false; + pressed = true; if (resetHoverOnPress) hoverTime = 1; - boolean consume = false; if (onClick != null) { onClick.run(); - consume = true; - } - if (onPress != null) { - consume = true; } if (getPressSound() != null) { mc().getSoundManager().play(SimpleSoundInstance.forUI(getPressSound(), 1F)); } - return consume; + return true; } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { - consumed = super.mouseReleased(mouseX, mouseY, button, consumed); + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseReleased(event, consumed); if (!pressed) return consumed; - Runnable onClick = this.onClick.get(button); - Runnable onPress = this.onPress.get(button); + Runnable onClick = this.onClick.get(event.button()); + Runnable onPress = this.onPress.get(event.button()); if (onClick == null && onPress == null) return consumed; + if (resetHoverOnPress) hoverTime = 1; if (!isDisabled() && isMouseOver()) { diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java index 1d4d6b71..e4800225 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java @@ -4,9 +4,10 @@ import codechicken.lib.gui.modular.lib.*; import codechicken.lib.gui.modular.lib.geometry.Axis; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; @@ -25,7 +26,7 @@ public class GuiColourPicker extends GuiManipulable { private GuiButton okButton; private GuiButton cancelButton; - public GuiColourPicker(@NotNull GuiParent parent, Colour initialColour) { + public GuiColourPicker(GuiParent parent, Colour initialColour) { super(parent); this.initialColour = initialColour; } @@ -132,15 +133,15 @@ public GuiColourPicker setCancelOnOutsideClick(boolean closeOnOutsideClick) { } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { - if (closeOnOutsideClick && !getContentElement().getRectangle().contains(mouseX, mouseY)) { + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + if (closeOnOutsideClick && !getContentElement().getRectangle().contains(event.x(), event.y())) { cancel(); } - return super.mouseClicked(mouseX, mouseY, button, consumed) || blockOutsideClicks; + return super.mouseClicked(event, consumed) || blockOutsideClicks; } public void cancel() { - if (cancelButton != null && cancelButton.isEnabled()){ + if (cancelButton != null && cancelButton.isEnabled()) { colourState.set(initialColour); } close(); @@ -160,62 +161,64 @@ private static boolean validHex(String value) { } public static class SliderBG extends GuiElement implements BackgroundRender { + public int colour; public int highlight; public GuiSlider slider; public boolean pressed = false; - public SliderBG(@NotNull GuiParent parent, int colour, int highlight) { + public SliderBG(GuiParent parent, int colour, int highlight) { super(parent); this.colour = colour; this.highlight = highlight; } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { - pressed = button == 0; - return super.mouseClicked(mouseX, mouseY, button, consumed); + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + pressed = event.button() == 0; + return super.mouseClicked(event, consumed); } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { - if (button == 0) pressed = false; - return super.mouseReleased(mouseX, mouseY, button, consumed); + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + if (event.button() == 0) pressed = false; + return super.mouseReleased(event, consumed); } @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { - render.fill(xMin(), yMin(), xMin() + 1, yMax(), colour); - render.fill(xMax() - 1, yMin(), xMax(), yMax(), colour); - render.fill(xMin() + 1, yCenter() - 0.5, xMax() - 1, yCenter() + 0.5, colour); + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + render.cc$fill(xMin(), yMin(), xMin() + 1, yMax(), colour); + render.cc$fill(xMax() - 1, yMin(), xMax(), yMax(), colour); + render.cc$fill(xMin() + 1, yCenter() - 0.5, xMax() - 1, yCenter() + 0.5, colour); if ((isMouseOver() && !pressed) || slider.isDragging()) { - render.rect(getRectangle(), highlight); + render.cc$fill(getRectangle(), highlight); } } } public static class ColourPreview extends GuiElement implements BackgroundRender { + private final Supplier colour; public int colourA = 0xFF999999; public int colourB = 0xFF666666; - public ColourPreview(@NotNull GuiParent parent, Supplier colour) { + public ColourPreview(GuiParent parent, Supplier colour) { super(parent); this.colour = colour; } @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { - render.pushScissorRect(xMin(), yMin(), xSize(), ySize()); + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + render.cc$enableScissor(xMin(), yMin(), xSize(), ySize()); for (int x = 0; xMin() + (x * 2) < xMax(); x++) { for (int y = 0; yMin() + (y * 2) < yMax(); y++) { int col = (y & 1) == 0 ? ((x & 1) == 0 ? colourA : colourB) : ((x & 1) == 0 ? colourB : colourA); - render.rect(xMin() + (x * 2), yMin() + (y * 2), 2, 2, col); + render.cc$fill(xMin() + (x * 2), yMin() + (y * 2), 2, 2, col); } } - render.popScissor(); - render.rect(getRectangle(), colour.get()); + render.cc$disableScissor(); + render.cc$fill(getRectangle(), colour.get()); } } @@ -229,19 +232,19 @@ public ColourState getState() { } public SliderState sliderStateAlpha() { - return SliderState.forSlider(() -> (double) colourState.getColour().aF(), e -> colourState.set(colourState.getColour().aF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + return SliderState.forSlider(() -> (double) colourState.getColour().aF(), e -> colourState.set(colourState.getColour().aF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); } public SliderState sliderStateRed() { - return SliderState.forSlider(() -> (double) colourState.getColour().rF(), e -> colourState.set(colourState.getColour().rF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + return SliderState.forSlider(() -> (double) colourState.getColour().rF(), e -> colourState.set(colourState.getColour().rF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); } public SliderState sliderStateGreen() { - return SliderState.forSlider(() -> (double) colourState.getColour().gF(), e -> colourState.set(colourState.getColour().gF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + return SliderState.forSlider(() -> (double) colourState.getColour().gF(), e -> colourState.set(colourState.getColour().gF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); } public SliderState sliderStateBlue() { - return SliderState.forSlider(() -> (double) colourState.getColour().bF(), e -> colourState.set(colourState.getColour().bF(e.floatValue())), () -> -1D / (Screen.hasShiftDown() ? 16 : 64)); + return SliderState.forSlider(() -> (double) colourState.getColour().bF(), e -> colourState.set(colourState.getColour().bF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); } public TextState getTextState() { diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java index 33f344f4..6eb4b1d1 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java @@ -3,6 +3,7 @@ import codechicken.lib.gui.modular.ModularGui; import codechicken.lib.gui.modular.lib.Constraints; import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.Component; import java.util.*; @@ -122,8 +123,8 @@ private void rebuildButtons() { } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { - consumed = super.mouseClicked(mouseX, mouseY, button, consumed); + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseClicked(event, consumed); pressed = isMouseOver(); if (isMouseOver() || consumed) { if (actionOnClick) { @@ -141,8 +142,8 @@ public boolean mouseClicked(double mouseX, double mouseY, int button, boolean co } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { - consumed = super.mouseReleased(mouseX, mouseY, button, consumed); + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseReleased(event, consumed); if (isMouseOver() || consumed) { if (!actionOnClick) { if (consumed && closeOnItemClicked && pressed) { diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java index a3195c62..2d119f49 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java @@ -2,12 +2,12 @@ import codechicken.lib.gui.modular.lib.ContentElement; import codechicken.lib.math.MathHelper; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.gui.modular.lib.geometry.Rectangle; -import org.jetbrains.annotations.NotNull; +import net.minecraft.client.gui.GuiGraphics; import org.joml.Vector2d; +import org.jspecify.annotations.Nullable; import java.util.Random; import java.util.function.Consumer; @@ -24,12 +24,12 @@ public class GuiDVD extends GuiElement implements ContentElement movingElement; private double xOffset = 0; private double yOffset = 0; - private Vector2d velocity = null; + private @Nullable Vector2d velocity = null; private int bounce = 0; private Consumer onBounce = bounce -> { }; - public GuiDVD(@NotNull GuiParent parent) { + public GuiDVD(GuiParent parent) { super(parent); this.movingElement = new GuiElement<>(this) .constrain(TOP, Constraint.relative(get(TOP), () -> yOffset)) @@ -64,7 +64,7 @@ public void tick(double mouseX, double mouseY) { } @Override - public void render(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void render(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { super.render(render, mouseX, mouseY, partialTicks); if (velocity == null) return; diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java index 064e1f9f..bf535d92 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java @@ -5,12 +5,11 @@ import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; -import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; @@ -27,7 +26,7 @@ public class GuiDialog extends GuiElement { private boolean blockKeyInput = true; private boolean blockMouseInput = true; - protected GuiDialog(@NotNull GuiParent parent) { + protected GuiDialog(GuiParent parent) { super(parent); } @@ -40,7 +39,7 @@ protected GuiDialog(@NotNull GuiParent parent) { * @param width The dialog width, (Height will automatically adjust based on content.) * @param options The list of options for this dialog. */ - public static GuiDialog optionsDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, int width, Option... options) { + public static GuiDialog optionsDialog(GuiParent parent, @Nullable Component title, Component dialogText, int width, Option... options) { return optionsDialog(parent, title, dialogText, GuiRectangle::toolTipBackground, GuiDialog::defaultButton, width, options); } @@ -52,7 +51,7 @@ public static GuiDialog optionsDialog(@NotNull GuiParent parent, @Nullable Co * @param width The dialog width, (Height will automatically adjust based on content.) * @param options The list of options for this dialog. */ - public static GuiDialog optionsDialog(@NotNull GuiParent parent, Component dialogText, int width, Option... options) { + public static GuiDialog optionsDialog(GuiParent parent, Component dialogText, int width, Option... options) { return optionsDialog(parent, null, dialogText, width, options); } @@ -65,7 +64,7 @@ public static GuiDialog optionsDialog(@NotNull GuiParent parent, Component di * @param dialogText The main dialog text. * @param width The dialog width, (Height will automatically adjust based on content.) */ - public static GuiDialog infoDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, int width, @Nullable Runnable okAction) { + public static GuiDialog infoDialog(GuiParent parent, @Nullable Component title, Component dialogText, int width, @Nullable Runnable okAction) { return optionsDialog(parent, title, dialogText, width, neutral(Component.translatable("gui.ok"), okAction)); } @@ -78,7 +77,7 @@ public static GuiDialog infoDialog(@NotNull GuiParent parent, @Nullable Compo * @param dialogText The main dialog text. * @param width The dialog width, (Height will automatically adjust based on content.) */ - public static GuiDialog infoDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, int width) { + public static GuiDialog infoDialog(GuiParent parent, @Nullable Component title, Component dialogText, int width) { return infoDialog(parent, title, dialogText, width, null); } @@ -90,7 +89,7 @@ public static GuiDialog infoDialog(@NotNull GuiParent parent, @Nullable Compo * @param dialogText The main dialog text. * @param width The dialog width, (Height will automatically adjust based on content.) */ - public static GuiDialog infoDialog(@NotNull GuiParent parent, Component dialogText, int width) { + public static GuiDialog infoDialog(GuiParent parent, Component dialogText, int width) { return infoDialog(parent, null, dialogText, width); } @@ -138,12 +137,12 @@ public void close() { } @Override - public boolean keyPressed(int key, int scancode, int modifiers) { + public boolean keyPressed(KeyEvent event) { return blockKeyInput; } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { + public boolean mouseClicked(MouseButtonEvent event) { return blockMouseInput; } @@ -160,7 +159,7 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { * @param width The dialog width, (Height will automatically adjust based on content.) * @param options The list of options for this dialog. */ - public static GuiDialog optionsDialog(@NotNull GuiParent parent, @Nullable Component title, Component dialogText, Function> backgroundBuilder, BiFunction buttonBuilder, int width, Option... options) { + public static GuiDialog optionsDialog(GuiParent parent, @Nullable Component title, Component dialogText, Function> backgroundBuilder, BiFunction buttonBuilder, int width, Option... options) { if (options.length == 0) throw new IllegalStateException("Can not create gui dialog with no options!"); ModularGui gui = parent.getModularGui(); @@ -237,5 +236,5 @@ private static GuiButton defaultButton(GuiDialog dialog, Option option) { return button; } - public record Option(Component text, @Nullable Runnable action, Function colour) {} + public record Option(Component text, @Nullable Runnable action, Function colour) { } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java index a94c1909..6ac44ea9 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java @@ -1,21 +1,21 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.colour.ColourARGB; -import com.google.common.collect.Lists; -import com.mojang.blaze3d.vertex.PoseStack; import codechicken.lib.gui.modular.ModularGui; import codechicken.lib.gui.modular.lib.*; import codechicken.lib.gui.modular.lib.geometry.ConstrainedGeometry; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.gui.modular.lib.geometry.Position; import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import codechicken.lib.math.MathHelper; +import com.google.common.collect.Lists; +import com.mojang.blaze3d.vertex.PoseStack; import net.covers1624.quack.util.SneakyUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.security.InvalidParameterException; @@ -44,7 +44,6 @@ */ public class GuiElement> extends ConstrainedGeometry implements ElementEvents, TooltipHandler { - @NotNull private GuiParent parent; private final List> addedQueue = new ArrayList<>(); @@ -64,7 +63,6 @@ public class GuiElement> extends ConstrainedGeometry private boolean isMouseOver = false; private boolean opaque = false; private boolean removed = true; - private boolean zStacking = true; private Supplier enabled = () -> true; private Supplier enableToolTip = () -> true; private Supplier> toolTip = null; @@ -76,12 +74,11 @@ public class GuiElement> extends ConstrainedGeometry /** * @param parent parent {@link GuiParent}. */ - public GuiElement(@NotNull GuiParent parent) { + public GuiElement(GuiParent parent) { this.parent = parent; this.parent.addChild(this); } - @NotNull @Override public GuiParent getParent() { return parent; @@ -301,8 +298,8 @@ public int hoverTime() { @Override public String toString() { return getClass().getSimpleName() + "{" + - "geometry=" + getRectangle() + - '}'; + "geometry=" + getRectangle() + + '}'; } //=== Render / Update ===// @@ -317,49 +314,6 @@ public T setRenderCull(@Nullable Rectangle renderCull) { return SneakyUtils.unsafeCast(this); } - /** - * Allows you to disable child z-stacking, Meaning all child elements will be rendered at the same z-level - * rather than being stacked. (Not Recursive, children their sub elements with stacking) - *

    - * This can be useful when rendering a lot of high z depth elements such as ItemStacks. - * As long as you know for sure none of the elements intersect, it should be safe to disable stacking. - * - * @param zStacking Enable z stacking (default true) - */ - public T setZStacking(boolean zStacking) { - this.zStacking = zStacking; - return SneakyUtils.unsafeCast(this); - } - - public boolean zStacking() { - return zStacking; - } - - /** - * Returns the depth of this element plus all of its children (recursively) - * Note: You should almost never need to override this! Depth of background and / or foreground content - * should be specified via {@link BackgroundRender#getBackgroundDepth()} and {@link ForegroundRender#getForegroundDepth()} - * - * @return The depth (z height) of this element plus all of its children. - */ - public double getCombinedElementDepth() { - double depth = 0; - if (this instanceof BackgroundRender bgr) depth += bgr.getBackgroundDepth(); - if (this instanceof ForegroundRender fgr) depth += fgr.getForegroundDepth(); - - double childDepth = 0; - for (GuiElement child : childElements) { - if (!child.isEnabled()) continue; - if (zStacking) { - childDepth += child.getCombinedElementDepth(); - } else { - childDepth = Math.max(childDepth, child.getCombinedElementDepth()); - } - } - - return depth + childDepth; - } - /** * This is the main render method that handles rendering this element and any child elements it may have. * This method almost never needs to be overridden, instead when creating custom elements with custom rendering, @@ -369,51 +323,31 @@ public double getCombinedElementDepth() { * Note: After the render is complete, the poseStack's z pos will be offset by the total depth of this element and its children. * This is intended behavior, * - * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + * @param graphics Contains gui context information as well as essential render methods/utils including the PoseStack. * @param mouseX Current mouse X position * @param mouseY Current mouse Y position * @param partialTicks Partial render ticks */ - public void render(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void render(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { applyQueuedChildUpdates(); if (this instanceof BackgroundRender bgr) { - double depth = bgr.getBackgroundDepth(); - bgr.renderBackground(render, mouseX, mouseY, partialTicks); - if (depth > 0) { - render.pose().translate(0, 0, depth); - } + bgr.renderBehind(graphics, mouseX, mouseY, partialTicks); } - double maxDepth = 0; for (GuiElement child : childElements) { if (child.isEnabled()) { - boolean rendered = renderChild(child, render, mouseX, mouseY, partialTicks); - //If z-stacking is disabled, we need to undo the z offset that was applied by the child element. - if (!zStacking && rendered) { - double depth = child.getCombinedElementDepth(); - maxDepth = Math.max(maxDepth, depth); - render.pose().translate(0, 0, -depth); - } + renderChild(child, graphics, mouseX, mouseY, partialTicks); } } - if (!zStacking) { - //Now we need to apply the z offset of the tallest child. - render.pose().translate(0, 0, maxDepth); - } - if (this instanceof ForegroundRender fgr) { - double depth = fgr.getForegroundDepth(); - fgr.renderForeground(render, mouseX, mouseY, partialTicks); - if (depth > 0) { - render.pose().translate(0, 0, depth); - } + fgr.renderInFront(graphics, mouseX, mouseY, partialTicks); } } - protected boolean renderChild(GuiElement child, GuiRender render, double mouseX, double mouseY, float partialTicks) { + protected boolean renderChild(GuiElement child, GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { if (renderCull != null && !renderCull.intersects(child.getRectangle())) return false; - child.render(render, mouseX, mouseY, partialTicks); + child.render(graphics, mouseX, mouseY, partialTicks); return true; } @@ -428,20 +362,20 @@ protected boolean renderChild(GuiElement child, GuiRender render, double mous * To check if the cursor is over this element, use 'render.hoveredElement() == this' * {@link #isMouseOver()} Will also work, but may be problematic when multiple, stacked elements have overlay content. * - * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + * @param graphics Contains gui context information as well as essential render methods/utils including the PoseStack. * @param mouseX Current mouse X position * @param mouseY Current mouse Y position * @param partialTicks Partial render ticks * @param consumed Will be true if the overlay render call has already been consumed by another element. * @return true if the render call has been consumed. */ - public boolean renderOverlay(GuiRender render, double mouseX, double mouseY, float partialTicks, boolean consumed) { + public boolean renderOverlay(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks, boolean consumed) { for (GuiElement child : Lists.reverse(getChildren())) { if (child.isEnabled()) { - consumed |= child.renderOverlay(render, mouseX, mouseY, partialTicks, consumed); + consumed |= child.renderOverlay(graphics, mouseX, mouseY, partialTicks, consumed); } } - return consumed || (showToolTip() && renderTooltip(render, mouseX, mouseY)); + return consumed || (showToolTip() && renderTooltip(graphics, Minecraft.getInstance().font, mouseX, mouseY)); } /** @@ -487,7 +421,7 @@ public boolean updateMouseOver(double mouseX, double mouseY, boolean consumed) { } } - isMouseOver = !consumed && GuiRender.isInRect(xMin(), yMin(), xSize(), ySize(), mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY); + isMouseOver = !consumed && MathHelper.isInRect(xMin(), yMin(), xSize(), ySize(), mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY); return consumed || (isMouseOver && isOpaque()); } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java index 907885b0..1e8f5ec6 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java @@ -1,143 +1,143 @@ -package codechicken.lib.gui.modular.elements; - -import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.Constraints; -import codechicken.lib.gui.modular.lib.GuiRender; -import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.GuiTextures; -import codechicken.lib.gui.modular.sprite.Material; -import codechicken.lib.util.FormatUtil; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; - -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.function.BiFunction; -import java.util.function.Supplier; - -import static net.minecraft.ChatFormatting.*; - -/** - * Created by brandon3055 on 10/09/2023 - */ -public class GuiEnergyBar extends GuiElement implements BackgroundRender { - public static final DecimalFormat COMMA_FORMAT = new DecimalFormat("###,###,###,###,###", DecimalFormatSymbols.getInstance(Locale.ROOT)); - public static final Material EMPTY = GuiTextures.CCL.getUncached("widgets/energy_empty"); - public static final Material FULL = GuiTextures.CCL.getUncached("widgets/energy_full"); - - private Supplier energy = () -> 0L; - private Supplier capacity = () -> 0L; - private Material emptyTexture = EMPTY; - private Material fullTexture = FULL; - private BiFunction> toolTipFormatter; - - public GuiEnergyBar(@NotNull GuiParent parent) { - super(parent); - setTooltipDelay(0); - setToolTipFormatter(defaultFormatter()); - } - - /** - * Creates a simple energy bar using a simple slot as a background to make it look nice. - */ - public static EnergyBar simpleBar(@NotNull GuiParent parent) { - GuiRectangle container = GuiRectangle.vanillaSlot(parent); - GuiEnergyBar energyBar = new GuiEnergyBar(container); - Constraints.bind(energyBar, container, 1); - return new EnergyBar(container, energyBar); - } - - public static BiFunction> defaultFormatter() { - return (energy, capacity) -> { - List tooltip = new ArrayList<>(); - tooltip.add(Component.translatable("ccl.energy_bar.energy_storage").withStyle(DARK_AQUA)); - boolean shift = Screen.hasShiftDown(); - tooltip.add(Component.translatable("ccl.energy_bar.capacity") - .withStyle(GOLD) - .append(" ") - .append(Component.literal(shift ? FormatUtil.addCommas(capacity) : FormatUtil.formatNumber(capacity)) - .withStyle(GRAY) - .append(" ") - .append(Component.translatable("ccl.energy_bar.rf") - .withStyle(GRAY) - ) - ) - ); - tooltip.add(Component.translatable("ccl.energy_bar.stored") - .withStyle(GOLD) - .append(" ") - .append(Component.literal(shift ? FormatUtil.addCommas(energy) : FormatUtil.formatNumber(energy)) - .withStyle(GRAY) - ) - .append(" ") - .append(Component.translatable("ccl.energy_bar.rf") - .withStyle(GRAY) - ) - .append(Component.literal(String.format(" (%.2f%%)", ((double) energy / (double) capacity) * 100D)) - .withStyle(GRAY) - ) - ); - return tooltip; - }; - } - - public GuiEnergyBar setEmptyTexture(Material emptyTexture) { - this.emptyTexture = emptyTexture; - return this; - } - - public GuiEnergyBar setFullTexture(Material fullTexture) { - this.fullTexture = fullTexture; - return this; - } - - public GuiEnergyBar setCapacity(long capacity) { - return setCapacity(() -> capacity); - } - - public GuiEnergyBar setCapacity(Supplier capacity) { - this.capacity = capacity; - return this; - } - - public GuiEnergyBar setEnergy(long energy) { - return setEnergy(() -> energy); - } - - public GuiEnergyBar setEnergy(Supplier energy) { - this.energy = energy; - return this; - } - - public long getEnergy() { - return energy.get(); - } - - public long getCapacity() { - return capacity.get(); - } - - /** - * Install a custom formatter to control how the energy tool tip renders. - */ - public GuiEnergyBar setToolTipFormatter(BiFunction> toolTipFormatter) { - this.toolTipFormatter = toolTipFormatter; - setTooltip(() -> this.toolTipFormatter.apply(getEnergy(), getCapacity())); - return this; - } - - @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { - float p = 1 / 128F; - float height = getCapacity() <= 0 ? 0 : (float) ySize() * (getEnergy() / (float) getCapacity()); - float texHeight = height * p; - render.partialSprite(EMPTY.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), EMPTY.sprite(), 0F, 1F - (p * (float) ySize()), p * (float) xSize(), 1F, 0xFFFFFFFF); - render.partialSprite(FULL.renderType(GuiRender::texColType), xMin(), yMin() + (ySize() - height), xMax(), yMax(), FULL.sprite(), 0F, 1F - texHeight, p * (float) xSize(), 1F, 0xFFFFFFFF); - } - - public record EnergyBar(GuiRectangle container, GuiEnergyBar bar) {} -} +//package codechicken.lib.gui.modular.elements; +// +//import codechicken.lib.gui.modular.lib.BackgroundRender; +//import codechicken.lib.gui.modular.lib.Constraints; +//import codechicken.lib.gui.modular.lib.geometry.GuiParent; +//import codechicken.lib.gui.modular.sprite.GuiTextures; +//import codechicken.lib.gui.modular.sprite.SpriteSupplier; +//import codechicken.lib.util.FormatUtil; +//import net.minecraft.client.Minecraft; +//import net.minecraft.client.gui.GuiGraphics; +//import net.minecraft.network.chat.Component; +// +//import java.text.DecimalFormat; +//import java.text.DecimalFormatSymbols; +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Locale; +//import java.util.function.BiFunction; +//import java.util.function.Supplier; +// +//import static net.minecraft.ChatFormatting.*; +// +///** +// * Created by brandon3055 on 10/09/2023 +// */ +//public class GuiEnergyBar extends GuiElement implements BackgroundRender { +// +// public static final DecimalFormat COMMA_FORMAT = new DecimalFormat("###,###,###,###,###", DecimalFormatSymbols.getInstance(Locale.ROOT)); +// public static final SpriteSupplier EMPTY = GuiTextures.CCL.get("widgets/energy_empty"); +// public static final SpriteSupplier FULL = GuiTextures.CCL.get("widgets/energy_full"); +// +// private Supplier energy = () -> 0L; +// private Supplier capacity = () -> 0L; +// private SpriteSupplier emptyTexture = EMPTY; +// private SpriteSupplier fullTexture = FULL; +// private BiFunction> toolTipFormatter; +// +// public GuiEnergyBar(GuiParent parent) { +// super(parent); +// setTooltipDelay(0); +// setToolTipFormatter(defaultFormatter()); +// } +// +// /** +// * Creates a simple energy bar using a simple slot as a background to make it look nice. +// */ +// public static EnergyBar simpleBar(GuiParent parent) { +// GuiRectangle container = GuiRectangle.vanillaSlot(parent); +// GuiEnergyBar energyBar = new GuiEnergyBar(container); +// Constraints.bind(energyBar, container, 1); +// return new EnergyBar(container, energyBar); +// } +// +// public static BiFunction> defaultFormatter() { +// return (energy, capacity) -> { +// List tooltip = new ArrayList<>(); +// tooltip.add(Component.translatable("ccl.energy_bar.energy_storage").withStyle(DARK_AQUA)); +// boolean shift = Minecraft.getInstance().hasShiftDown(); +// tooltip.add(Component.translatable("ccl.energy_bar.capacity") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(shift ? FormatUtil.addCommas(capacity) : FormatUtil.formatNumber(capacity)) +// .withStyle(GRAY) +// .append(" ") +// .append(Component.translatable("ccl.energy_bar.rf") +// .withStyle(GRAY) +// ) +// ) +// ); +// tooltip.add(Component.translatable("ccl.energy_bar.stored") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(shift ? FormatUtil.addCommas(energy) : FormatUtil.formatNumber(energy)) +// .withStyle(GRAY) +// ) +// .append(" ") +// .append(Component.translatable("ccl.energy_bar.rf") +// .withStyle(GRAY) +// ) +// .append(Component.literal(String.format(" (%.2f%%)", ((double) energy / (double) capacity) * 100D)) +// .withStyle(GRAY) +// ) +// ); +// return tooltip; +// }; +// } +// +// public GuiEnergyBar setEmptyTexture(SpriteSupplier emptyTexture) { +// this.emptyTexture = emptyTexture; +// return this; +// } +// +// public GuiEnergyBar setFullTexture(SpriteSupplier fullTexture) { +// this.fullTexture = fullTexture; +// return this; +// } +// +// public GuiEnergyBar setCapacity(long capacity) { +// return setCapacity(() -> capacity); +// } +// +// public GuiEnergyBar setCapacity(Supplier capacity) { +// this.capacity = capacity; +// return this; +// } +// +// public GuiEnergyBar setEnergy(long energy) { +// return setEnergy(() -> energy); +// } +// +// public GuiEnergyBar setEnergy(Supplier energy) { +// this.energy = energy; +// return this; +// } +// +// public long getEnergy() { +// return energy.get(); +// } +// +// public long getCapacity() { +// return capacity.get(); +// } +// +// /** +// * Install a custom formatter to control how the energy tool tip renders. +// */ +// public GuiEnergyBar setToolTipFormatter(BiFunction> toolTipFormatter) { +// this.toolTipFormatter = toolTipFormatter; +// setTooltip(() -> this.toolTipFormatter.apply(getEnergy(), getCapacity())); +// return this; +// } +// +// @Override +// public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { +// float p = 1 / 128F; +// float height = getCapacity() <= 0 ? 0 : (float) ySize() * (getEnergy() / (float) getCapacity()); +// float texHeight = height * p; +// graphics.partialSprite(EMPTY.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), EMPTY.sprite(), 0F, 1F - (p * (float) ySize()), p * (float) xSize(), 1F, 0xFFFFFFFF); +// graphics.partialSprite(FULL.renderType(GuiRender::texColType), xMin(), yMin() + (ySize() - height), xMax(), yMax(), FULL.sprite(), 0F, 1F - texHeight, p * (float) xSize(), 1F, 0xFFFFFFFF); +// } +// +// public record EnergyBar(GuiRectangle container, GuiEnergyBar bar) { } +//} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java index a70097c8..b4eeee2c 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java @@ -1,26 +1,20 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.gui.modular.lib.geometry.Rectangle; import codechicken.lib.render.CCRenderEventHandler; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.math.Axis; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.joml.Matrix4f; -import org.joml.Quaternionf; import java.util.ArrayList; import java.util.HashMap; @@ -34,20 +28,20 @@ public class GuiEntityRenderer extends GuiElement implements BackgroundRender { public static final Logger LOGGER = LogManager.getLogger(); - private static final Map entityCache = new HashMap<>(); - private static final List invalidEntities = new ArrayList<>(); + private static final Map entityCache = new HashMap<>(); + private static final List invalidEntities = new ArrayList<>(); private Supplier rotationSpeed = () -> 1F; private Supplier lockedRotation = () -> 0F; - private Entity entity; - private ResourceLocation entityName; + private @Nullable Entity entity; + private @Nullable Identifier entityName; private boolean invalidEntity = false; private Supplier rotationLocked = () -> false; private Supplier trackMouse = () -> false; private Supplier drawName = () -> false; public boolean force2dSize = false; - public GuiEntityRenderer(@NotNull GuiParent parent) { + public GuiEntityRenderer(GuiParent parent) { super(parent); } @@ -63,11 +57,11 @@ public GuiEntityRenderer setEntity(Entity entity) { return this; } - public GuiEntityRenderer setEntity(ResourceLocation entity) { + public GuiEntityRenderer setEntity(Identifier entity) { this.entityName = entity; this.entity = entityCache.computeIfAbsent(entity, resourceLocation -> { - EntityType type = BuiltInRegistries.ENTITY_TYPE.getOptional(entity).orElse(null); - return type == null ? null : type.create(mc().level); + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(entity); + return type.create(mc().level, EntitySpawnReason.SPAWNER); }); invalidEntity = this.entity == null; @@ -154,16 +148,7 @@ public GuiEntityRenderer setForce2dSize(boolean force2dSize) { } @Override - public double getBackgroundDepth() { - Rectangle rect = getRectangle(); - if (invalidEntity || entity == null) return 0.01; - float scale = (float) (force2dSize ? (Math.min(rect.height() / entity.getBbHeight(), rect.width() / entity.getBbWidth())) : rect.height() / entity.getBbHeight()); - if (Float.isInfinite(scale)) scale = 1; - return scale * 2; - } - - @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { if (invalidEntity) return; try { @@ -176,108 +161,42 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo if (entity instanceof LivingEntity living) { int eyeOffset = (int) ((entity.getEyeHeight()) * scale); if (trackMouse.get()) { - renderEntityInInventoryFollowsMouse(render, xPos, yPos, scale, force2dSize, xPos - (float) mouseX, yPos - (float) mouseY - eyeOffset, living); + InventoryScreen.renderEntityInInventoryFollowsMouse( + graphics, + (int) rect.x(), (int) rect.y(), + (int) rect.xMax(), (int) rect.yMax(), + (int) scale, + 0f, + (float) mouseX, + (float) mouseY - eyeOffset, + living + ); } else { - renderEntityInInventoryWithRotation(render, xPos, yPos, scale, force2dSize, rotation, living); + // TODO always tracks mouse for now, need math + InventoryScreen.renderEntityInInventoryFollowsMouse( + graphics, + (int) rect.x(), (int) rect.y(), + (int) rect.xMax(), (int) rect.yMax(), + (int) scale, + 0f, + (float) mouseX, + (float) mouseY - eyeOffset, + living + ); } } else { - Quaternionf quaternionf = new Quaternionf().rotateZ((float) Math.PI); - Quaternionf quaternionf1 = Axis.YP.rotationDegrees(rotation); - quaternionf.mul(quaternionf1); - renderEntityInInventory(render, xPos, yPos, scale, force2dSize, quaternionf, quaternionf1, entity); + // TODO not supported without custom submit. +// Quaternionf quaternionf = new Quaternionf().rotateZ((float) Math.PI); +// Quaternionf quaternionf1 = Axis.YP.rotationDegrees(rotation); +// quaternionf.mul(quaternionf1); +// renderEntityInInventory(graphics, xPos, yPos, scale, force2dSize, quaternionf, quaternionf1, entity); } } } catch (Throwable e) { invalidEntity = true; invalidEntities.add(entityName); LOGGER.error("Failed to render entity in GUI. This is not a bug there are just some entities that can not be rendered like this."); - LOGGER.error("Entity: " + entity, e); + LOGGER.error("Entity: {}", entity, e); } } - - public static void renderEntityInInventoryFollowsMouse(GuiRender render, double pX, double pY, double pScale, float offsetX, float offsetY, LivingEntity pEntity) { - renderEntityInInventoryFollowsMouse(render, pX, pY, pScale, false, offsetX, offsetY, pEntity); - } - - public static void renderEntityInInventoryFollowsMouse(GuiRender render, double pX, double pY, double pScale, boolean flat, float offsetX, float offsetY, LivingEntity pEntity) { - float xAngle = (float) Math.atan(offsetX / 40.0F); - float yAngle = (float) Math.atan(offsetY / 40.0F); - renderEntityInInventoryFollowsAngle(render, pX, pY, pScale, flat, xAngle, yAngle, pEntity); - } - - public static void renderEntityInInventoryFollowsAngle(GuiRender render, double pX, double pY, double pScale, float angleX, float angleY, LivingEntity pEntity) { - renderEntityInInventoryFollowsAngle(render, pX, pY, pScale, false, angleX, angleY, pEntity); - } - - public static void renderEntityInInventoryFollowsAngle(GuiRender render, double pX, double pY, double pScale, boolean flat, float angleX, float angleY, LivingEntity pEntity) { - Quaternionf quaternionf = (new Quaternionf()).rotateZ((float) Math.PI); - Quaternionf quaternionf1 = (new Quaternionf()).rotateX(angleY * 20.0F * ((float) Math.PI / 180F)); - quaternionf.mul(quaternionf1); - float f2 = pEntity.yBodyRot; - float f3 = pEntity.getYRot(); - float f4 = pEntity.getXRot(); - float f5 = pEntity.yHeadRotO; - float f6 = pEntity.yHeadRot; - pEntity.yBodyRot = 180.0F + angleX * 20.0F; - pEntity.setYRot(180.0F + angleX * 40.0F); - pEntity.setXRot(-angleY * 20.0F); - pEntity.yHeadRot = pEntity.getYRot(); - pEntity.yHeadRotO = pEntity.getYRot(); - renderEntityInInventory(render, pX, pY, pScale, flat, quaternionf, quaternionf1, pEntity); - pEntity.yBodyRot = f2; - pEntity.setYRot(f3); - pEntity.setXRot(f4); - pEntity.yHeadRotO = f5; - pEntity.yHeadRot = f6; - } - - public static void renderEntityInInventoryWithRotation(GuiRender render, double xPos, double yPos, double scale, double rotation, LivingEntity living) { - renderEntityInInventoryWithRotation(render, xPos, yPos, scale, false, rotation, living); - } - - public static void renderEntityInInventoryWithRotation(GuiRender render, double xPos, double yPos, double scale, boolean flat, double rotation, LivingEntity living) { - Quaternionf quaternionf = new Quaternionf().rotateZ((float) Math.PI); - Quaternionf quaternionf1 = Axis.YP.rotationDegrees((float) rotation); - quaternionf.mul(quaternionf1); - float f2 = living.yBodyRot; - float f3 = living.getYRot(); - float f4 = living.getXRot(); - float f5 = living.yHeadRotO; - float f6 = living.yHeadRot; - living.yBodyRot = 180.0F; - living.setYRot(180.0F); - living.setXRot(0); - living.yHeadRot = living.getYRot(); - living.yHeadRotO = living.getYRot(); - renderEntityInInventory(render, xPos, yPos, scale, flat, quaternionf, quaternionf1, living); - living.yBodyRot = f2; - living.setYRot(f3); - living.setXRot(f4); - living.yHeadRotO = f5; - living.yHeadRot = f6; - } - - public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, Entity pEntity) { - renderEntityInInventory(render, pX, pY, pScale, false, quat, pCameraOrientation, pEntity); - } - - public static void renderEntityInInventory(GuiRender render, double pX, double pY, double pScale, boolean flat, Quaternionf quat, @Nullable Quaternionf pCameraOrientation, Entity pEntity) { - render.pose().pushPose(); - render.pose().translate(pX, pY, 50.0D); - render.pose().scale((float) pScale, (float) pScale, flat ? -1 : (float) (-pScale)); - render.pose().mulPose(quat); - Lighting.setupForEntityInInventory(); - EntityRenderDispatcher entityrenderdispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); - if (pCameraOrientation != null) { - pCameraOrientation.conjugate(); - entityrenderdispatcher.overrideCameraOrientation(pCameraOrientation); - } - - entityrenderdispatcher.setRenderShadow(false); - RenderSystem.runAsFancy(() -> entityrenderdispatcher.render(pEntity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F, render.pose(), render.buffers(), 15728880)); - render.flush(); - entityrenderdispatcher.setRenderShadow(true); - render.pose().popPose(); - Lighting.setupFor3DItems(); - } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java index 9ff6c5d2..59368659 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java @@ -1,29 +1,29 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import org.apache.logging.log4j.util.TriConsumer; -import org.jetbrains.annotations.NotNull; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; import java.util.ArrayList; import java.util.List; -import java.util.function.BiConsumer; +import java.util.function.Consumer; /** * Created by brandon3055 on 15/11/2023 */ -// TODO Replace TriConsumer. public class GuiEventProvider extends GuiElement { private boolean ignoreConsumed = false; - private final List> clickListeners = new ArrayList<>(); - private final List> releaseListeners = new ArrayList<>(); - private final List> movedListeners = new ArrayList<>(); + private final List> clickListeners = new ArrayList<>(); + private final List> releaseListeners = new ArrayList<>(); + private final List movedListeners = new ArrayList<>(); private final List scrollListeners = new ArrayList<>(); - private final List> keyPressListeners = new ArrayList<>(); - private final List> keyReleaseListeners = new ArrayList<>(); - private final List> charTypedListeners = new ArrayList<>(); + private final List> keyPressListeners = new ArrayList<>(); + private final List> keyReleaseListeners = new ArrayList<>(); + private final List> charTypedListeners = new ArrayList<>(); - public GuiEventProvider(@NotNull GuiParent parent) { + public GuiEventProvider(GuiParent parent) { super(parent); } @@ -32,17 +32,17 @@ public GuiEventProvider setIgnoreConsumed(boolean ignoreConsumed) { return this; } - public GuiEventProvider onMouseClick(TriConsumer listener) { + public GuiEventProvider onMouseClick(Consumer listener) { clickListeners.add(listener); return this; } - public GuiEventProvider onMouseRelease(TriConsumer listener) { + public GuiEventProvider onMouseRelease(Consumer listener) { releaseListeners.add(listener); return this; } - public GuiEventProvider onMouseMove(BiConsumer listener) { + public GuiEventProvider onMouseMove(MouseMoveListener listener) { movedListeners.add(listener); return this; } @@ -52,40 +52,40 @@ public GuiEventProvider onScroll(ScrollListener listener) { return this; } - public GuiEventProvider onKeyPress(TriConsumer listener) { + public GuiEventProvider onKeyPress(Consumer listener) { keyPressListeners.add(listener); return this; } - public GuiEventProvider onKeyRelease(TriConsumer listener) { + public GuiEventProvider onKeyRelease(Consumer listener) { keyReleaseListeners.add(listener); return this; } - public GuiEventProvider onCharTyped(BiConsumer listener) { + public GuiEventProvider onCharTyped(Consumer listener) { charTypedListeners.add(listener); return this; } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { if (ignoreConsumed || !consumed) { - clickListeners.forEach(e -> e.accept(mouseX, mouseY, button)); + clickListeners.forEach(e -> e.accept(event)); } - return super.mouseClicked(mouseX, mouseY, button, consumed); + return super.mouseClicked(event, consumed); } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { if (ignoreConsumed || !consumed) { - releaseListeners.forEach(e -> e.accept(mouseX, mouseY, button)); + releaseListeners.forEach(e -> e.accept(event)); } - return super.mouseReleased(mouseX, mouseY, button, consumed); + return super.mouseReleased(event, consumed); } @Override public void mouseMoved(double mouseX, double mouseY) { - movedListeners.forEach(e -> e.accept(mouseX, mouseY)); + movedListeners.forEach(e -> e.onMoved(mouseX, mouseY)); super.mouseMoved(mouseX, mouseY); } @@ -98,27 +98,32 @@ public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, doubl } @Override - public boolean keyPressed(int key, int scancode, int modifiers, boolean consumed) { + public boolean keyPressed(KeyEvent event, boolean consumed) { if (ignoreConsumed || !consumed) { - keyPressListeners.forEach(e -> e.accept(key, scancode, modifiers)); + keyPressListeners.forEach(e -> e.accept(event)); } - return super.keyPressed(key, scancode, modifiers, consumed); + return super.keyPressed(event, consumed); } @Override - public boolean keyReleased(int key, int scancode, int modifiers, boolean consumed) { + public boolean keyReleased(KeyEvent event, boolean consumed) { if (ignoreConsumed || !consumed) { - keyReleaseListeners.forEach(e -> e.accept(key, scancode, modifiers)); + keyReleaseListeners.forEach(e -> e.accept(event)); } - return super.keyReleased(key, scancode, modifiers, consumed); + return super.keyReleased(event, consumed); } @Override - public boolean charTyped(char character, int modifiers, boolean consumed) { + public boolean charTyped(CharacterEvent event, boolean consumed) { if (ignoreConsumed || !consumed) { - charTypedListeners.forEach(e -> e.accept(character, modifiers)); + charTypedListeners.forEach(e -> e.accept(event)); } - return super.charTyped(character, modifiers, consumed); + return super.charTyped(event, consumed); + } + + public interface MouseMoveListener { + + void onMoved(double mouseX, double mouseY); } public interface ScrollListener { diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java index f880bf02..46b58f06 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java @@ -1,253 +1,251 @@ -package codechicken.lib.gui.modular.elements; - -import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.Constraints; -import codechicken.lib.gui.modular.lib.GuiRender; -import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.GuiTextures; -import codechicken.lib.gui.modular.sprite.Material; -import codechicken.lib.util.FormatUtil; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.Style; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.Fluids; -import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; -import net.neoforged.neoforge.fluids.FluidStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Supplier; - -import static net.minecraft.ChatFormatting.*; - -/** - * When implementing this tank, you must specify the tank capacity in mb, - * And then you have two options for specifying the tank contents. - * You can set the fluid and the amount stored, - * Or you can provide a {@link FluidStack} - *

    - * Created by brandon3055 on 11/09/2023 - */ -public class GuiFluidTank extends GuiElement implements BackgroundRender { - - //TODO make a better texture, This feels a little too.. cluttered. - public static final Material DEFAULT_WINDOW = GuiTextures.CCL.getUncached("widgets/tank_window"); - - private int gaugeColour = 0xFF909090; - private boolean drawGauge = true; - private Material window = null; - private Supplier capacity = () -> 10000L; - private Supplier fluidStack = () -> FluidStack.EMPTY; - - private BiFunction> toolTipFormatter; - - public GuiFluidTank(@NotNull GuiParent parent) { - super(parent); - setTooltipDelay(0); - setToolTipFormatter(defaultFormatter()); - } - - /** - * Creates a simple tank using a simple slot as a background to make it look nice. - */ - public static FluidTank simpleTank(@NotNull GuiParent parent) { - GuiRectangle container = GuiRectangle.vanillaSlot(parent); - GuiFluidTank energyBar = new GuiFluidTank(container); - Constraints.bind(energyBar, container, 1); - return new FluidTank(container, energyBar); - } - - /** - * Sets the capacity of this tank in milli-buckets. - */ - public GuiFluidTank setCapacity(long capacity) { - return setCapacity(() -> capacity); - } - - /** - * Supply the capacity of this tank in milli-buckets. - */ - public GuiFluidTank setCapacity(Supplier capacity) { - this.capacity = capacity; - return this; - } - - /** - * Allows you to set the current stored fluid stack. - */ - public GuiFluidTank setFluidStack(FluidStack fluidStack) { - return setFluidStack(() -> fluidStack); - } - - /** - * Allows you to supply the current stored fluid stack. - */ - public GuiFluidTank setFluidStack(Supplier fluidStack) { - this.fluidStack = fluidStack; - return this; - } - - /** - * Install a custom formatter to control how the fluid tool tip renders. - */ - public GuiFluidTank setToolTipFormatter(BiFunction> toolTipFormatter) { - this.toolTipFormatter = toolTipFormatter; - setTooltip(() -> this.toolTipFormatter.apply(getFluidStack(), getCapacity())); - return this; - } - - /** - * Sets the tank window texture, Will be tiled to fit the tank size. - * - * @param window New window texture or null for no window texture. - */ - public GuiFluidTank setWindow(@Nullable Material window) { - this.window = window; - return this; - } - - /** - * Enable the built-in fluid gauge lines. - */ - public GuiFluidTank setDrawGauge(boolean drawGauge) { - this.drawGauge = drawGauge; - return this; - } - - /** - * Sets the colour of the built-in fluid gauge lines - */ - public GuiFluidTank setGaugeColour(int gaugeColour) { - this.gaugeColour = gaugeColour; - return this; - } - - public Long getCapacity() { - return capacity.get(); - } - - public FluidStack getFluidStack() { - return fluidStack.get(); - } - - @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { - FluidStack stack = getFluidStack(); - Material fluidMat = Material.fromSprite(getStillTexture(stack)); - - if (!stack.isEmpty() && fluidMat != null) { - int fluidColor = getColour(stack); - float height = getCapacity() <= 0 ? 0 : (float) ySize() * (stack.getAmount() / (float) getCapacity()); - render.tileSprite(fluidMat.renderType(GuiRender::texColType), xMin(), yMax() - height, xMax(), yMax(), fluidMat.sprite(), fluidColor); - } - - if (window != null) { - render.tileSprite(window.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), window.sprite(), 0xFFFFFFFF); - } - - gaugeColour = 0xFF000000; - if (drawGauge) { - double spacing = computeGaugeSpacing(); - if (spacing == 0) return; - - double pos = spacing; - while (pos + 1 < ySize()) { - double width = xSize() / 4; - double yPos = yMax() - 1 - pos; - render.fill(xMax() - width, yPos, xMax(), yPos + 1, gaugeColour); - pos += spacing; - } - } - } - - private double computeGaugeSpacing() { - double ySize = ySize(); - double capacity = getCapacity(); - if (ySize / (capacity / 100D) > 3) return ySize / (capacity / 100D); - if (ySize / (capacity / 500D) > 3) return ySize / (capacity / 500D); - if (ySize / (capacity / 1000D) > 3) return ySize / (capacity / 1000D); - if (ySize / (capacity / 5000D) > 3) return ySize / (capacity / 5000D); - if (ySize / (capacity / 10000D) > 3) return ySize / (capacity / 10000D); - if (ySize / (capacity / 50000D) > 3) return ySize / (capacity / 50000D); - if (ySize / (capacity / 100000D) > 3) return ySize / (capacity / 100000D); - return 0; - } - - public static BiFunction> defaultFormatter() { - return (fluidStack, capacity) -> { - List tooltip = new ArrayList<>(); - tooltip.add(Component.translatable("ccl.fluid_tank.fluid_storage").withStyle(DARK_AQUA)); - if (!fluidStack.isEmpty()) { - tooltip.add(Component.translatable("ccl.fluid_tank.contains") - .withStyle(GOLD) - .append(" ") - .append(fluidStack.getDisplayName().copy() - .setStyle(Style.EMPTY - .withColor(getColour(fluidStack)) - ) - ) - ); - } - - tooltip.add(Component.translatable("ccl.fluid_tank.capacity") - .withStyle(GOLD) - .append(" ") - .append(Component.literal(FormatUtil.addCommas(capacity)) - .withStyle(GRAY) - .append(" ") - .append(Component.translatable("ccl.fluid_tank.mb") - .withStyle(GRAY) - ) - ) - ); - tooltip.add(Component.translatable("ccl.fluid_tank.stored") - .withStyle(GOLD) - .append(" ") - .append(Component.literal(FormatUtil.addCommas(fluidStack.getAmount())) - .withStyle(GRAY) - ) - .append(" ") - .append(Component.translatable("ccl.fluid_tank.mb") - .withStyle(GRAY) - ) - .append(Component.literal(String.format(" (%.2f%%)", ((double) fluidStack.getAmount() / (double) capacity) * 100D)) - .withStyle(GRAY) - ) - ); - return tooltip; - }; - } - - //TODO These could maybe go in FluidUtils? but they are client side only so... - - public static int getColour(FluidStack fluidStack) { - return fluidStack.getFluid() == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluidStack.getFluid()).getTintColor(fluidStack); - } - - public static int getColour(Fluid fluid) { - return fluid == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluid).getTintColor(); - } - - @Nullable - public static TextureAtlasSprite getStillTexture(FluidStack stack) { - if (stack.getFluid() == Fluids.EMPTY) return null; - ResourceLocation texture = IClientFluidTypeExtensions.of(stack.getFluid()).getStillTexture(stack); - return Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(texture); - } - - @Nullable - public static TextureAtlasSprite getStillTexture(Fluid fluid) { - if (fluid == Fluids.EMPTY) return null; - ResourceLocation texture = IClientFluidTypeExtensions.of(fluid).getStillTexture(); - return Minecraft.getInstance().getTextureAtlas(TextureAtlas.LOCATION_BLOCKS).apply(texture); - } - - public record FluidTank(GuiRectangle container, GuiFluidTank tank) { } -} +//package codechicken.lib.gui.modular.elements; +// +//import codechicken.lib.gui.modular.lib.BackgroundRender; +//import codechicken.lib.gui.modular.lib.Constraints; +//import codechicken.lib.gui.modular.lib.geometry.GuiParent; +//import codechicken.lib.gui.modular.sprite.GuiTextures; +//import codechicken.lib.gui.modular.sprite.SpriteSupplier; +//import codechicken.lib.util.FormatUtil; +//import net.minecraft.client.Minecraft; +//import net.minecraft.client.gui.GuiGraphics; +//import net.minecraft.client.renderer.texture.TextureAtlasSprite; +//import net.minecraft.network.chat.Component; +//import net.minecraft.network.chat.Style; +//import net.minecraft.resources.ResourceLocation; +//import net.minecraft.world.level.material.Fluid; +//import net.minecraft.world.level.material.Fluids; +//import net.neoforged.neoforge.client.ClientHooks; +//import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +//import net.neoforged.neoforge.fluids.FluidStack; +//import org.jetbrains.annotations.Nullable; +// +//import java.util.ArrayList; +//import java.util.List; +//import java.util.function.BiFunction; +//import java.util.function.Supplier; +// +//import static net.minecraft.ChatFormatting.*; +// +///** +// * When implementing this tank, you must specify the tank capacity in mb, +// * And then you have two options for specifying the tank contents. +// * You can set the fluid and the amount stored, +// * Or you can provide a {@link FluidStack} +// *

    +// * Created by brandon3055 on 11/09/2023 +// */ +//public class GuiFluidTank extends GuiElement implements BackgroundRender { +// +// //TODO make a better texture, This feels a little too.. cluttered. +// public static final SpriteSupplier DEFAULT_WINDOW = GuiTextures.CCL.get("widgets/tank_window"); +// +// private int gaugeColour = 0xFF909090; +// private boolean drawGauge = true; +// private SpriteSupplier window = SpriteSupplier.EMPTY; +// private Supplier capacity = () -> 10000L; +// private Supplier fluidStack = () -> FluidStack.EMPTY; +// +// private BiFunction> toolTipFormatter; +// +// public GuiFluidTank(GuiParent parent) { +// super(parent); +// setTooltipDelay(0); +// setToolTipFormatter(defaultFormatter()); +// } +// +// /** +// * Creates a simple tank using a simple slot as a background to make it look nice. +// */ +// public static FluidTank simpleTank(GuiParent parent) { +// GuiRectangle container = GuiRectangle.vanillaSlot(parent); +// GuiFluidTank energyBar = new GuiFluidTank(container); +// Constraints.bind(energyBar, container, 1); +// return new FluidTank(container, energyBar); +// } +// +// /** +// * Sets the capacity of this tank in milli-buckets. +// */ +// public GuiFluidTank setCapacity(long capacity) { +// return setCapacity(() -> capacity); +// } +// +// /** +// * Supply the capacity of this tank in milli-buckets. +// */ +// public GuiFluidTank setCapacity(Supplier capacity) { +// this.capacity = capacity; +// return this; +// } +// +// /** +// * Allows you to set the current stored fluid stack. +// */ +// public GuiFluidTank setFluidStack(FluidStack fluidStack) { +// return setFluidStack(() -> fluidStack); +// } +// +// /** +// * Allows you to supply the current stored fluid stack. +// */ +// public GuiFluidTank setFluidStack(Supplier fluidStack) { +// this.fluidStack = fluidStack; +// return this; +// } +// +// /** +// * Install a custom formatter to control how the fluid tool tip renders. +// */ +// public GuiFluidTank setToolTipFormatter(BiFunction> toolTipFormatter) { +// this.toolTipFormatter = toolTipFormatter; +// setTooltip(() -> this.toolTipFormatter.apply(getFluidStack(), getCapacity())); +// return this; +// } +// +// /** +// * Sets the tank window texture, Will be tiled to fit the tank size. +// * +// * @param window New window texture or null for no window texture. +// */ +// public GuiFluidTank setWindow(SpriteSupplier window) { +// this.window = window; +// return this; +// } +// +// /** +// * Enable the built-in fluid gauge lines. +// */ +// public GuiFluidTank setDrawGauge(boolean drawGauge) { +// this.drawGauge = drawGauge; +// return this; +// } +// +// /** +// * Sets the colour of the built-in fluid gauge lines +// */ +// public GuiFluidTank setGaugeColour(int gaugeColour) { +// this.gaugeColour = gaugeColour; +// return this; +// } +// +// public Long getCapacity() { +// return capacity.get(); +// } +// +// public FluidStack getFluidStack() { +// return fluidStack.get(); +// } +// +// @Override +// public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { +// FluidStack stack = getFluidStack(); +// var fluidStill = getStillTexture(stack); +// +// if (!stack.isEmpty() && fluidStill != null) { +// int fluidColor = getColour(stack); +// float height = getCapacity() <= 0 ? 0 : (float) ySize() * (stack.getAmount() / (float) getCapacity()); +// graphics.tileSprite(fluidStill.renderType(GuiRender::texColType), xMin(), yMax() - height, xMax(), yMax(), fluidStill, fluidColor); +// } +// window.ifPresent(icon -> { +// graphics.tileSprite(window.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), icon, 0xFFFFFFFF); +// }); +// +// gaugeColour = 0xFF000000; +// if (drawGauge) { +// double spacing = computeGaugeSpacing(); +// if (spacing == 0) return; +// +// double pos = spacing; +// while (pos + 1 < ySize()) { +// double width = xSize() / 4; +// double yPos = yMax() - 1 - pos; +// graphics.cc$fill(xMax() - width, yPos, xMax(), yPos + 1, gaugeColour); +// pos += spacing; +// } +// } +// } +// +// private double computeGaugeSpacing() { +// double ySize = ySize(); +// double capacity = getCapacity(); +// if (ySize / (capacity / 100D) > 3) return ySize / (capacity / 100D); +// if (ySize / (capacity / 500D) > 3) return ySize / (capacity / 500D); +// if (ySize / (capacity / 1000D) > 3) return ySize / (capacity / 1000D); +// if (ySize / (capacity / 5000D) > 3) return ySize / (capacity / 5000D); +// if (ySize / (capacity / 10000D) > 3) return ySize / (capacity / 10000D); +// if (ySize / (capacity / 50000D) > 3) return ySize / (capacity / 50000D); +// if (ySize / (capacity / 100000D) > 3) return ySize / (capacity / 100000D); +// return 0; +// } +// +// public static BiFunction> defaultFormatter() { +// return (fluidStack, capacity) -> { +// List tooltip = new ArrayList<>(); +// tooltip.add(Component.translatable("ccl.fluid_tank.fluid_storage").withStyle(DARK_AQUA)); +// if (!fluidStack.isEmpty()) { +// tooltip.add(Component.translatable("ccl.fluid_tank.contains") +// .withStyle(GOLD) +// .append(" ") +// .append(fluidStack.getHoverName().copy() +// .setStyle(Style.EMPTY +// .withColor(getColour(fluidStack)) +// ) +// ) +// ); +// } +// +// tooltip.add(Component.translatable("ccl.fluid_tank.capacity") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(FormatUtil.addCommas(capacity)) +// .withStyle(GRAY) +// .append(" ") +// .append(Component.translatable("ccl.fluid_tank.mb") +// .withStyle(GRAY) +// ) +// ) +// ); +// tooltip.add(Component.translatable("ccl.fluid_tank.stored") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(FormatUtil.addCommas(fluidStack.getAmount())) +// .withStyle(GRAY) +// ) +// .append(" ") +// .append(Component.translatable("ccl.fluid_tank.mb") +// .withStyle(GRAY) +// ) +// .append(Component.literal(String.format(" (%.2f%%)", ((double) fluidStack.getAmount() / (double) capacity) * 100D)) +// .withStyle(GRAY) +// ) +// ); +// return tooltip; +// }; +// } +// +// //TODO These could maybe go in FluidUtils? but they are client side only so... +// +// public static int getColour(FluidStack fluidStack) { +// return fluidStack.getFluid() == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluidStack.getFluid()).getTintColor(fluidStack); +// } +// +// public static int getColour(Fluid fluid) { +// return fluid == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluid).getTintColor(); +// } +// +// @Nullable +// public static TextureAtlasSprite getStillTexture(FluidStack stack) { +// if (stack.getFluid() == Fluids.EMPTY) return null; +// ResourceLocation texture = IClientFluidTypeExtensions.of(stack.getFluid()).getStillTexture(stack); +// return Minecraft.getInstance().getAtlasManager().get(ClientHooks.getBlockMaterial(texture)); +// } +// +// @Nullable +// public static TextureAtlasSprite getStillTexture(Fluid fluid) { +// if (fluid == Fluids.EMPTY) return null; +// ResourceLocation texture = IClientFluidTypeExtensions.of(fluid).getStillTexture(); +// return Minecraft.getInstance().getAtlasManager().get(ClientHooks.getBlockMaterial(texture)); +// } +// +// public record FluidTank(GuiRectangle container, GuiFluidTank tank) { } +//} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java index 3e074eec..80235694 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java @@ -1,10 +1,12 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; -import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; @@ -24,16 +26,16 @@ public class GuiItemStack extends GuiElement implements Background private Supplier decorate = () -> true; private Supplier toolTip = () -> true; - public GuiItemStack(@NotNull GuiParent parent) { + public GuiItemStack(GuiParent parent) { this(parent, () -> ItemStack.EMPTY); } - public GuiItemStack(@NotNull GuiParent parent, ItemStack itemStack) { + public GuiItemStack(GuiParent parent, ItemStack itemStack) { super(parent); setStack(itemStack); } - public GuiItemStack(@NotNull GuiParent parent, Supplier provider) { + public GuiItemStack(GuiParent parent, Supplier provider) { super(parent); setStack(provider); } @@ -86,31 +88,36 @@ public GuiItemStack enableStackToolTip(Supplier enableToolTip) { //=== Internal methods ===// - public double getStackSize() { + private double getStackSize() { return Math.max(getValue(WIDTH), getValue(HEIGHT)); } @Override - public double getBackgroundDepth() { - return getStackSize() * 2; - } - - @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { ItemStack stack = this.stack.get(); if (stack.isEmpty()) return; - render.renderItem(stack, xMin(), yMin(), getStackSize(), (int) (xMin() + (xSize() * yMin()))); + // TODO size needs to be applied via pose transform + render.cc$renderItem(stack, xMin(), yMin(), (int) (xMin() + (xSize() * yMin()))); if (decorate.get()) { - render.renderItemDecorations(stack, xMin(), yMin(), getStackSize()); + render.cc$renderItemDecorations(Minecraft.getInstance().font, stack, xMin(), yMin()); } } @Override - public boolean renderOverlay(GuiRender render, double mouseX, double mouseY, float partialTicks, boolean consumed) { - if (super.renderOverlay(render, mouseX, mouseY, partialTicks, consumed)) return true; - if (isMouseOver() && !stack.get().isEmpty() && toolTip.get()) { - render.renderTooltip(stack.get(), mouseX, mouseY); + public boolean renderOverlay(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks, boolean consumed) { + if (super.renderOverlay(graphics, mouseX, mouseY, partialTicks, consumed)) return true; + var stack = this.stack.get(); + if (isMouseOver() && !stack.isEmpty() && toolTip.get()) { + graphics.setTooltipForNextFrame( + font(), + Screen.getTooltipFromItem(Minecraft.getInstance(), stack), + stack.getTooltipImage(), + stack, + (int) mouseX, + (int) mouseY, + stack.get(DataComponents.TOOLTIP_STYLE) + ); return true; } return false; diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java index fe26fb75..44158abc 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java @@ -1,11 +1,10 @@ package codechicken.lib.gui.modular.elements; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.SliderState; import codechicken.lib.gui.modular.lib.geometry.*; import codechicken.lib.math.MathHelper; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.BiFunction; @@ -53,9 +52,8 @@ public class GuiList extends GuiElement> { return text; }; - public GuiList(@NotNull GuiParent parent) { + public GuiList(GuiParent parent) { super(parent); - this.setZStacking(false); this.setRenderCull(getRectangle()); } @@ -226,9 +224,9 @@ public boolean blockMouseOver(GuiElement element, double mouseX, double mouse } @Override - public void render(GuiRender render, double mouseX, double mouseY, float partialTicks) { - if (enableScissor) render.pushScissorRect(getRectangle()); + public void render(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + if (enableScissor) render.cc$enableScissor(getRectangle()); super.render(render, mouseX, mouseY, partialTicks); - if (enableScissor) render.popScissor(); + if (enableScissor) render.cc$disableScissor(); } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java index 336dacdc..ee532a1f 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java @@ -8,7 +8,7 @@ import codechicken.lib.gui.modular.lib.geometry.Rectangle; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import org.jetbrains.annotations.NotNull; +import net.minecraft.client.input.MouseButtonEvent; import org.jetbrains.annotations.Nullable; import java.util.function.Consumer; @@ -34,6 +34,7 @@ * Created by brandon3055 on 13/11/2023 */ public class GuiManipulable extends GuiElement implements ContentElement> { + private final GuiElement contentElement; private int dragXOffset = 0; @@ -84,7 +85,7 @@ public class GuiManipulable extends GuiElement implements Conten private GuiElement topHandle; private GuiElement bottomHandle; - public GuiManipulable(@NotNull GuiParent parent) { + public GuiManipulable(GuiParent parent) { super(parent); this.contentElement = new ContentElement(this) .constrain(LEFT, Constraint.dynamic(() -> (double) xMin)) @@ -99,10 +100,10 @@ public GuiManipulable(@NotNull GuiParent parent) { } public GuiManipulable resetBounds() { - xMin = (int)xMin(); - xMax = (int)xMax(); - yMin = (int)yMin(); - yMax = (int)yMax(); + xMin = (int) xMin(); + xMax = (int) xMax(); + yMin = (int) yMin(); + yMax = (int) yMax(); return this; } @@ -297,7 +298,6 @@ public Rectangle getMaxSize() { return maxSize; } - @Override public void tick(double mouseX, double mouseY) { if (enableCursors) { @@ -382,7 +382,7 @@ public void mouseMoved(double mouseX, double mouseY) { } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { if (isMoving()) { validatePosition(true); onMoved(true); @@ -391,7 +391,7 @@ public boolean mouseReleased(double mouseX, double mouseY, int button, boolean c onResized(true); } isDragging = dragPos = dragTop = dragLeft = dragBottom = dragRight = false; - return super.mouseReleased(mouseX, mouseY, button, consumed); + return super.mouseReleased(event, consumed); } protected void validatePosition(boolean finished) { @@ -424,18 +424,19 @@ public boolean isResizing() { } public interface PositionRestraint { + void restrainPosition(GuiManipulable draggable); } private class ContentElement extends GuiElement { - public ContentElement(@NotNull GuiParent parent) { + public ContentElement(GuiParent parent) { super(parent); } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (super.mouseClicked(mouseX, mouseY, button)) return true; + public boolean mouseClicked(MouseButtonEvent event) { + if (super.mouseClicked(event)) return true; boolean posFlag = moveHandle != null && moveHandle.isMouseOver(); boolean topFlag = topHandle != null && topHandle.isMouseOver(); @@ -444,8 +445,8 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { boolean rightFlag = rightHandle != null && rightHandle.isMouseOver(); if (posFlag || topFlag || leftFlag || bottomFlag || rightFlag) { - dragXOffset = (int) (mouseX - xMin); - dragYOffset = (int) (mouseY - yMin); + dragXOffset = (int) (event.x() - xMin); + dragYOffset = (int) (event.y() - yMin); isDragging = true; if (posFlag) { dragPos = true; diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java index 47a0caf0..82294538 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java @@ -1,14 +1,13 @@ package codechicken.lib.gui.modular.elements; - import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.Axis; import codechicken.lib.gui.modular.lib.geometry.Direction; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.Material; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import codechicken.lib.gui.modular.SpriteSupplier; +import codechicken.lib.math.MathHelper; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderPipelines; import java.util.function.Supplier; @@ -25,36 +24,26 @@ */ public class GuiProgressIcon extends GuiElement implements BackgroundRender { - private Supplier background = null; - private Supplier animated; + private SpriteSupplier background = SpriteSupplier.EMPTY; + private SpriteSupplier animated = SpriteSupplier.EMPTY; private Supplier progress = () -> 0D; private boolean rotateToDirection = true; private Direction direction = Direction.RIGHT; - public GuiProgressIcon(@NotNull GuiParent parent, Supplier animated) { - super(parent); - this.animated = animated; + public GuiProgressIcon(GuiParent parent) { + this(parent, SpriteSupplier.EMPTY, SpriteSupplier.EMPTY); } - public GuiProgressIcon(@NotNull GuiParent parent, Material animated) { - this(parent, () -> animated); + public GuiProgressIcon(GuiParent parent, SpriteSupplier animated) { + this(parent, SpriteSupplier.EMPTY, animated); } - public GuiProgressIcon(@NotNull GuiParent parent, Supplier background, Supplier animated) { + public GuiProgressIcon(GuiParent parent, SpriteSupplier background, SpriteSupplier animated) { super(parent); this.background = background; this.animated = animated; } - public GuiProgressIcon(@NotNull GuiParent parent, Material background, Material animated) { - this(parent, () -> background, () -> animated); - } - - - public GuiProgressIcon(@NotNull GuiParent parent) { - super(parent); - } - /** * The expected default direction for a progress texture is left-to-right e.g. furnace arrow. * The texture will then be rotated to the direction specified via {@link #setDirection(Direction)} @@ -76,15 +65,7 @@ public GuiProgressIcon setDirection(Direction direction) { /** * Sets the background texture, aka the "empty" texture. */ - public GuiProgressIcon setBackground(@Nullable Material background) { - this.background = () -> background; - return this; - } - - /** - * Sets the background texture, aka the "empty" texture. - */ - public GuiProgressIcon setBackground(@Nullable Supplier background) { + public GuiProgressIcon setBackground(SpriteSupplier background) { this.background = background; return this; } @@ -92,15 +73,7 @@ public GuiProgressIcon setBackground(@Nullable Supplier background) { /** * Sets the texture that will be animated. */ - public GuiProgressIcon setAnimated(Material animated) { - this.animated = () -> animated; - return this; - } - - /** - * Sets the texture that will be animated. - */ - public GuiProgressIcon setAnimated(Supplier animated) { + public GuiProgressIcon setAnimated(SpriteSupplier animated) { this.animated = animated; return this; } @@ -127,39 +100,40 @@ public double getProgress() { } @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { if (rotateToDirection) { - render.pose().pushPose(); + graphics.pose().pushMatrix(); double width = direction.getAxis() == Axis.X ? xSize() : ySize(); double height = direction.getAxis() == Axis.X ? ySize() : xSize(); - render.pose().translate(xMin() + (xSize() / 2), yMin() + (ySize() / 2), 0); - render.pose().mulPose(com.mojang.math.Axis.ZP.rotationDegrees((float) Direction.RIGHT.rotationTo(direction))); + graphics.pose().translate((float) (xMin() + (xSize() / 2)), (float) (yMin() + (ySize() / 2))); + graphics.pose().rotate((float) (Direction.RIGHT.rotationTo(direction) * MathHelper.torad)); double halfWidth = width / 2; double halfHeight = height / 2; - if (background != null && background.get() != null) { - render.tex(background.get(), -halfWidth, -halfHeight, halfWidth, halfHeight, 0xFFFFFFFF); - } - - if (animated == null || animated.get() == null) return; - float progress = (float) getProgress(); - render.partialSprite(animated.get().renderType(GuiRender::texColType), -halfWidth, -halfHeight, -halfWidth + (width * progress), -halfHeight + height, animated.get().sprite(), 0F, 0F, progress, 1F, 0xFFFFFFFF); - - render.pose().popPose(); + background.ifPresent(sprite -> { + graphics.cc$blitSprite(RenderPipelines.GUI_TEXTURED, sprite, -halfWidth, -halfHeight, halfWidth, halfHeight); + }); + + animated.ifPresent(sprite -> { + float progress = (float) getProgress(); + graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, -halfWidth, -halfHeight, -halfWidth + (width * progress), -halfHeight + height, sprite, 0F, 0F, progress, 1F, 0xFFFFFFFF); + }); + graphics.pose().popMatrix(); } else { - if (background != null && background.get() != null) { - render.texRect(background.get(), getRectangle()); - } - if (animated == null || animated.get() == null) return; - float progress = (float) getProgress(); - switch (direction) { - case UP -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMin(), yMax() - (ySize() * progress), xMax(), yMax(), animated.get().sprite(), 0F, 1F - progress, 1F, 1F, 0xFFFFFFFF); - case LEFT -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMax() - (xSize() * progress), yMin(), xMax(), yMax(), animated.get().sprite(), 1F - progress, 0F, 1F, 1F, 0xFFFFFFFF); - case DOWN -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMin() + (ySize() * progress), animated.get().sprite(), 0F, 0F, 1F, progress, 0xFFFFFFFF); - case RIGHT -> render.partialSprite(animated.get().renderType(GuiRender::texColType), xMin(), yMin(), xMin() + (xSize() * progress), yMax(), animated.get().sprite(), 0F, 0F, progress, 1F, 0xFFFFFFFF); - } + background.ifPresent(sprite -> { + graphics.cc$blitSprite(RenderPipelines.GUI_TEXTURED, sprite, getRectangle()); + }); + animated.ifPresent(sprite -> { + float progress = (float) getProgress(); + switch (direction) { + case UP -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMin(), yMax() - (ySize() * progress), xMax(), yMax(), sprite, 0F, 1F - progress, 1F, 1F); + case LEFT -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMax() - (xSize() * progress), yMin(), xMax(), yMax(), sprite, 1F - progress, 0F, 1F, 1F); + case DOWN -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMin(), yMin(), xMax(), yMin() + (ySize() * progress), sprite, 0F, 0F, 1F, progress); + case RIGHT -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMin(), yMin(), xMin() + (xSize() * progress), yMax(), sprite, 0F, 0F, progress, 1F); + } + }); } } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java index 0d034702..d02209ad 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java @@ -1,11 +1,15 @@ package codechicken.lib.gui.modular.elements; +import codechicken.lib.colour.Colour; import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import org.jetbrains.annotations.NotNull; +import net.minecraft.client.gui.GuiGraphics; +import org.jetbrains.annotations.Nullable; -import java.util.function.Supplier; +import java.util.function.DoubleSupplier; +import java.util.function.IntSupplier; + +import static java.util.Objects.requireNonNull; /** * Used to draw a simple rectangle on the screen. @@ -15,19 +19,20 @@ * Created by brandon3055 on 28/08/2023 */ public class GuiRectangle extends GuiElement implements BackgroundRender { - private Supplier fill = null; - private Supplier border = null; - private Supplier borderWidth = () -> 1D; + private @Nullable IntSupplier fill = null; + private @Nullable IntSupplier border = null; + + private DoubleSupplier borderWidth = () -> 1D; - private Supplier shadeTopLeft; - private Supplier shadeBottomRight; - private Supplier shadeCorners; + private @Nullable IntSupplier shadeTopLeft; + private @Nullable IntSupplier shadeBottomRight; + private @Nullable IntSupplier shadeCorners; /** * @param parent parent {@link GuiParent}. */ - public GuiRectangle(@NotNull GuiParent parent) { + public GuiRectangle(GuiParent parent) { super(parent); } @@ -35,7 +40,7 @@ public GuiRectangle(@NotNull GuiParent parent) { * Creates a rectangle that mimics the appearance of a vanilla inventory slot. * Uses shadedRect to create the 3D "inset" look. */ - public static GuiRectangle vanillaSlot(@NotNull GuiParent parent) { + public static GuiRectangle vanillaSlot(GuiParent parent) { return new GuiRectangle(parent).shadedRect(0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); } @@ -43,30 +48,30 @@ public static GuiRectangle vanillaSlot(@NotNull GuiParent parent) { * Creates a rectangle that mimics the appearance of a vanilla inventory slot, except inverted * Uses shadedRect to create the 3D "popped out" appearance */ - public static GuiRectangle invertedSlot(@NotNull GuiParent parent) { + public static GuiRectangle invertedSlot(GuiParent parent) { return new GuiRectangle(parent).shadedRect(0xFFffffff, 0xFF373737, 0xFF8b8b8b, 0xFF8b8b8b); } /** * Creates a rectangle similar in appearance to a vanilla button, but with no texture and no black border. */ - public static GuiRectangle planeButton(@NotNull GuiParent parent) { + public static GuiRectangle planeButton(GuiParent parent) { return new GuiRectangle(parent).shadedRect(0xFFaaaaaa, 0xFF545454, 0xFF6f6f6f); } - public static GuiRectangle toolTipBackground(@NotNull GuiParent parent) { + public static GuiRectangle toolTipBackground(GuiParent parent) { return toolTipBackground(parent, 0xF0100010, 0x505000FF, 0x5028007f); } - public static GuiRectangle toolTipBackground(@NotNull GuiParent parent, int backgroundColour, int borderColourTop, int borderColourBottom) { + public static GuiRectangle toolTipBackground(GuiParent parent, int backgroundColour, int borderColourTop, int borderColourBottom) { return toolTipBackground(parent, backgroundColour, backgroundColour, borderColourTop, borderColourBottom); } - public static GuiRectangle toolTipBackground(@NotNull GuiParent parent, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom) { + public static GuiRectangle toolTipBackground(GuiParent parent, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom) { return new GuiRectangle(parent) { @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { - render.toolTipBackground(xMin(), yMin(), xSize(), ySize(), backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false); + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + graphics.cc$tooltipBackground(xMin(), yMin(), xSize(), ySize(), backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false); } }; } @@ -75,7 +80,7 @@ public GuiRectangle border(int border) { return border(() -> border); } - public GuiRectangle border(Supplier border) { + public GuiRectangle border(@Nullable IntSupplier border) { this.border = border; return this; } @@ -84,7 +89,7 @@ public GuiRectangle fill(int fill) { return fill(() -> fill); } - public GuiRectangle fill(Supplier fill) { + public GuiRectangle fill(IntSupplier fill) { this.fill = fill; return this; } @@ -93,7 +98,7 @@ public GuiRectangle rectangle(int fill, int border) { return rectangle(() -> fill, () -> border); } - public GuiRectangle rectangle(Supplier fill, Supplier border) { + public GuiRectangle rectangle(IntSupplier fill, IntSupplier border) { this.fill = fill; this.border = border; return this; @@ -103,15 +108,15 @@ public GuiRectangle shadedRect(int topLeft, int bottomRight, int fill) { return shadedRect(() -> topLeft, () -> bottomRight, () -> fill); } - public GuiRectangle shadedRect(Supplier topLeft, Supplier bottomRight, Supplier fill) { - return shadedRect(topLeft, bottomRight, () -> GuiRender.midColour(topLeft.get(), bottomRight.get()), fill); + public GuiRectangle shadedRect(IntSupplier topLeft, IntSupplier bottomRight, IntSupplier fill) { + return shadedRect(topLeft, bottomRight, () -> Colour.mid(topLeft.getAsInt(), bottomRight.getAsInt()), fill); } public GuiRectangle shadedRect(int topLeft, int bottomRight, int cornerMix, int fill) { return shadedRect(() -> topLeft, () -> bottomRight, () -> cornerMix, () -> fill); } - public GuiRectangle shadedRect(Supplier topLeft, Supplier bottomRight, Supplier cornerMix, Supplier fill) { + public GuiRectangle shadedRect(IntSupplier topLeft, IntSupplier bottomRight, IntSupplier cornerMix, IntSupplier fill) { this.fill = fill; this.shadeTopLeft = topLeft; this.shadeBottomRight = bottomRight; @@ -119,23 +124,27 @@ public GuiRectangle shadedRect(Supplier topLeft, Supplier bott return this; } - public GuiRectangle setShadeTopLeft(Supplier shadeTopLeft) { + public GuiRectangle setShadeTopLeft(IntSupplier shadeTopLeft) { this.shadeTopLeft = shadeTopLeft; return this; } - public GuiRectangle setShadeBottomRight(Supplier shadeBottomRight) { + public GuiRectangle setShadeBottomRight(IntSupplier shadeBottomRight) { this.shadeBottomRight = shadeBottomRight; return this; } - public GuiRectangle setShadeCorners(Supplier shadeCorners) { + public GuiRectangle setShadeCorners(IntSupplier shadeCorners) { this.shadeCorners = shadeCorners; return this; } public GuiRectangle setShadeCornersAuto() { - this.shadeCorners = () -> GuiRender.midColour(shadeTopLeft.get(), shadeBottomRight.get()); + this.shadeCorners = () -> { + var topLeft = requireNonNull(shadeTopLeft, "shadeTopLeft required for corners.").getAsInt(); + var bottomRight = requireNonNull(shadeBottomRight, "shadeBottomRight required for corners.").getAsInt(); + return Colour.mid(topLeft, bottomRight); + }; return this; } @@ -143,23 +152,23 @@ public GuiRectangle borderWidth(double borderWidth) { return borderWidth(() -> borderWidth); } - public GuiRectangle borderWidth(Supplier borderWidth) { + public GuiRectangle borderWidth(DoubleSupplier borderWidth) { this.borderWidth = borderWidth; return this; } public double getBorderWidth() { - return borderWidth.get(); + return borderWidth.getAsDouble(); } @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { if (shadeTopLeft != null && shadeBottomRight != null && shadeCorners != null) { - render.shadedRect(getRectangle(), getBorderWidth(), shadeTopLeft.get(), shadeBottomRight.get(), shadeCorners.get(), fill == null ? 0 : fill.get()); + render.cc$shadedRect(getRectangle(), getBorderWidth(), shadeTopLeft.getAsInt(), shadeBottomRight.getAsInt(), shadeCorners.getAsInt(), fill == null ? 0 : fill.getAsInt()); } else if (border != null) { - render.borderRect(getRectangle(), getBorderWidth(), fill == null ? 0 : fill.get(), border.get()); + render.cc$borderRect(getRectangle(), getBorderWidth(), fill == null ? 0 : fill.getAsInt(), border.getAsInt()); } else if (fill != null) { - render.rect(getRectangle(), fill.get()); + render.cc$fill(getRectangle(), fill.getAsInt()); } } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java index c0c5f9e0..24238383 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java @@ -2,14 +2,13 @@ import codechicken.lib.gui.modular.lib.Constraints; import codechicken.lib.gui.modular.lib.ContentElement; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.SliderState; import codechicken.lib.gui.modular.lib.geometry.Axis; import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GeoParam; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.math.MathHelper; -import org.jetbrains.annotations.NotNull; +import net.minecraft.client.gui.GuiGraphics; import org.jetbrains.annotations.Nullable; import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; @@ -49,7 +48,7 @@ public class GuiScrolling extends GuiElement implements ContentEle /** * @param parent parent {@link GuiParent}. */ - public GuiScrolling(@NotNull GuiParent parent) { + public GuiScrolling(GuiParent parent) { super(parent); installContainerElement(new ContentElement(this)); } @@ -153,19 +152,20 @@ public boolean blockMouseOver(GuiElement element, double mouseX, double mouse //=== Rendering ===// @Override - protected boolean renderChild(GuiElement child, GuiRender render, double mouseX, double mouseY, float partialTicks) { + protected boolean renderChild(GuiElement child, GuiGraphics render, double mouseX, double mouseY, float partialTicks) { boolean scissor = child == contentElement && enableScissor; - if (scissor) render.pushScissorRect(getRectangle()); + if (scissor) render.cc$enableScissor(getRectangle()); boolean ret = super.renderChild(child, render, mouseX, mouseY, partialTicks); - if (scissor) render.popScissor(); + if (scissor) render.cc$disableScissor(); return ret; } private class ContentElement extends GuiElement { + /** * @param parent parent {@link GuiParent}. */ - public ContentElement(@NotNull GuiParent parent) { + public ContentElement(GuiParent parent) { super(parent); } @@ -176,7 +176,7 @@ public ContentElement constrain(GeoParam param, @Nullable Constraint constraint) } } - public static ScrollWindow simpleScrollWindow(@NotNull GuiParent parent, boolean verticalScrollBar, boolean horizontalScrollBar) { + public static ScrollWindow simpleScrollWindow(GuiParent parent, boolean verticalScrollBar, boolean horizontalScrollBar) { GuiElement container = new GuiElement<>(parent); GuiRectangle background = GuiRectangle.vanillaSlot(container) .constrain(TOP, match(container.get(TOP))) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java index 13abc8c5..cb3763c3 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java @@ -1,9 +1,10 @@ package codechicken.lib.gui.modular.elements; -import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.SliderState; import codechicken.lib.gui.modular.lib.geometry.*; import codechicken.lib.math.MathHelper; -import org.jetbrains.annotations.NotNull; +import net.minecraft.client.input.MouseButtonEvent; import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; @@ -19,6 +20,7 @@ * Created by brandon3055 on 02/09/2023 */ public class GuiSlider extends GuiElement { + private final Axis axis; private SliderState state = SliderState.create(0.1); private GuiElement slider; @@ -43,7 +45,7 @@ public class GuiSlider extends GuiElement { * This includes a default slider element the width of which is bound to the GuiSlider, * And the length of which is controlled by {@link SliderState#sliderRatio()} */ - public GuiSlider(@NotNull GuiParent parent, Axis axis) { + public GuiSlider(GuiParent parent, Axis axis) { super(parent); this.axis = axis; installSlider(new GuiElement<>(this)); @@ -51,7 +53,7 @@ public GuiSlider(@NotNull GuiParent parent, Axis axis) { bindSliderWidth(); } - public GuiSlider(@NotNull GuiParent parent, Axis axis, GuiElement slider) { + public GuiSlider(GuiParent parent, Axis axis, GuiElement slider) { super(parent); this.axis = axis; installSlider(slider); @@ -198,28 +200,28 @@ public GuiSlider setScrollDragButton(int scrollDragButton) { } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { + public boolean mouseClicked(MouseButtonEvent event) { dragging = false; - clickPos = Position.create(mouseX, mouseY); + clickPos = Position.create(event.x(), event.y()); slideStartPos = state.getPos(); - if (button == dragButton && isMouseOver()) { + if (event.button() == dragButton && isMouseOver()) { if (!slider.isMouseOver()) { clickPos = Position.create(slider.xCenter(), slider.yCenter()); - handleDrag(mouseX, mouseY); + handleDrag(event.x(), event.y()); } dragging = true; return true; } - if (button == scrollDragButton && scrollableElement != null && scrollableElement.isMouseOver()) { + if (event.button() == scrollDragButton && scrollableElement != null && scrollableElement.isMouseOver()) { scrollableDragging = true; } return false; } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { dragging = scrollableDragging = false; - return super.mouseReleased(mouseX, mouseY, button, consumed); + return super.mouseReleased(event, consumed); } @Override @@ -262,5 +264,5 @@ public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, doubl return false; } - public record ScrollBar(GuiRectangle container, GuiSlider slider, GuiRectangle highlight) {} + public record ScrollBar(GuiRectangle container, GuiSlider slider, GuiRectangle highlight) { } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java index 93384352..934e691b 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -1,26 +1,29 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; import codechicken.lib.gui.modular.lib.container.SlotGroup; import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GeoParam; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.gui.modular.lib.geometry.Position; -import codechicken.lib.gui.modular.sprite.GuiTextures; -import codechicken.lib.gui.modular.sprite.Material; +import codechicken.lib.gui.modular.SpriteSupplier; +import codechicken.lib.math.MathHelper; import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.data.AtlasIds; +import net.minecraft.resources.Identifier; import net.minecraft.world.inventory.Slot; import org.apache.logging.log4j.util.TriConsumer; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.function.Function; +import static codechicken.lib.CodeChickenLib.MOD_ID; import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; import static codechicken.lib.gui.modular.lib.geometry.Constraint.relative; import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; -import static net.minecraft.world.inventory.InventoryMenu.BLOCK_ATLAS; /** * This element is used to manage and render a grid of inventory slots in a GUI. @@ -32,8 +35,14 @@ * Created by brandon3055 on 08/09/2023 */ public class GuiSlots extends GuiElement implements BackgroundRender { - public static final Material[] ARMOR_SLOTS = new Material[]{Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_helmet"), Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_chestplate"), Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_leggings"), Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_boots")}; - public static final Material OFF_HAND_SLOT = Material.fromAtlas(BLOCK_ATLAS, "item/empty_armor_slot_shield"); + + public static final SpriteSupplier[] ARMOR_SLOTS = new SpriteSupplier[] { + SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_helmet")), + SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_chestplate")), + SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_leggings")), + SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_boots")) + }; + public static final SpriteSupplier OFF_HAND_SLOT = SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_shield")); private final int firstSlot; private final int slotCount; @@ -41,10 +50,10 @@ public class GuiSlots extends GuiElement implements BackgroundRender { private final SlotGroup slots; private final ContainerScreenAccess screenAccess; - private Function slotTexture = slot -> GuiTextures.CCL.getUncached("widgets/slot"); - private Function slotIcons = slot -> null; + private Function slotTexture = slot -> SpriteSupplier.gui(Identifier.fromNamespaceAndPath(MOD_ID, "widgets/slot")); + private Function slotIcons = slot -> SpriteSupplier.EMPTY; private Function highlightColour = slot -> 0x80ffffff; - private TriConsumer slotOverlay = null; + private @Nullable TriConsumer slotOverlay = null; private int xSlotSpacing = 0; private int ySlotSpacing = 0; @@ -52,7 +61,7 @@ public class GuiSlots extends GuiElement implements BackgroundRender { * @param slots The slot group containing the slots that this element will manage. * @param gridColumns The width of the inventory grid (Typically 9 for standard player or chest inventories) */ - public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int gridColumns) { + public GuiSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int gridColumns) { this(parent, screenAccess, slots, 0, slots.size(), gridColumns); } @@ -62,7 +71,7 @@ public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAcc * @param slotCount The number of slots that this element will manage. * @param gridColumns The width of the inventory grid (Typically 9 for standard player or chest inventories) */ - public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int firstSlot, int slotCount, int gridColumns) { + public GuiSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int firstSlot, int slotCount, int gridColumns) { super(parent); this.screenAccess = screenAccess; this.slots = slots; @@ -82,28 +91,26 @@ public GuiSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAcc } updateSlots(parent.getModularGui().getRoot()); - setZStacking(false); } //=== Construction Helpers ===// - public static GuiSlots singleSlot(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots) { + public static GuiSlots singleSlot(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots) { return singleSlot(parent, screenAccess, slots, 0); } - public static GuiSlots singleSlot(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int index) { + public static GuiSlots singleSlot(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int index) { return new GuiSlots(parent, screenAccess, slots, index, 1, 1); } - public static Player player(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots) { + public static Player player(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots) { return player(parent, screenAccess, mainSlots, hotBarSlots, 3); } - public static Player player(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, int hotBarSpacing) { + public static Player player(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, int hotBarSpacing) { int width = 18 * 9; int height = 18 * 4 + hotBarSpacing; GuiElement container = new GuiElement<>(parent) - .setZStacking(false) .constrain(WIDTH, Constraint.literal(width)) .constrain(HEIGHT, Constraint.literal(height)); @@ -117,15 +124,14 @@ public static Player player(@NotNull GuiParent parent, ContainerScreenAccess< return new Player(container, main, bar); } - public static PlayerWithArmor playerWithArmor(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots) { + public static PlayerWithArmor playerWithArmor(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots) { return playerWithArmor(parent, screenAccess, mainSlots, hotBarSlots, armorSlots, 3, true); } - public static PlayerWithArmor playerWithArmor(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, int groupSpacing, boolean slotIcons) { + public static PlayerWithArmor playerWithArmor(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, int groupSpacing, boolean slotIcons) { int width = 18 * 10 + groupSpacing; int height = 18 * 4 + groupSpacing; GuiElement container = new GuiElement<>(parent) - .setZStacking(false) .constrain(WIDTH, Constraint.literal(width)) .constrain(HEIGHT, Constraint.literal(height)); @@ -146,15 +152,14 @@ public static PlayerWithArmor playerWithArmor(@NotNull GuiParent parent, Cont return new PlayerWithArmor(container, main, bar, armor); } - public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots) { + public static PlayerAll playerAllSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots) { return playerAllSlots(parent, screenAccess, mainSlots, hotBarSlots, armorSlots, offhandSlots, 3, true); } - public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots, int groupSpacing, boolean slotIcons) { + public static PlayerAll playerAllSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots, int groupSpacing, boolean slotIcons) { int width = 18 * 11 + groupSpacing * 2; int height = 18 * 4 + groupSpacing; GuiElement container = new GuiElement<>(parent) - .setZStacking(false) .constrain(WIDTH, Constraint.literal(width)) .constrain(HEIGHT, Constraint.literal(height)); @@ -185,7 +190,7 @@ public static PlayerAll playerAllSlots(@NotNull GuiParent parent, ContainerSc /** * Allows you to use a custom slot texture, The default is the standard vanilla slot. */ - public GuiSlots setSlotTexture(Material slotTexture) { + public GuiSlots setSlotTexture(SpriteSupplier slotTexture) { this.slotTexture = e -> slotTexture; return this; } @@ -193,7 +198,7 @@ public GuiSlots setSlotTexture(Material slotTexture) { /** * Allows you to use a custom per-slot slot textures, The default is the standard vanilla texture for all slots. */ - public GuiSlots setSlotTexture(Function slotTexture) { + public GuiSlots setSlotTexture(Function slotTexture) { this.slotTexture = slotTexture; return this; } @@ -203,7 +208,7 @@ public GuiSlots setSlotTexture(Function slotTexture) { *

    * Similar to {@link #setSlotTexture(Function)} except you are given the index of the slot within the {@link GuiSlots} element. */ - public GuiSlots setSlotTextureI(Function slotTexture) { + public GuiSlots setSlotTextureI(Function slotTexture) { this.slotTexture = slot -> slotTexture.apply(slots.indexOf(slot) - firstSlot); return this; } @@ -239,7 +244,7 @@ public GuiSlots setHighlightColourI(Function highlightColour) * Applies a single empty slot icon to all slots. * Recommended texture size is 16x16 */ - public GuiSlots setEmptyIcon(Material texture) { + public GuiSlots setEmptyIcon(SpriteSupplier texture) { return setEmptyIcon(index -> texture); } @@ -249,7 +254,7 @@ public GuiSlots setEmptyIcon(Material texture) { * * @param slotIcons A function that is given the slot index within the {@link SlotGroup}, and should return a material or null. */ - public GuiSlots setEmptyIcon(Function slotIcons) { + public GuiSlots setEmptyIcon(Function slotIcons) { this.slotIcons = slotIcons; return this; } @@ -262,7 +267,7 @@ public GuiSlots setEmptyIcon(Function slotIcons) { * * @param slotIcons A function that is given the slot index within the {@link SlotGroup}, and should return a material or null. */ - public GuiSlots setEmptyIconI(Function slotIcons) { + public GuiSlots setEmptyIconI(Function slotIcons) { this.slotIcons = slot -> slotIcons.apply(slots.indexOf(slot) - firstSlot); return this; } @@ -273,7 +278,7 @@ public GuiSlots setEmptyIconI(Function slotIcons) { * * @param slotOverlay Render callback providing the slot, screen position of the slot (top-left corner) and the active GuiRender. */ - public GuiSlots setSlotOverlay(TriConsumer slotOverlay) { + public GuiSlots setSlotOverlay(TriConsumer slotOverlay) { this.slotOverlay = slotOverlay; return this; } @@ -286,7 +291,7 @@ public GuiSlots setSlotOverlay(TriConsumer slotOverla * * @param slotOverlay Render callback providing the slot, screen position of the slot (top-left corner) and the active GuiRender. */ - public GuiSlots setSlotOverlayI(TriConsumer slotOverlay) { + public GuiSlots setSlotOverlayI(TriConsumer slotOverlay) { this.slotOverlay = (slot, position, render) -> slotOverlay.accept(slots.indexOf(slot) - firstSlot, position, render); return this; } @@ -309,11 +314,6 @@ public GuiSlots setSlotSpacing(int xSlotSpacing, int ySlotSpacing) { //=== Internal Methods ===// - @Override - public double getBackgroundDepth() { - return 33; - } - private void updateSlots(GuiElement root) { int columns = Math.min(this.columns, slotCount); int rows = Math.max(1, slotCount / columns); @@ -337,41 +337,34 @@ public void tick(double mouseX, double mouseY) { } @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { GuiElement root = getModularGui().getRoot(); updateSlots(root); Slot highlightSlot = null; - render.pose().pushPose(); for (int index = 0; index < slotCount; index++) { Slot slot = slots.getSlot(index + firstSlot); - Material tex = slotTexture.apply(slot); - if (tex != null) { - render.texRect(tex, slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); - } + slotTexture.apply(slot).ifPresent(icon -> { + render.cc$blitSprite(RenderPipelines.GUI_TEXTURED, icon, slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); + }); } - render.pose().translate(0, 0, 0.4); - for (int index = 0; index < slotCount; index++) { Slot slot = slots.getSlot(index + firstSlot); if (!slot.isActive()) continue; if (!slot.hasItem()) { - Material icon = slotIcons.apply(slot); - if (icon != null) { - render.texRect(icon, slot.x + root.xMin(), slot.y + root.yMin(), 16, 16); - } + slotIcons.apply(slot).ifPresent(icon -> { + render.cc$blitSprite(RenderPipelines.GUI_TEXTURED, icon, slot.x + root.xMin(), slot.y + root.yMin(), 16, 16); + }); } - screenAccess.renderSlot(render, slot); - if (GuiRender.isInRect(slot.x + root.xMin(), slot.y + root.yMin(), 16, 16, mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY) && isMouseOver()) { + screenAccess.doRenderSlot(render, slot); + if (MathHelper.isInRect(slot.x + root.xMin(), slot.y + root.yMin(), 16, 16, mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY) && isMouseOver()) { highlightSlot = slot; } } - render.pose().translate(0, 0, getBackgroundDepth() - 0.8); - if (slotOverlay != null) { for (int index = 0; index < slotCount; index++) { Slot slot = slots.getSlot(index + firstSlot); @@ -381,25 +374,26 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo } if (highlightSlot != null) { - render.rect(highlightSlot.x + root.xMin(), highlightSlot.y + root.yMin(), 16, 16, highlightColour.apply(highlightSlot)); + render.cc$fill(highlightSlot.x + root.xMin(), highlightSlot.y + root.yMin(), 16, 16, highlightColour.apply(highlightSlot)); } - - render.pose().popPose(); } public record Player(GuiElement container, GuiSlots main, GuiSlots hotBar) { + public FastStream stream() { return FastStream.of(main, hotBar); } } public record PlayerWithArmor(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor) { + public FastStream stream() { return FastStream.of(main, hotBar, armor); } } public record PlayerAll(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor, GuiSlots offHand) { + public FastStream stream() { return FastStream.of(main, hotBar, armor, offHand); } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java index ad847e6d..7e947f60 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java @@ -1,19 +1,17 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.ForegroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.Align; import codechicken.lib.gui.modular.lib.geometry.GeoParam; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import codechicken.lib.gui.modular.lib.geometry.Position; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Axis; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.locale.Language; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.FormattedText; import net.minecraft.util.FormattedCharSequence; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -22,15 +20,17 @@ import static codechicken.lib.gui.modular.lib.geometry.Align.MAX; import static codechicken.lib.gui.modular.lib.geometry.Align.MIN; import static codechicken.lib.gui.modular.lib.geometry.Constraint.dynamic; +import static java.util.Objects.requireNonNull; /** * Created by brandon3055 on 31/08/2023 */ public class GuiText extends GuiElement implements ForegroundRender { + private Supplier text; private Supplier shadow = () -> true; private Supplier textColour = () -> 0xFFFFFFFF; - private Supplier rotation = null; + private @Nullable Supplier rotation = null; private Position rotatePoint = Position.create(() -> xSize() / 2, () -> ySize() / 2); private boolean trim = false; private boolean wrap = false; @@ -41,21 +41,21 @@ public class GuiText extends GuiElement implements ForegroundRender { /** * @param parent parent {@link GuiParent}. */ - public GuiText(@NotNull GuiParent parent) { + public GuiText(GuiParent parent) { this(parent, () -> null); } /** * @param parent parent {@link GuiParent}. */ - public GuiText(@NotNull GuiParent parent, @Nullable Component text) { + public GuiText(GuiParent parent, @Nullable Component text) { this(parent, () -> text); } /** * @param parent parent {@link GuiParent}. */ - public GuiText(@NotNull GuiParent parent, @NotNull Supplier<@Nullable Component> text) { + public GuiText(GuiParent parent, Supplier<@Nullable Component> text) { super(parent); this.text = text; } @@ -64,16 +64,16 @@ public GuiText(@NotNull GuiParent parent, @NotNull Supplier<@Nullable Compone * Apply a dynamic height constraint that sets the height based on text height (accounting for wrapping) */ public GuiText autoHeight() { - constrain(GeoParam.HEIGHT, dynamic(() -> wrap ? (double) font().wordWrapHeight(getText(), (int) xSize()) : font().lineHeight)); + constrain(GeoParam.HEIGHT, dynamic(() -> wrap ? (double) font().wordWrapHeight(requireNonNull(getText()), (int) xSize()) : font().lineHeight)); return this; } public GuiText autoWidth() { - constrain(GeoParam.WIDTH, dynamic(() -> (double) font().width(getText()))); + constrain(GeoParam.WIDTH, dynamic(() -> (double) font().width(requireNonNull(getText())))); return this; } - public GuiText setTextSupplier(@NotNull Supplier<@Nullable Component> textSupplier) { + public GuiText setTextSupplier(Supplier<@Nullable Component> textSupplier) { this.text = textSupplier; return this; } @@ -83,12 +83,12 @@ public GuiText setText(@Nullable Component text) { return this; } - public GuiText setText(@NotNull String text) { + public GuiText setText(String text) { this.text = () -> Component.literal(text); return this; } - public GuiText setTranslatable(@NotNull String translationKey) { + public GuiText setTranslatable(String translationKey) { this.text = () -> Component.translatable(translationKey); return this; } @@ -152,7 +152,7 @@ public boolean getScroll() { return scroll; } - public GuiText setShadow(@NotNull Supplier shadow) { + public GuiText setShadow(Supplier shadow) { this.shadow = shadow; return this; } @@ -208,27 +208,22 @@ public GuiText setRotatePoint(Position rotatePoint) { } @Override - public double getForegroundDepth() { - return 0.05; - } - - @Override - public void renderForeground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderInFront(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { Component component = getText(); if (component == null) return; - Font font = render.font(); + Font font = Minecraft.getInstance().font; int textHeight = font.lineHeight; int textWidth = font.width(component); boolean tooLong = textWidth > xSize(); double yPos = (yMin() + ySize() / 2 - textHeight / 2D) + 1; //Adding 1 here makes the text look 'visually' centered, Text height includes the height of the optional underline. - PoseStack stack = render.pose(); + var pose = graphics.pose(); if (rotation != null) { - stack.pushPose(); - stack.translate(xMin() + rotatePoint.x(), yMin() + rotatePoint.y(), 0); - stack.mulPose(Axis.ZP.rotationDegrees(rotation.get().floatValue())); - stack.translate(-xMin() - rotatePoint.x(), -yMin() - rotatePoint.y(), 0); + pose.pushMatrix(); + pose.translate((float) (xMin() + rotatePoint.x()), (float) (yMin() + rotatePoint.y())); + pose.rotate(rotation.get().floatValue()); + pose.translate((float) (-xMin() - rotatePoint.x()), (float) (-yMin() - rotatePoint.y())); } //Draw Trimmed @@ -239,7 +234,7 @@ public void renderForeground(GuiRender render, double mouseX, double mouseY, flo textWidth = font.width(formatted); double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; - render.drawString(formatted, xPos, yPos, getTextColour(), getShadow()); + graphics.cc$drawString(font, formatted, xPos, yPos, getTextColour(), getShadow()); } //Draw Wrapped else if ((tooLong || font().split(component, Integer.MAX_VALUE).size() > 1) && wrap) { @@ -250,24 +245,24 @@ else if ((tooLong || font().split(component, Integer.MAX_VALUE).size() > 1) && w for (FormattedCharSequence line : list) { int lineWidth = font.width(line); double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - lineWidth : xMin() + xSize() / 2 - lineWidth / 2D; - render.drawString(line, xPos, yPos, getTextColour(), getShadow()); + graphics.cc$drawString(font, line, xPos, yPos, getTextColour(), getShadow()); yPos += font.lineHeight; } } //Draw Scrolling else if (tooLong && scroll) { - render.pushScissorRect(getRectangle()); - render.drawScrollingString(component, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); - render.popScissor(); + graphics.cc$enableScissor(getRectangle()); + graphics.cc$drawScrollingString(font, component, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); + graphics.cc$disableScissor(); } //Draw else { double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; - render.drawString(component, xPos, yPos, getTextColour(), getShadow()); + graphics.cc$drawString(font, component, xPos, yPos, getTextColour(), getShadow()); } if (rotation != null) { - stack.popPose(); + pose.popMatrix(); } } -} \ No newline at end of file +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java index 1e1083c1..14498a2b 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java @@ -1,25 +1,21 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.TextState; import codechicken.lib.gui.modular.lib.geometry.Constraint; import codechicken.lib.gui.modular.lib.geometry.GuiParent; import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.Util; +import net.minecraft.util.Util; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.RenderStateShard; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Style; import net.minecraft.util.FormattedCharSequence; import net.minecraft.util.Mth; import net.minecraft.util.StringUtil; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; @@ -37,11 +33,6 @@ */ public class GuiTextField extends GuiElement implements BackgroundRender { - private static final RenderType HIGHLIGHT_TYPE = RenderType.create("text_field_highlight", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() - .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionColorShader)) - .setColorLogicState(RenderStateShard.OR_REVERSE_COLOR_LOGIC) - .createCompositeState(false)); - private int tick; private int cursorPos; private int maxLength = 32; @@ -68,7 +59,7 @@ public class GuiTextField extends GuiElement implements Background private Predicate filter = Objects::nonNull; private BiFunction formatter = (string, pos) -> FormattedCharSequence.forward(string, Style.EMPTY); - public GuiTextField(@NotNull GuiParent parent) { + public GuiTextField(GuiParent parent) { super(parent); } @@ -317,7 +308,7 @@ public void insertText(String text) { } private void deleteText(int i) { - if (Screen.hasControlDown()) { + if (Minecraft.getInstance().hasControlDown()) { deleteWords(i); } else { deleteChars(i); @@ -474,25 +465,25 @@ public void setHighlightPos(int newPos) { //=== Input Handling ===// @Override - public boolean keyPressed(int key, int scancode, int modifiers) { + public boolean keyPressed(KeyEvent event) { if (!canConsumeInput()) { return false; } else { - shiftPressed = Screen.hasShiftDown(); - if (Screen.isSelectAll(key)) { + shiftPressed = event.hasShiftDown(); + if (event.isSelectAll()) { moveCursorToEnd(); setHighlightPos(0); return true; - } else if (Screen.isCopy(key)) { + } else if (event.isCopy()) { Minecraft.getInstance().keyboardHandler.setClipboard(getHighlighted()); return true; - } else if (Screen.isPaste(key)) { + } else if (event.isPaste()) { if (isEditable()) { insertText(Minecraft.getInstance().keyboardHandler.getClipboard()); } return true; - } else if (Screen.isCut(key)) { + } else if (event.isCut()) { Minecraft.getInstance().keyboardHandler.setClipboard(getHighlighted()); if (isEditable()) { insertText(""); @@ -500,12 +491,12 @@ public boolean keyPressed(int key, int scancode, int modifiers) { return true; } else { - switch (key) { + switch (event.key()) { case InputConstants.KEY_BACKSPACE: if (isEditable()) { shiftPressed = false; deleteText(-1); - shiftPressed = Screen.hasShiftDown(); + shiftPressed = event.hasShiftDown(); } return true; @@ -525,23 +516,23 @@ public boolean keyPressed(int key, int scancode, int modifiers) { case InputConstants.KEY_PAGEDOWN: default: //Consume key presses when we are typing so we dont do something dumb like close the screen when you type e - return key != GLFW.GLFW_KEY_ESCAPE; + return event.key() != GLFW.GLFW_KEY_ESCAPE; case InputConstants.KEY_DELETE: if (isEditable()) { shiftPressed = false; deleteText(1); - shiftPressed = Screen.hasShiftDown(); + shiftPressed = event.hasShiftDown(); } return true; case InputConstants.KEY_RIGHT: - if (Screen.hasControlDown()) { + if (event.hasControlDown()) { moveCursorTo(getWordPosition(1)); } else { moveCursor(1); } return true; case InputConstants.KEY_LEFT: - if (Screen.hasControlDown()) { + if (event.hasControlDown()) { moveCursorTo(getWordPosition(-1)); } else { moveCursor(-1); @@ -563,18 +554,18 @@ public boolean canConsumeInput() { } @Override - public boolean keyReleased(int key, int scancode, int modifiers, boolean consumed) { - this.shiftPressed = Screen.hasShiftDown(); - return super.keyReleased(key, scancode, modifiers, consumed); + public boolean keyReleased(KeyEvent event, boolean consumed) { + this.shiftPressed = event.hasShiftDown(); + return super.keyReleased(event, consumed); } @Override - public boolean charTyped(char charTyped, int charCode) { + public boolean charTyped(CharacterEvent event) { if (!canConsumeInput()) { return false; - } else if (StringUtil.isAllowedChatCharacter(charTyped)) { + } else if (StringUtil.isAllowedChatCharacter(event.codepoint())) { if (isEditable()) { - insertText(Character.toString(charTyped)); + insertText(event.codepointAsString()); } return true; } else { @@ -583,8 +574,8 @@ public boolean charTyped(char charTyped, int charCode) { } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { - consumed = super.mouseClicked(mouseX, mouseY, button, consumed); + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseClicked(event, consumed); boolean mouseOver = isMouseOver(); if (isFocused() && !mouseOver) { @@ -599,8 +590,8 @@ public boolean mouseClicked(double mouseX, double mouseY, int button, boolean co setFocus(isFocusable.get()); } - if (isFocused() && mouseOver && button == 0) { - int i = (int) (Mth.floor(mouseX) - xMin()); + if (isFocused() && mouseOver && event.button() == 0) { + int i = (int) (Mth.floor(event.x()) - xMin()); String s = font().plainSubstrByWidth(getValue().substring(displayPos), (int) xSize()); moveCursorTo(font().plainSubstrByWidth(s, i).length() + displayPos); return true; @@ -609,15 +600,9 @@ public boolean mouseClicked(double mouseX, double mouseY, int button, boolean co } } - //=== Rendering ===// - - @Override - public double getBackgroundDepth() { - return 0.04; - } - @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + var font = Minecraft.getInstance().font; String value = getValue(); int colour = textColor.get(); @@ -636,7 +621,9 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo if (!displayText.isEmpty()) { String drawString = flag ? displayText.substring(0, textStart) : displayText; - drawEnd = render.drawString(formatter.apply(drawString, displayPos), drawX, drawY, colour, shadow.get()); + var formatted = formatter.apply(drawString, displayPos); + render.cc$drawString(font, formatted, drawX, drawY, colour, shadow.get()); + drawEnd += font.width(formatted) + 1; } boolean flag2 = cursorPos < value.length() || value.length() >= getMaxLength(); @@ -650,26 +637,24 @@ public void renderBackground(GuiRender render, double mouseX, double mouseY, flo } if (!displayText.isEmpty() && flag && textStart < displayText.length()) { - render.drawString(formatter.apply(displayText.substring(textStart), cursorPos), drawEnd, drawY, colour, shadow.get()); + render.cc$drawString(font, formatter.apply(displayText.substring(textStart), cursorPos), drawEnd, drawY, colour, shadow.get()); } if (suggestion != null && value.isEmpty()) { - render.drawString(suggestion.get(), (float) (k1 - 1), (float) drawY, suggestionColour.get(), suggestionShadow.get()); + render.cc$drawString(font, suggestion.get(), (float) (k1 - 1), (float) drawY, suggestionColour.get(), suggestionShadow.get()); } if (cursorBlink) { if (flag2) { - render.fill(k1, drawY - 1, k1 + 1, drawY + 1 + 9, -3092272); + render.cc$fill(k1, drawY - 1, k1 + 1, drawY + 1 + 9, -3092272); } else { - render.drawString("_", (float) k1, (float) drawY, colour, shadow.get()); + render.cc$drawString(font, "_", (float) k1, (float) drawY, colour, shadow.get()); } } if (highlightStart != textStart) { int l1 = (int) (drawX + font().width(displayText.substring(0, highlightStart))); - render.pose().translate(0, 0, 0.035); - render.fill(HIGHLIGHT_TYPE, k1, drawY - 1, l1 - 1, drawY + 1 + 9, 0xFF0000FF); - render.pose().translate(0, 0, -0.035); + render.cc$textHighlight(k1, drawY - 1, l1 - 1, drawY + 1 + 9); } } diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java index 865b935c..b74febc4 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java @@ -1,13 +1,13 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.ForegroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.Align; import codechicken.lib.gui.modular.lib.geometry.GeoParam; import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.function.Supplier; @@ -20,6 +20,7 @@ * Created by brandon3055 on 10/10/2023 */ public class GuiTextList extends GuiElement implements ForegroundRender { + private Supplier> text; private Supplier shadow = () -> true; private Supplier textColour = () -> 0xFFFFFFFF; @@ -31,21 +32,21 @@ public class GuiTextList extends GuiElement implements ForegroundRe /** * @param parent parent {@link GuiParent}. */ - public GuiTextList(@NotNull GuiParent parent) { + public GuiTextList(GuiParent parent) { this(parent, () -> null); } /** * @param parent parent {@link GuiParent}. */ - public GuiTextList(@NotNull GuiParent parent, List text) { + public GuiTextList(GuiParent parent, List text) { this(parent, () -> text); } /** * @param parent parent {@link GuiParent}. */ - public GuiTextList(@NotNull GuiParent parent, @NotNull Supplier> text) { + public GuiTextList(GuiParent parent, Supplier> text) { super(parent); this.text = text; } @@ -58,7 +59,7 @@ public GuiTextList autoHeight() { return this; } - public GuiTextList setTextSupplier(@NotNull Supplier> textSupplier) { + public GuiTextList setTextSupplier(Supplier> textSupplier) { this.text = textSupplier; return this; } @@ -113,7 +114,7 @@ public boolean getScroll() { return scroll; } - public GuiTextList setShadow(@NotNull Supplier shadow) { + public GuiTextList setShadow(Supplier shadow) { this.shadow = shadow; return this; } @@ -142,15 +143,10 @@ public int getTextColour() { } @Override - public double getForegroundDepth() { - return 0.035; - } - - @Override - public void renderForeground(GuiRender render, double mouseX, double mouseY, float partialTicks) { + public void renderInFront(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { List list = getText(); if (list.isEmpty()) return; - Font font = render.font(); + Font font = Minecraft.getInstance().font; double height = (list.size() * (font.lineHeight + lineSpacing)) - lineSpacing; double yPos = verticalAlign == MIN ? yMin() : verticalAlign == MAX ? yMax() - height : (yCenter() - (height / 2)) + 1; @@ -159,15 +155,15 @@ public void renderForeground(GuiRender render, double mouseX, double mouseY, flo boolean tooLong = textWidth > xSize(); if (tooLong && scroll) { - render.pushScissorRect(getRectangle()); - render.drawScrollingString(line, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); - render.popScissor(); + render.cc$enableScissor(getRectangle()); + render.cc$drawScrollingString(font, line, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); + render.cc$disableScissor(); } else { double xPos = horizontalAlign == MIN ? xMin() : horizontalAlign == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; - render.drawString(line, xPos, yPos, getTextColour(), getShadow()); + render.cc$drawString(font, line, xPos, yPos, getTextColour(), getShadow()); } yPos += font.lineHeight + lineSpacing; } } -} \ No newline at end of file +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java index 542b6ee2..f61aa21c 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java @@ -1,11 +1,11 @@ package codechicken.lib.gui.modular.elements; import codechicken.lib.gui.modular.lib.BackgroundRender; -import codechicken.lib.gui.modular.lib.GuiRender; import codechicken.lib.gui.modular.lib.geometry.Borders; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.gui.modular.sprite.Material; -import org.jetbrains.annotations.NotNull; +import codechicken.lib.gui.modular.SpriteSupplier; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderPipelines; import org.jetbrains.annotations.Nullable; import java.util.function.Supplier; @@ -14,41 +14,28 @@ * Created by brandon3055 on 28/08/2023 */ public class GuiTexture extends GuiElement implements BackgroundRender { - private Supplier getMaterial; + + private SpriteSupplier spriteSupplier = SpriteSupplier.EMPTY; private Supplier colour = () -> 0xFFFFFFFF; - private Borders dynamicBorders = null; + private @Nullable Borders dynamicBorders = null; private Supplier rotation = () -> 0; - /** - * @param parent parent {@link GuiParent}. - */ - public GuiTexture(@NotNull GuiParent parent) { - super(parent); - } - - public GuiTexture(@NotNull GuiParent parent, Supplier supplier) { - super(parent); - setMaterial(supplier); + public GuiTexture(GuiParent parent) { + this(parent, SpriteSupplier.EMPTY); } - public GuiTexture(@NotNull GuiParent parent, Material material) { + public GuiTexture(GuiParent parent, SpriteSupplier spriteSupplier) { super(parent); - setMaterial(material); - } - - public GuiTexture setMaterial(Supplier supplier) { - this.getMaterial = supplier; - return this; + setMaterial(spriteSupplier); } - public GuiTexture setMaterial(Material material) { - this.getMaterial = () -> material; + public GuiTexture setMaterial(SpriteSupplier spriteSupplier) { + this.spriteSupplier = spriteSupplier; return this; } - @Nullable - public Material getMaterial() { - return getMaterial == null ? null : getMaterial.get(); + public SpriteSupplier getSprite() { + return spriteSupplier; } /** @@ -76,7 +63,7 @@ public GuiTexture dynamicTexture(int textureBorders) { * The border parameters indicate the width of border around the texture that must be maintained during the cutting and tiling process. * For standardisation purposes the border width should be >= 5 */ - public GuiTexture dynamicTexture(Borders textureBorders) { + public GuiTexture dynamicTexture(@Nullable Borders textureBorders) { dynamicBorders = textureBorders; return this; } @@ -117,13 +104,13 @@ public GuiTexture setRotation(int rotation) { } @Override - public void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks) { - Material material = getMaterial(); - if (material == null) return; - if (dynamicBorders != null) { - render.dynamicTex(material, getRectangle(), dynamicBorders, colour.get()); - } else { - render.texRect(material, rotation.get(), getRectangle(), colour.get()); - } + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + getSprite().ifPresent(sprite -> { + if (dynamicBorders != null) { + graphics.cc$blitDynamicSprite(RenderPipelines.GUI_TEXTURED, sprite, getRectangle(), dynamicBorders, colour.get()); + } else { + graphics.cc$blitSprite(RenderPipelines.GUI_TEXTURED, sprite, rotation.get(), getRectangle(), colour.get()); + } + }); } } diff --git a/src/main/java/codechicken/lib/model/bakedmodels/package-info.java b/src/main/java/codechicken/lib/gui/modular/elements/package-info.java similarity index 58% rename from src/main/java/codechicken/lib/model/bakedmodels/package-info.java rename to src/main/java/codechicken/lib/gui/modular/elements/package-info.java index 39092011..0fff58bb 100644 --- a/src/main/java/codechicken/lib/model/bakedmodels/package-info.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/package-info.java @@ -1,4 +1,4 @@ @NonNullApi -package codechicken.lib.model.bakedmodels; +package codechicken.lib.gui.modular.elements; import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java b/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java index 0291e8af..4836da56 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java @@ -1,6 +1,7 @@ package codechicken.lib.gui.modular.lib; import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.gui.GuiGraphics; /** * Allows a Gui Elements to render content behind child elements. @@ -10,18 +11,6 @@ */ public interface BackgroundRender { - /** - * Specifies the z depth of the background content. - * After {@link #renderBackground(GuiRender, double, double, float)} is called, the PoseStack will be translated by this amount in the z direction - * before any assigned child elements are rendered. - * Recommended minimum depth is 0.01 or 0.035 if this element renders text. (text shadows are rendered with a 0.03 offset) - * - * @return the z height of the background content. - */ - default double getBackgroundDepth() { - return 0.01; - } - /** * Used to render content behind this elements child elements. * When rendering element content, always use the {@link PoseStack} available via the provided {@link GuiRender} @@ -29,6 +18,6 @@ default double getBackgroundDepth() { * * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. */ - void renderBackground(GuiRender render, double mouseX, double mouseY, float partialTicks); + void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks); } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java index c20a2cee..c073addf 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java @@ -2,7 +2,7 @@ import codechicken.lib.CodeChickenLib; import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.Resource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -26,16 +26,16 @@ public class CursorHelper { public static final Logger LOGGER = LogManager.getLogger(); - public static final ResourceLocation DRAG = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/drag.png"); - public static final ResourceLocation RESIZE_H = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_h.png"); - public static final ResourceLocation RESIZE_V = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_v.png"); - public static final ResourceLocation RESIZE_TRBL = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_trbl.png"); - public static final ResourceLocation RESIZE_TLBR = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_tlbr.png"); + public static final Identifier DRAG = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/drag.png"); + public static final Identifier RESIZE_H = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_h.png"); + public static final Identifier RESIZE_V = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_v.png"); + public static final Identifier RESIZE_TRBL = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_trbl.png"); + public static final Identifier RESIZE_TLBR = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_tlbr.png"); - private static final Map cursors = new HashMap<>(); - private static ResourceLocation active = null; + private static final Map cursors = new HashMap<>(); + private static Identifier active = null; - private static long createCursor(ResourceLocation cursorTexture) { + private static long createCursor(Identifier cursorTexture) { try { Resource resource = Minecraft.getInstance().getResourceManager().getResource(cursorTexture).orElse(null); if (resource == null) return MemoryUtil.NULL; @@ -74,10 +74,10 @@ private static GLFWImage imageToGLFWImage(BufferedImage image) { return result; } - public static void setCursor(@Nullable ResourceLocation cursor) { + public static void setCursor(@Nullable Identifier cursor) { if (cursor != active) { active = cursor; - long window = Minecraft.getInstance().getWindow().getWindow(); + long window = Minecraft.getInstance().getWindow().handle(); long newCursor = active == null ? 0 : cursors.computeIfAbsent(cursor, CursorHelper::createCursor); GLFW.glfwSetCursor(window, newCursor); } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java b/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java index aa15ddfa..77c167e1 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java @@ -1,6 +1,6 @@ package codechicken.lib.gui.modular.lib; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import java.util.function.Function; @@ -13,15 +13,15 @@ public interface DynamicTextures { void makeTextures(Function textures); - default String dynamicTexture(Function textures, ResourceLocation dynamicInput, ResourceLocation outputLocation, int width, int height, int border) { + default String dynamicTexture(Function textures, Identifier dynamicInput, Identifier outputLocation, int width, int height, int border) { return textures.apply(new DynamicTexture(dynamicInput, outputLocation, width, height, border, border, border, border)); } - default String dynamicTexture(Function textures, ResourceLocation dynamicInput, ResourceLocation outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + default String dynamicTexture(Function textures, Identifier dynamicInput, Identifier outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { return textures.apply(new DynamicTexture(dynamicInput, outputLocation, width, height, topBorder, leftBorder, bottomBorder, rightBorder)); } - record DynamicTexture(ResourceLocation dynamicInput, ResourceLocation outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + record DynamicTexture(Identifier dynamicInput, Identifier outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { public String guiTexturePath() { return outputLocation.getPath().replace("textures/gui/", "").replace(".gui", ""); } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java index 85eb7502..66f36548 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java @@ -2,6 +2,9 @@ import codechicken.lib.gui.modular.elements.GuiElement; import com.google.common.collect.Lists; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; import java.util.List; @@ -43,81 +46,73 @@ default void mouseMoved(double mouseX, double mouseY) { /** * Override this method to implement handling for the mouseClicked event. * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. - * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseClicked(double, double, int, boolean)} + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseClicked(MouseButtonEvent, boolean)} *

    * Note: You do not need to call super when overriding this interface method. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param button Mouse Button + * @param event The mouse button event. Position, Key, and modifiers. * @return true to consume event. */ - default boolean mouseClicked(double mouseX, double mouseY, int button) { + default boolean mouseClicked(MouseButtonEvent event) { return false; } /** * Root handler for mouseClick event. This method will always be called for all elements even if the event has already been consumed. - * There are a few uses for this method, but the fast majority of mouseClick handling should be implemented via {@link #mouseClicked(double, double, int)} + * There are a few uses for this method, but the fast majority of mouseClick handling should be implemented via {@link #mouseClicked(MouseButtonEvent)} *

    * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param button Mouse Button + * @param event The mouse button event. Position, Key, and modifiers. * @param consumed Will be true if this action has already been consumed. * @return true if this event has been consumed. */ - default boolean mouseClicked(double mouseX, double mouseY, int button, boolean consumed) { + default boolean mouseClicked(MouseButtonEvent event, boolean consumed) { for (GuiElement child : Lists.reverse(getChildren())) { if (child.isEnabled()) { - consumed |= child.mouseClicked(mouseX, mouseY, button, consumed); + consumed |= child.mouseClicked(event, consumed); } } - return consumed || mouseClicked(mouseX, mouseY, button) || blockMouseEvents(); + return consumed || mouseClicked(event) || blockMouseEvents(); } /** * Override this method to implement handling for the mouseReleased event. * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. - * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseReleased(double, double, int, boolean)} + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseReleased(MouseButtonEvent, boolean)} *

    * Note: You do not need to call super when overriding this interface method. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param button Mouse Button + * @param event The mouse button event. Position, Key, and modifiers. * @return true to consume event. */ - default boolean mouseReleased(double mouseX, double mouseY, int button) { + default boolean mouseReleased(MouseButtonEvent event) { return false; } /** * Root handler for mouseReleased event. This method will always be called for all elements even if the event has already been consumed. - * There are a few uses for this method, but the fast majority of mouseReleased handling should be implemented via {@link #mouseReleased(double, double, int)} + * There are a few uses for this method, but the fast majority of mouseReleased handling should be implemented via {@link #mouseReleased(MouseButtonEvent)} *

    * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. * - * @param mouseX Mouse X position - * @param mouseY Mouse Y position - * @param button Mouse Button + * @param event The mouse button event. Position, Key, and modifiers. * @param consumed Will be true if this action has already been consumed. * @return true if this event has been consumed. */ - default boolean mouseReleased(double mouseX, double mouseY, int button, boolean consumed) { + default boolean mouseReleased(MouseButtonEvent event, boolean consumed) { for (GuiElement child : Lists.reverse(getChildren())) { if (child.isEnabled()) { - consumed |= child.mouseReleased(mouseX, mouseY, button, consumed); + consumed |= child.mouseReleased(event, consumed); } } - return consumed || mouseReleased(mouseX, mouseY, button) || blockMouseEvents(); + return consumed || mouseReleased(event) || blockMouseEvents(); } /** * Override this method to implement handling for the mouseScrolled event. * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. - * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseScrolled(double, double, double, boolean)} + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseScrolled(double, double, double, double, boolean)} *

    * Note: You do not need to call super when overriding this interface method. * @@ -133,7 +128,7 @@ default boolean mouseScrolled(double mouseX, double mouseY, double scrollX, doub /** * Root handler for mouseScrolled event. This method will always be called for all elements even if the event has already been consumed. - * There are a few uses for this method, but the fast majority of mouseScrolled handling should be implemented via {@link #mouseScrolled(double, double, double)} + * There are a few uses for this method, but the fast majority of mouseScrolled handling should be implemented via {@link #mouseScrolled(double, double, double, double)} *

    * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. * @@ -165,110 +160,100 @@ default boolean blockMouseEvents() { /** * Override this method to implement handling for the keyPressed event. * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. - * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyPressed(int, int, int, boolean)} + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyPressed(KeyEvent, boolean)} *

    * Note: You do not need to call super when overriding this interface method. * - * @param key the keyboard key that was pressed. - * @param scancode the system-specific scancode of the key - * @param modifiers bitfield describing which modifier keys were held down. + * @param event The key event. Key, scancode, and modifiers. * @return true to consume event. */ - default boolean keyPressed(int key, int scancode, int modifiers) { + default boolean keyPressed(KeyEvent event) { return false; } /** * Root handler for keyPressed event. This method will always be called for all elements even if the event has already been consumed. - * There are a few uses for this method, but the fast majority of keyPressed handling should be implemented via {@link #keyPressed(int, int, int)} + * There are a few uses for this method, but the fast majority of keyPressed handling should be implemented via {@link #keyPressed(KeyEvent)} *

    * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. * - * @param key the keyboard key that was pressed. - * @param scancode the system-specific scancode of the key - * @param modifiers bitfield describing which modifier keys were held down. - * @param consumed Will be true if this action has already been consumed. + * @param event The key event. Key, scancode, and modifiers. + * @param consumed Will be true if this action has already been consumed. * @return true if this event has been consumed. */ - default boolean keyPressed(int key, int scancode, int modifiers, boolean consumed) { + default boolean keyPressed(KeyEvent event, boolean consumed) { for (GuiElement child : Lists.reverse(getChildren())) { if (child.isEnabled()) { - consumed |= child.keyPressed(key, scancode, modifiers, consumed); + consumed |= child.keyPressed(event, consumed); } } - return consumed || keyPressed(key, scancode, modifiers); + return consumed || keyPressed(event); } /** * Override this method to implement handling for the keyReleased event. * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. - * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyReleased(int, int, int, boolean)} + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyReleased(KeyEvent, boolean)} *

    * Note: You do not need to call super when overriding this interface method. * - * @param key the keyboard key that was released. - * @param scancode the system-specific scancode of the key - * @param modifiers bitfield describing which modifier keys were held down. + * @param event The key event. Key, scancode, and modifiers. * @return true to consume event. */ - default boolean keyReleased(int key, int scancode, int modifiers) { + default boolean keyReleased(KeyEvent event) { return false; } /** * Root handler for keyReleased event. This method will always be called for all elements even if the event has already been consumed. - * There are a few uses for this method, but the fast majority of keyReleased handling should be implemented via {@link #keyReleased(int, int, int)} + * There are a few uses for this method, but the fast majority of keyReleased handling should be implemented via {@link #keyReleased(KeyEvent)} *

    * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. * - * @param key the keyboard key that was released. - * @param scancode the system-specific scancode of the key - * @param modifiers bitfield describing which modifier keys were held down. - * @param consumed Will be true if this action has already been consumed. + * @param event The key event. Key, scancode, and modifiers. + * @param consumed Will be true if this action has already been consumed. * @return true if this event has been consumed. */ - default boolean keyReleased(int key, int scancode, int modifiers, boolean consumed) { + default boolean keyReleased(KeyEvent event, boolean consumed) { for (GuiElement child : Lists.reverse(getChildren())) { if (child.isEnabled()) { - consumed |= child.keyReleased(key, scancode, modifiers, consumed); + consumed |= child.keyReleased(event, consumed); } } - return consumed || keyReleased(key, scancode, modifiers); + return consumed || keyReleased(event); } /** * Override this method to implement handling for the charTyped event. * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. - * For rare cases where you need to receive this even if it has been consumed, you can override {@link #charTyped(char, int, boolean)} + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #charTyped(CharacterEvent, boolean)} *

    * Note: You do not need to call super when overriding this interface method. * - * @param character The character typed. - * @param modifiers bitfield describing which modifier keys were held down. + * @param event The character event, codepoint and modifiers. * @return true to consume event. */ - default boolean charTyped(char character, int modifiers) { + default boolean charTyped(CharacterEvent event) { return false; } /** * Root handler for charTyped event. This method will always be called for all elements even if the event has already been consumed. - * There are a few uses for this method, but the fast majority of charTyped handling should be implemented via {@link #charTyped(char, int)} + * There are a few uses for this method, but the fast majority of charTyped handling should be implemented via {@link #charTyped(CharacterEvent)} *

    * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. * - * @param character The character typed. - * @param modifiers bitfield describing which modifier keys were held down. - * @param consumed Will be true if this action has already been consumed. + * @param event The character event, codepoint and modifiers. + * @param consumed Will be true if this action has already been consumed. * @return true if this event has been consumed. */ - default boolean charTyped(char character, int modifiers, boolean consumed) { + default boolean charTyped(CharacterEvent event, boolean consumed) { for (GuiElement child : Lists.reverse(getChildren())) { if (child.isEnabled()) { - consumed |= child.charTyped(character, modifiers, consumed); + consumed |= child.charTyped(event, consumed); } } - return consumed || charTyped(character, modifiers); + return consumed || charTyped(event); } } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java b/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java index 76dfcfb3..2e51189f 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java @@ -1,6 +1,7 @@ package codechicken.lib.gui.modular.lib; import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.gui.GuiGraphics; /** * Allows a Gui Elements to render content in front of child elements. @@ -10,23 +11,12 @@ */ public interface ForegroundRender { - /** - * Specifies the z depth of the foreground content. - * Used when calculating the total depth of this gui element. - * Recommended minimum depth is 0.01 or 0.035 if this element renders text. (text shadows are rendered with a 0.03 offset) - * - * @return the z height of the background content. - */ - default double getForegroundDepth() { - return 0.01; - } - /** * Used to render content in front of this elements child elements. * When rendering element content, always use the {@link PoseStack} available via the provided {@link GuiRender} * Where applicable, always use push/pop to ensure the stack is returned to its original state after your rendering is complete. * - * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + * @param graphics Contains gui context information as well as essential render methods/utils including the PoseStack. */ - void renderForeground(GuiRender render, double mouseX, double mouseY, float partialTicks); + void renderInFront(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks); } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java deleted file mode 100644 index 68c96a01..00000000 --- a/src/main/java/codechicken/lib/gui/modular/lib/GuiRender.java +++ /dev/null @@ -1,1729 +0,0 @@ -package codechicken.lib.gui.modular.lib; - -import codechicken.lib.gui.modular.lib.geometry.Borders; -import codechicken.lib.gui.modular.lib.geometry.Rectangle; -import codechicken.lib.gui.modular.sprite.Material; -import com.mojang.blaze3d.platform.Lighting; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.CrashReport; -import net.minecraft.CrashReportCategory; -import net.minecraft.ReportedException; -import net.minecraft.Util; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner; -import net.minecraft.client.gui.screens.inventory.tooltip.DefaultTooltipPositioner; -import net.minecraft.client.player.LocalPlayer; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderStateShard; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.client.renderer.texture.SpriteContents; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.FormattedText; -import net.minecraft.network.chat.HoverEvent; -import net.minecraft.network.chat.Style; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.FormattedCharSequence; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.inventory.tooltip.TooltipComponent; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.neoforged.neoforge.client.ClientHooks; -import net.neoforged.neoforge.client.ItemDecoratorHandler; -import net.neoforged.neoforge.client.event.RenderTooltipEvent; -import net.neoforged.neoforge.common.NeoForge; -import org.jetbrains.annotations.Nullable; -import org.joml.Matrix4f; -import org.joml.Vector2ic; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -/** - * This class primarily based on GuiHelper from BrandonsCore - * But its implementation is heavily inspired by the new GuiGraphics system in 1.20+ - *

    - * The purpose of this class is to provide most of the basic rendering functions required to render various GUI geometry. - * This includes things like simple rectangles, textures, strings, etc. - *

    - * Created by brandon3055 on 29/06/2023 - */ -public class GuiRender { - - public static final RenderType SOLID = RenderType.gui(); - - //Used for things like events that require the vanilla GuiGraphics - private final RenderWrapper renderWrapper; - - private final Minecraft mc; - private final PoseStack pose; - private final ScissorHandler scissorHandler = new ScissorHandler(); - private final MultiBufferSource.BufferSource buffers; - private boolean batchDraw; - private Font fontOverride; - - public GuiRender(Minecraft mc, PoseStack poseStack, MultiBufferSource.BufferSource buffers) { - this.mc = mc; - this.pose = poseStack; - this.buffers = buffers; - this.renderWrapper = new RenderWrapper(this); - } - - public GuiRender(Minecraft mc, MultiBufferSource.BufferSource buffers) { - this(mc, new PoseStack(), buffers); - } - - public static GuiRender convert(GuiGraphics graphics) { - return new GuiRender(Minecraft.getInstance(), graphics.pose(), graphics.bufferSource()); - } - - public PoseStack pose() { - return pose; - } - - public MultiBufferSource.BufferSource buffers() { - return buffers; - } - - public Minecraft mc() { - return mc; - } - - public Font font() { - return fontOverride == null ? mc().font : fontOverride; - } - - public int guiWidth() { - return mc().getWindow().getGuiScaledWidth(); - } - - public int guiHeight() { - return mc().getWindow().getGuiScaledHeight(); - } - - /** - * Allows you to override the font renderer used for all text rendering. - * Be sure to set the override back to null when you are finished using your custom font! - * - * @param font The font to use, or null to disable override. - */ - public void overrideFont(@Nullable Font font) { - this.fontOverride = font; - } - - /** - * Allow similar render calls to be batched together into a single draw for better render efficiency. - * All render calls in batch must use the same render type. - * - * @param batch callback in which the rendering should be implemented. - */ - public void batchDraw(Runnable batch) { - flush(); - batchDraw = true; - batch.run(); - batchDraw = false; - flush(); - } - - private void flushIfUnBatched() { - if (!batchDraw) flush(); - } - - private void flushIfBatched() { - if (batchDraw) flush(); - } - - public void flush() { - RenderSystem.disableDepthTest(); - buffers.endBatch(); - RenderSystem.enableDepthTest(); - } - - /** - * Only use this as a last resort! It may explode... Have fun! - * - * @return A Vanilla GuiGraphics instance that wraps this {@link GuiRender} - */ - @Deprecated - public RenderWrapper guiGraphicsWrapper() { - return renderWrapper; - } - - //=== Un-Textured geometry ===// - - /** - * Fill rectangle with solid colour - */ - public void rect(Rectangle rectangle, int colour) { - this.rect(SOLID, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), colour); - } - - /** - * Fill rectangle with solid colour - */ - public void rect(RenderType type, Rectangle rectangle, int colour) { - this.rect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), colour); - } - - /** - * Fill rectangle with solid colour - */ - public void rect(double x, double y, double width, double height, int colour) { - this.fill(SOLID, x, y, x + width, y + height, colour); - } - - /** - * Fill rectangle with solid colour - */ - public void rect(RenderType type, double x, double y, double width, double height, int colour) { - this.fill(type, x, y, x + width, y + height, colour); - } - - /** - * Fill area with solid colour - */ - public void fill(double xMin, double yMin, double xMax, double yMax, int colour) { - this.fill(SOLID, xMin, yMin, xMax, yMax, colour); - } - - /** - * Fill area with solid colour - */ - public void fill(RenderType type, double xMin, double yMin, double xMax, double yMax, int colour) { - if (xMax < xMin) { - double min = xMax; - xMax = xMin; - xMin = min; - } - if (yMax < yMin) { - double min = yMax; - yMax = yMin; - yMin = min; - } - - Matrix4f mat = pose.last().pose(); - VertexConsumer buffer = buffers.getBuffer(type); - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(colour); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(colour); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(colour); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(colour); //L-B - flushIfUnBatched(); - } - - /** - * Fill area with colour gradient from top to bottom - */ - public void gradientFillV(double xMin, double yMin, double xMax, double yMax, int topColour, int bottomColour) { - this.gradientFillV(SOLID, xMin, yMin, xMax, yMax, topColour, bottomColour); - } - - /** - * Fill area with colour gradient from top to bottom - */ - public void gradientFillV(RenderType type, double xMin, double yMin, double xMax, double yMax, int topColour, int bottomColour) { - VertexConsumer buffer = buffers().getBuffer(type); - float sA = a(topColour); - float sR = r(topColour); - float sG = g(topColour); - float sB = b(topColour); - float eA = a(bottomColour); - float eR = r(bottomColour); - float eG = g(bottomColour); - float eB = b(bottomColour); - Matrix4f mat = pose.last().pose(); - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(eR, eG, eB, eA); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(sR, sG, sB, sA); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(sR, sG, sB, sA); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(eR, eG, eB, eA); //L-B - this.flushIfUnBatched(); - } - - /** - * Fill area with colour gradient from left to right - */ - public void gradientFillH(double xMin, double yMin, double xMax, double yMax, int leftColour, int rightColour) { - this.gradientFillH(SOLID, xMin, yMin, xMax, yMax, leftColour, rightColour); - } - - /** - * Fill area with colour gradient from left to right - */ - public void gradientFillH(RenderType type, double xMin, double yMin, double xMax, double yMax, int leftColour, int rightColour) { - VertexConsumer buffer = buffers().getBuffer(type); - float sA = a(leftColour); - float sR = r(leftColour); - float sG = g(leftColour); - float sB = b(leftColour); - float eA = a(rightColour); - float eR = r(rightColour); - float eG = g(rightColour); - float eB = b(rightColour); - Matrix4f mat = pose.last().pose(); - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(eR, eG, eB, eA); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(eR, eG, eB, eA); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(sR, sG, sB, sA); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(sR, sG, sB, sA); //L-B - this.flushIfUnBatched(); - } - - /** - * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. - */ - public void borderRect(Rectangle rectangle, double borderWidth, int fillColour, int borderColour) { - borderFill(rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, fillColour, borderColour); - } - - /** - * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. - */ - public void borderRect(double x, double y, double width, double height, double borderWidth, int fillColour, int borderColour) { - borderFill(x, y, x + width, y + height, borderWidth, fillColour, borderColour); - } - - /** - * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. - */ - public void borderRect(RenderType type, Rectangle rectangle, double borderWidth, int fillColour, int borderColour) { - borderFill(type, rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, fillColour, borderColour); - } - - /** - * Draw a bordered rectangle of specified with specified border width, border colour and fill colour. - */ - public void borderRect(RenderType type, double x, double y, double width, double height, double borderWidth, int fillColour, int borderColour) { - borderFill(type, x, y, x + width, y + height, borderWidth, fillColour, borderColour); - } - - /** - * Draw a border of specified with, fill internal area with solid colour. - */ - public void borderFill(double xMin, double yMin, double xMax, double yMax, double borderWidth, int fillColour, int borderColour) { - borderFill(SOLID, xMin, yMin, xMax, yMax, borderWidth, fillColour, borderColour); - } - - /** - * Draw a border of specified with, fill internal area with solid colour. - */ - public void borderFill(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int fillColour, int borderColour) { - if (batchDraw) { //Draw batched for efficiency, unless already doing a batch draw. - borderFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, fillColour, borderColour); - } else { - batchDraw(() -> borderFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, fillColour, borderColour)); - } - } - - private void borderFillInternal(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int fillColour, int borderColour) { - fill(type, xMin, yMin, xMax, yMin + borderWidth, borderColour); //Top - fill(type, xMin, yMin + borderWidth, xMin + borderWidth, yMax - borderWidth, borderColour); //Left - fill(type, xMin, yMax - borderWidth, xMax, yMax, borderColour); //Bottom - fill(type, xMax - borderWidth, yMin + borderWidth, xMax, yMax - borderWidth, borderColour); //Right - if (fillColour != 0) { //No point rendering fill if there is no fill colour - fill(type, xMin + borderWidth, yMin + borderWidth, xMax - borderWidth, yMax - borderWidth, fillColour); //Fill - } - } - - /** - * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedRect(Rectangle rectangle, double borderWidth, int topLeftColour, int bottomRightColour, int fillColour) { - shadedFill(SOLID, rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, topLeftColour, bottomRightColour, midColour(topLeftColour, bottomRightColour), fillColour); - } - - /** - * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedRect(double x, double y, double width, double height, double borderWidth, int topLeftColour, int bottomRightColour, int fillColour) { - shadedFill(SOLID, x, y, x + width, y + height, borderWidth, topLeftColour, bottomRightColour, midColour(topLeftColour, bottomRightColour), fillColour); - } - - /** - * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedRect(Rectangle rectangle, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { - shadedFill(SOLID, rectangle.x(), rectangle.y(), rectangle.xMax(), rectangle.yMax(), borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); - } - - /** - * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedRect(double x, double y, double width, double height, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { - shadedFill(SOLID, x, y, x + width, y + height, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); - } - - /** - * Can be used to create the illusion of an inset / outset rectangle. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedRect(RenderType type, double x, double y, double width, double height, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { - shadedFill(type, x, y, x + width, y + height, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); - } - - /** - * Can be used to create the illusion of an inset / outset area. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedFill(double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int fillColour) { - shadedFill(SOLID, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, midColour(topLeftColour, bottomRightColour), fillColour); - } - - /** - * Can be used to create the illusion of an inset / outset area. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedFill(double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { - shadedFill(SOLID, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); - } - - /** - * Can be used to create the illusion of an inset / outset area. This is identical to the way inventory slots are rendered except in code rather than via a texture. - * Example Usage: render.shadedFill(0, 0, 18, 18, 1, 0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); //Renders a vanilla style inventory slot - * This can also be used to render things like buttons that appear to actually "push in" when you press them. - */ - public void shadedFill(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { - if (batchDraw) { //Draw batched for efficiency, unless already doing a batch draw. - shadedFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour); - } else { - batchDraw(() -> shadedFillInternal(type, xMin, yMin, xMax, yMax, borderWidth, topLeftColour, bottomRightColour, cornerMixColour, fillColour)); - } - } - - public void shadedFillInternal(RenderType type, double xMin, double yMin, double xMax, double yMax, double borderWidth, int topLeftColour, int bottomRightColour, int cornerMixColour, int fillColour) { - fill(type, xMin, yMin, xMax - borderWidth, yMin + borderWidth, topLeftColour); //Top - fill(type, xMin, yMin + borderWidth, xMin + borderWidth, yMax - borderWidth, topLeftColour); //Left - fill(type, xMin + borderWidth, yMax - borderWidth, xMax, yMax, bottomRightColour); //Bottom - fill(type, xMax - borderWidth, yMin + borderWidth, xMax, yMax - borderWidth, bottomRightColour); //Right - fill(type, xMax - borderWidth, yMin, xMax, yMin + borderWidth, cornerMixColour); //Top Right Corner - fill(type, xMin, yMax - borderWidth, xMin + borderWidth, yMax, cornerMixColour); //Bottom Left Corner - - if (fillColour != 0) { //No point rendering fill if there is no fill colour - fill(type, xMin + borderWidth, yMin + borderWidth, xMax - borderWidth, yMax - borderWidth, fillColour); //Fill - } - } - - //=== Generic Backgrounds ===// - - /** - * Draws a rectangle / background with a style matching vanilla tool tips. - */ - public void toolTipBackground(double x, double y, double width, double height) { - toolTipBackground(x, y, width, height, 0xF0100010, 0x505000FF, 0x5028007f); - } - - /** - * Draws a rectangle / background with a style matching vanilla tool tips. - * Vanilla Default Colours: 0xF0100010, 0x505000FF, 0x5028007f - */ - public void toolTipBackground(double x, double y, double width, double height, int backgroundColour, int borderColourTop, int borderColourBottom) { - toolTipBackground(x, y, width, height, backgroundColour, backgroundColour, borderColourTop, borderColourBottom, false); - } - - /** - * Draws a rectangle / background with a style matching vanilla tool tips. - * Vanilla Default Colours: 0xF0100010, 0xF0100010, 0x505000FF, 0x5028007f - */ - public void toolTipBackground(double x, double y, double width, double height, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom, boolean empty) { - if (batchDraw) { //Draw batched for efficiency, unless already doing a batch draw. - toolTipBackgroundInternal(x, y, x + width, y + height, backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false); - } else { - batchDraw(() -> toolTipBackgroundInternal(x, y, x + width, y + height, backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false)); - } - } - - private void toolTipBackgroundInternal(double xMin, double yMin, double xMax, double yMax, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom, boolean empty) { - fill(xMin + 1, yMin, xMax - 1, yMin + 1, backgroundColourTop); // Top - fill(xMin + 1, yMax - 1, xMax - 1, yMax, backgroundColourBottom); // Bottom - gradientFillV(xMin, yMin + 1, xMin + 1, yMax - 1, backgroundColourTop, backgroundColourBottom); // Left - gradientFillV(xMax - 1, yMin + 1, xMax, yMax - 1, backgroundColourTop, backgroundColourBottom); // Right - if (!empty) { - gradientFillV(xMin + 1, yMin + 1, xMax - 1, yMax - 1, backgroundColourTop, backgroundColourBottom); // Fill - } - gradientFillV(xMin + 1, yMin + 1, xMin + 2, yMax - 1, borderColourTop, borderColourBottom); // Left Accent - gradientFillV(xMax - 2, yMin + 1, xMax - 1, yMax - 1, borderColourTop, borderColourBottom); // Right Accent - fill(xMin + 2, yMin + 1, xMax - 2, yMin + 2, borderColourTop); // Top Accent - fill(xMin + 2, yMax - 2, xMax - 2, yMax - 1, borderColourBottom); // Bottom Accent - } - - //=== Textured geometry ===// - - //Sprite plus RenderType - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void spriteRect(RenderType type, Rectangle rectangle, TextureAtlasSprite sprite) { - spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), sprite, 1F, 1F, 1F, 1F); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void spriteRect(RenderType type, Rectangle rectangle, TextureAtlasSprite sprite, int argb) { - spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), sprite, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void spriteRect(RenderType type, Rectangle rectangle, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), sprite, red, green, blue, alpha); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void spriteRect(RenderType type, double x, double y, double width, double height, TextureAtlasSprite sprite) { - spriteRect(type, x, y, width, height, sprite, 1F, 1F, 1F, 1F); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void spriteRect(RenderType type, double x, double y, double width, double height, TextureAtlasSprite sprite, int argb) { - spriteRect(type, x, y, width, height, sprite, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void spriteRect(RenderType type, double x, double y, double width, double height, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - sprite(type, x, y, x + width, y + height, sprite, red, green, blue, alpha); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite) { - sprite(type, xMin, yMin, xMax, yMax, sprite, 1F, 1F, 1F, 1F); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int argb) { - sprite(type, xMin, yMin, xMax, yMax, sprite, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - VertexConsumer buffer = buffers().getBuffer(type); - Matrix4f mat = pose.last().pose(); - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV1()); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV0()); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV0()); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV1()); //L-B - flushIfUnBatched(); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void spriteRect(RenderType type, Rectangle rectangle, int rotation, TextureAtlasSprite sprite) { - spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, sprite, 1F, 1F, 1F, 1F); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void spriteRect(RenderType type, Rectangle rectangle, int rotation, TextureAtlasSprite sprite, int argb) { - spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, sprite, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void spriteRect(RenderType type, Rectangle rectangle, int rotation, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - spriteRect(type, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, sprite, red, green, blue, alpha); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void spriteRect(RenderType type, double x, double y, double width, double height, int rotation, TextureAtlasSprite sprite) { - spriteRect(type, x, y, width, height, rotation, sprite, 1F, 1F, 1F, 1F); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void spriteRect(RenderType type, double x, double y, double width, double height, int rotation, TextureAtlasSprite sprite, int argb) { - spriteRect(type, x, y, width, height, rotation, sprite, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void spriteRect(RenderType type, double x, double y, double width, double height, int rotation, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - sprite(type, x, y, x + width, y + height, rotation, sprite, red, green, blue, alpha); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite) { - sprite(type, xMin, yMin, xMax, yMax, rotation, sprite, 1F, 1F, 1F, 1F); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, int argb) { - sprite(type, xMin, yMin, xMax, yMax, rotation, sprite, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void sprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - float[] u = { sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0() }; - float[] v = { sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0() }; - VertexConsumer buffer = buffers().getBuffer(type); - Matrix4f mat = pose.last().pose(); - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]); //L-B - flushIfUnBatched(); - } - - //Partial Sprite - - //TODO figure out if there is a way to make this work. -// /** -// * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX -// * Texture will be resized / reshaped as appropriate to fit the defined area. -// *

    -// * This is similar to {@link #partialSprite(RenderType, double, double, double, double, TextureAtlasSprite, float, float, float, float, int)} -// * Except the input uv values are in texture coordinates. So to draw a full 16x16 sprite with this you would supply 0, 0, 16, 16 -// * -// * @param rotation Rotates sprite clockwise in 90 degree steps. -// */ -// public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, int texXMin, int texYMin, int texXMax, int texYMax, int argb) { -// float width = sprite.contents().width(); -// float height = sprite.contents().height(); -// partialSprite(type, xMin, yMin, xMax, yMax, rotation, sprite, texXMin / width, texYMin / height, texXMax / width, texYMax / height, argb); -// } -// - -// /** -// * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX -// * Texture will be resized / reshaped as appropriate to fit the defined area. -// * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] -// * -// * @param rotation Rotates sprite clockwise in 90 degree steps. -// */ -// public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, int argb) { -// partialSprite(type, xMin, yMin, xMax, yMax, rotation, sprite, uMin, vMin, uMax, vMax, r(argb), g(argb), b(argb), a(argb)); -// } -// -// /** -// * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX -// * Texture will be resized / reshaped as appropriate to fit the defined area. -// * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] -// * -// * @param rotation Rotates sprite clockwise in 90 degree steps. -// */ -// public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, int rotation, TextureAtlasSprite sprite, float left, float top, float right, float bottom, float red, float green, float blue, float alpha) { -// VertexConsumer buffer = buffers().getBuffer(type); -// Matrix4f mat = pose.last().pose(); -// rotation = Math.floorMod(rotation, 4); -// -// float[] sub = {left, top, right, bottom}; -// left = sub[rotation % 4]; -// top = sub[(rotation + 1) % 4]; -// right = sub[(rotation + 2) % 4]; -// bottom = sub[(rotation + 3) % 4]; -// -// float ul = sprite.getU1() - sprite.getU0(); -// float vl = sprite.getV1() - sprite.getV0(); -// float u0 = sprite.getU0() + (left * ul); -// float v0 = sprite.getV0() + (top * vl); -// float u1 = sprite.getU0() + (right * ul); -// float v1 = sprite.getV0() + (bottom * vl); -// float[] u = {u0, u1, u1, u0}; -// float[] v = {v1, v1, v0, v0}; -// buffer.vertex(mat, (float) xMax, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).endVertex(); //R-B -// buffer.vertex(mat, (float) xMax, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).endVertex(); //R-T -// buffer.vertex(mat, (float) xMin, (float) yMin, 0).color(red, green, blue, alpha).uv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).endVertex(); //L-T -// buffer.vertex(mat, (float) xMin, (float) yMax, 0).color(red, green, blue, alpha).uv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).endVertex(); //L-B -// flushIfUnBatched(); -// } - - /** - * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - *

    - * This is similar to {@link #partialSprite(RenderType, double, double, double, double, TextureAtlasSprite, float, float, float, float, int)} - * Except the input uv values are in texture coordinates. So to draw a full 16x16 sprite with this you would supply 0, 0, 16, 16 - */ - public void partialSpriteTex(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, double texXMin, double texYMin, double texXMax, double texYMax, int argb) { - partialSpriteTex(type, xMin, yMin, xMax, yMax, sprite, texXMin, texYMin, texXMax, texYMax, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - *

    - * This is similar to {@link #partialSprite(RenderType, double, double, double, double, TextureAtlasSprite, float, float, float, float, int)} - * Except the input uv values are in texture coordinates. So to draw a full 16x16 sprite with this you would supply 0, 0, 16, 16 - */ - public void partialSpriteTex(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, double texXMin, double texYMin, double texXMax, double texYMax, float red, float green, float blue, float alpha) { - int width = sprite.contents().width(); - int height = sprite.contents().height(); - partialSprite(type, xMin, yMin, xMax, yMax, sprite, (float) texXMin / width, (float) texYMin / height, (float) texXMax / width, (float) texYMax / height, red, green, blue, alpha); - } - - /** - * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] - */ - public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, int argb) { - partialSprite(type, xMin, yMin, xMax, yMax, sprite, uMin, vMin, uMax, vMax, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a subsection of a TextureAtlasSprite using the given render type, Vertex format should be POSITION_COLOR_TEX - * Texture will be resized / reshaped as appropriate to fit the defined area. - * Valid input u/v value range is 0 to 1 [0, 0, 1, 1 would render the full sprite] - */ - public void partialSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, float red, float green, float blue, float alpha) { - VertexConsumer buffer = buffers().getBuffer(type); - Matrix4f mat = pose.last().pose(); - float u0 = sprite.getU0(); - float v0 = sprite.getV0(); - float u1 = sprite.getU1(); - float v1 = sprite.getV1(); - float ul = u1 - u0; - float vl = v1 - v0; - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMax * ul), v0 + (vMax * vl)); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMax * ul), v0 + (vMin * vl)); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMin * ul), v0 + (vMin * vl)); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u0 + (uMin * ul), v0 + (vMax * vl)); //L-B - flushIfUnBatched(); - } - - /** - * Draw a sprite tiled to fit the specified area. - * Sprite is drawn from the top-left so sprite will be tiled right and down. - */ - public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int argb) { - tileSprite(type, xMin, yMin, xMax, yMax, sprite, sprite.contents().width(), sprite.contents().height(), argb); - } - - /** - * Draw a sprite tiled to fit the specified area. - * Sprite is drawn from the top-left so sprite will be tiled right and down. - * - * @param textureWidth Set base width of the sprite texture in pixels - * @param textureHeight Set base height of the sprite texture in pixels - */ - public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int textureWidth, int textureHeight, int argb) { - tileSprite(type, xMin, yMin, xMax, yMax, sprite, textureWidth, textureHeight, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draw a sprite tiled to fit the specified area. - * Sprite is drawn from the top-left so sprite will be tiled right and down. - */ - public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, float red, float green, float blue, float alpha) { - tileSprite(type, xMin, yMin, xMax, yMax, sprite, sprite.contents().width(), sprite.contents().height(), red, green, blue, alpha); - } - - /** - * Draw a sprite tiled to fit the specified area. - * Sprite is drawn from the top-left so sprite will be tiled right and down. - * - * @param textureWidth Set base width of the sprite texture in pixels - * @param textureHeight Set base height of the sprite texture in pixels - */ - public void tileSprite(RenderType type, double xMin, double yMin, double xMax, double yMax, TextureAtlasSprite sprite, int textureWidth, int textureHeight, float red, float green, float blue, float alpha) { - double width = xMax - xMin; - double height = yMax - yMin; - if (width <= textureWidth && height <= textureHeight) { - partialSprite(type, xMin, yMin, xMax, yMax, sprite, 0F, 0F, (float) width / textureWidth, (float) height / textureHeight, red, green, blue, alpha); - } else { - Runnable draw = () -> { - double xPos = xMin; - do { - double sectionWidth = Math.min(textureWidth, xMax - xPos); - double uWidth = sectionWidth / textureWidth; - double yPos = yMin; - do { - double sectionHeight = Math.min(textureHeight, yMax - yPos); - double vWidth = sectionHeight / textureHeight; - partialSprite(type, xPos, yPos, xPos + sectionWidth, yPos + sectionHeight, sprite, 0, 0, (float) uWidth, (float) vWidth, red, green, blue, alpha); - yPos += textureHeight; - } - while (yPos < yMax); - xPos += textureWidth; - } - while (xPos < xMax); - }; - if (batchDraw) { - draw.run(); - } else { - batchDraw(draw); - } - } - } - - //Material - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void texRect(Material material, Rectangle rectangle) { - texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), 1F, 1F, 1F, 1F); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void texRect(Material material, Rectangle rectangle, int argb) { - texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void texRect(Material material, Rectangle rectangle, float red, float green, float blue, float alpha) { - texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), red, green, blue, alpha); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void texRect(Material material, double x, double y, double width, double height) { - texRect(material, x, y, width, height, 1F, 1F, 1F, 1F); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void texRect(Material material, double x, double y, double width, double height, int argb) { - texRect(material, x, y, width, height, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void texRect(Material material, double x, double y, double width, double height, float red, float green, float blue, float alpha) { - tex(material, x, y, x + width, y + height, red, green, blue, alpha); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void tex(Material material, double xMin, double yMin, double xMax, double yMax) { - tex(material, xMin, yMin, xMax, yMax, 1F, 1F, 1F, 1F); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void tex(Material material, double xMin, double yMin, double xMax, double yMax, int argb) { - tex(material, xMin, yMin, xMax, yMax, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - */ - public void tex(Material material, double xMin, double yMin, double xMax, double yMax, float red, float green, float blue, float alpha) { - TextureAtlasSprite sprite = material.sprite(); - VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); - Matrix4f mat = pose.last().pose(); - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV1()); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU1(), sprite.getV0()); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV0()); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(sprite.getU0(), sprite.getV1()); //L-B - flushIfUnBatched(); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void texRect(Material material, int rotation, Rectangle rectangle) { - texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, 1F, 1F, 1F, 1F); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void texRect(Material material, int rotation, Rectangle rectangle, int argb) { - texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void texRect(Material material, int rotation, Rectangle rectangle, float red, float green, float blue, float alpha) { - texRect(material, rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height(), rotation, red, green, blue, alpha); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void texRect(Material material, int rotation, double x, double y, double width, double height) { - texRect(material, x, y, width, height, rotation, 1F, 1F, 1F, 1F); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void texRect(Material material, int rotation, double x, double y, double width, double height, int argb) { - texRect(material, x, y, width, height, rotation, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void texRect(Material material, double x, double y, double width, double height, int rotation, float red, float green, float blue, float alpha) { - tex(material, x, y, x + width, y + height, rotation, red, green, blue, alpha); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void tex(Material material, int rotation, double xMin, double yMin, double xMax, double yMax) { - tex(material, xMin, yMin, xMax, yMax, rotation, 1F, 1F, 1F, 1F); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void tex(Material material, double xMin, double yMin, double xMax, double yMax, int rotation, int argb) { - tex(material, xMin, yMin, xMax, yMax, rotation, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * Draws a texture sprite derived from the provided material. - * Texture will be resized / reshaped as appropriate to fit the defined area. - * - * @param rotation Rotates sprite clockwise in 90 degree steps. - */ - public void tex(Material material, double xMin, double yMin, double xMax, double yMax, int rotation, float red, float green, float blue, float alpha) { - TextureAtlasSprite sprite = material.sprite(); - VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); - float[] u = { sprite.getU0(), sprite.getU1(), sprite.getU1(), sprite.getU0() }; - float[] v = { sprite.getV1(), sprite.getV1(), sprite.getV0(), sprite.getV0() }; - Matrix4f mat = pose.last().pose(); - buffer.addVertex(mat, (float) xMax, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]); //R-B - buffer.addVertex(mat, (float) xMax, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]); //R-T - buffer.addVertex(mat, (float) xMin, (float) yMin, 0).setColor(red, green, blue, alpha).setUv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]); //L-T - buffer.addVertex(mat, (float) xMin, (float) yMax, 0).setColor(red, green, blue, alpha).setUv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]); //L-B - flushIfUnBatched(); - } - - //Slice and stitch - - /** - * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. - * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. - * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. - */ - public void dynamicTex(Material material, Rectangle rectangle, Borders borders, int argb) { - dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), (int) borders.top(), (int) borders.left(), (int) borders.bottom(), (int) borders.right(), argb); - } - - /** - * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. - * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. - * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. - */ - public void dynamicTex(Material material, Rectangle rectangle, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int argb) { - dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), topBorder, leftBorder, bottomBorder, rightBorder, argb); - } - - /** - * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. - * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. - * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. - */ - public void dynamicTex(Material material, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int argb) { - dynamicTex(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, r(argb), g(argb), b(argb), a(argb)); - } - - /** - * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. - * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. - * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. - */ - public void dynamicTex(Material material, Rectangle rectangle, Borders borders) { - dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), (int) borders.top(), (int) borders.left(), (int) borders.bottom(), (int) borders.right()); - } - - /** - * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. - * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. - * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. - */ - public void dynamicTex(Material material, Rectangle rectangle, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { - dynamicTex(material, (int) rectangle.x(), (int) rectangle.y(), (int) rectangle.width(), (int) rectangle.height(), topBorder, leftBorder, bottomBorder, rightBorder); - } - - /** - * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. - * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. - * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. - */ - public void dynamicTex(Material material, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { - dynamicTex(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, 1F, 1F, 1F, 1F); - } - - /** - * This can be used to take something like a generic bordered background texture and dynamically resize it to draw at any size and shape you want. - * This is done by cutting up the texture and stitching it back to together using, cutting and tiling as required. - * The border parameters indicate the width of the borders around the texture, e.g. a vanilla gui texture has 4 pixel borders. - */ - public void dynamicTex(Material material, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder, float red, float green, float blue, float alpha) { - if (batchDraw) {//Draw batched for efficiency, unless already doing a batch draw. - dynamicTexInternal(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, red, green, blue, alpha); - } else { - batchDraw(() -> dynamicTexInternal(material, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, red, green, blue, alpha)); - } - } - - //Todo, This method can probably be made a lot more efficient. - private void dynamicTexInternal(Material material, int xPos, int yPos, int xSize, int ySize, int topBorder, int leftBorder, int bottomBorder, int rightBorder, float red, float green, float blue, float alpha) { - TextureAtlasSprite sprite = material.sprite(); - VertexConsumer buffer = material.buffer(buffers, GuiRender::texColType); - Matrix4f mat = pose.last().pose(); - SpriteContents contents = sprite.contents(); - int texWidth = contents.width(); - int texHeight = contents.height(); - int trimWidth = texWidth - leftBorder - rightBorder; - int trimHeight = texHeight - topBorder - bottomBorder; - if (xSize <= texWidth) trimWidth = Math.min(trimWidth, xSize - rightBorder); - if (xSize <= 0 || ySize <= 0 || trimWidth <= 0 || trimHeight <= 0) return; - - for (int x = 0; x < xSize; ) { - int rWidth = Math.min(xSize - x, trimWidth); - int trimU = 0; - if (x != 0) { - if (x + leftBorder + trimWidth <= xSize) { - trimU = leftBorder; - } else { - trimU = (texWidth - (xSize - x)); - } - } - - //Top & Bottom trim - bufferDynamic(buffer, mat, sprite, xPos + x, yPos, trimU, 0, rWidth, topBorder, red, green, blue, alpha); - bufferDynamic(buffer, mat, sprite, xPos + x, yPos + ySize - bottomBorder, trimU, texHeight - bottomBorder, rWidth, bottomBorder, red, green, blue, alpha); - - rWidth = Math.min(xSize - x - leftBorder - rightBorder, trimWidth); - for (int y = 0; y < ySize; ) { - int rHeight = Math.min(ySize - y - topBorder - bottomBorder, trimHeight); - int trimV; - if (y + (texHeight - topBorder - bottomBorder) <= ySize) { - trimV = topBorder; - } else { - trimV = texHeight - (ySize - y); - } - - //Left & Right trim - if (x == 0 && y + topBorder < ySize - bottomBorder) { - bufferDynamic(buffer, mat, sprite, xPos, yPos + y + topBorder, 0, trimV, leftBorder, rHeight, red, green, blue, alpha); - bufferDynamic(buffer, mat, sprite, xPos + xSize - rightBorder, yPos + y + topBorder, trimU + texWidth - rightBorder, trimV, rightBorder, rHeight, red, green, blue, alpha); - } - - //Core - if (y + topBorder < ySize - bottomBorder && x + leftBorder < xSize - rightBorder) { - bufferDynamic(buffer, mat, sprite, xPos + x + leftBorder, yPos + y + topBorder, leftBorder, topBorder, rWidth, rHeight, red, green, blue, alpha); - } - y += trimHeight; - } - x += trimWidth; - } - } - - private void bufferDynamic(VertexConsumer builder, Matrix4f mat, TextureAtlasSprite tex, int x, int y, float textureX, float textureY, int width, int height, float red, float green, float blue, float alpha) { - int w = tex.contents().width(); - int h = tex.contents().height(); - //@formatter:off - builder.addVertex(mat, x, y + height, 0).setColor(red, green, blue, alpha).setUv(tex.getU(textureX / w), tex.getV((textureY + height) / h)); - builder.addVertex(mat, x + width, y + height, 0).setColor(red, green, blue, alpha).setUv(tex.getU((textureX + width) / w), tex.getV((textureY + height) / h)); - builder.addVertex(mat, x + width, y, 0).setColor(red, green, blue, alpha).setUv(tex.getU((textureX + width) / w), tex.getV((textureY / h)) ); - builder.addVertex(mat, x, y, 0).setColor(red, green, blue, alpha).setUv(tex.getU(textureX / w), tex.getV((textureY / h)) ); - //@formatter:on - } - - //=== Strings ===// - - /** - * Draw string with shadow. - */ - public int drawString(@Nullable String message, double x, double y, int colour) { - return drawString(message, x, y, colour, true); - } - - public int drawString(@Nullable String message, double x, double y, int colour, boolean shadow) { - if (message == null) return 0; - int i = font().drawInBatch(message, (float) x, (float) y, colour, shadow, pose.last().pose(), buffers, Font.DisplayMode.NORMAL, 0, 15728880, font().isBidirectional()); - this.flushIfUnBatched(); - return i; - } - - /** - * Draw string with shadow. - */ - public int drawString(FormattedCharSequence message, double x, double y, int colour) { - return drawString(message, x, y, colour, true); - } - - public int drawString(FormattedCharSequence message, double x, double y, int colour, boolean shadow) { - int i = font().drawInBatch(message, (float) x, (float) y, colour, shadow, pose.last().pose(), buffers, Font.DisplayMode.NORMAL, 0, 15728880); - this.flushIfUnBatched(); - return i; - } - - /** - * Draw string with shadow. - */ - public int drawString(Component message, double x, double y, int colour) { - return drawString(message, x, y, colour, true); - } - - public int drawString(Component message, double x, double y, int colour, boolean shadow) { - return drawString(message.getVisualOrderText(), x, y, colour, shadow); - } - - /** - * Draw wrapped string with shadow. - */ - public void drawWordWrap(FormattedText message, double x, double y, int width, int colour) { - drawWordWrap(message, x, y, width, colour, false); - } - - public void drawWordWrap(FormattedText message, double x, double y, int width, int colour, boolean shadow) { - drawWordWrap(message, x, y, width, colour, shadow, font().lineHeight); - } - - public void drawWordWrap(FormattedText message, double x, double y, int width, int colour, boolean shadow, double spacing) { - for (FormattedCharSequence formattedcharsequence : font().split(message, width)) { - drawString(formattedcharsequence, x, y, colour, shadow); - y += spacing; - } - } - - /** - * Draw centered string with shadow. (centered on x position) - */ - public void drawCenteredString(String message, double x, double y, int colour) { - drawCenteredString(message, x, y, colour, true); - } - - public void drawCenteredString(String message, double x, double y, int colour, boolean shadow) { - drawString(message, x - font().width(message) / 2D, y, colour, shadow); - } - - /** - * Draw centered string with shadow. (centered on x position) - */ - public void drawCenteredString(Component message, double x, double y, int colour) { - drawCenteredString(message, x, y, colour, true); - } - - public void drawCenteredString(Component message, double x, double y, int colour, boolean shadow) { - FormattedCharSequence formattedcharsequence = message.getVisualOrderText(); - drawString(formattedcharsequence, x - font().width(formattedcharsequence) / 2D, y, colour, shadow); - } - - /** - * Draw centered string with shadow. (centered on x position) - */ - public void drawCenteredString(FormattedCharSequence message, double x, double y, int colour) { - drawCenteredString(message, x, y, colour, true); - } - - public void drawCenteredString(FormattedCharSequence message, double x, double y, int colour, boolean shadow) { - drawString(message, x - font().width(message) / 2D, y, colour, shadow); - } - - /** - * If text is to long ti fit between x and xMaz, the text will scroll from left to right. - * Otherwise, will render centered. - * This is mostly copied from {@link AbstractWidget#renderScrollingString(GuiGraphics, Font, Component, int, int, int, int, int)} - */ - @SuppressWarnings ("JavadocReference") - public void drawScrollingString(Component component, double x, double y, double xMax, int colour, boolean shadow) { - drawScrollingString(component, x, y, xMax, colour, shadow, true); - } - - /** - * If text is to long ti fit between x and xMaz, the text will scroll from left to right. - * Otherwise, will render centered. - * This is mostly copied from {@link net.minecraft.client.gui.components.AbstractWidget#renderScrollingString(GuiGraphics, Font, Component, int, int, int, int, int)} - */ - @SuppressWarnings ("JavadocReference") - public void drawScrollingString(Component component, double x, double y, double xMax, int colour, boolean shadow, boolean doScissor) { - int textWidth = font().width(component); - double width = xMax - x; - if (textWidth > width) { - double outside = textWidth - width; - double anim = (double) Util.getMillis() / 1000.0; - double e = Math.max(outside * 0.5, 3.0); - double f = Math.sin(1.5707963267948966 * Math.cos(6.283185307179586 * anim / e)) / 2.0 + 0.5; - double offset = Mth.lerp(f, 0.0, outside); - if (doScissor) pushScissor(x, y - 1, xMax, y + font().lineHeight + 1); - drawString(component, x - offset, y, colour, shadow); - if (doScissor) popScissor(); - } else { - drawCenteredString(component, (x + xMax) / 2, y, colour, shadow); - } - } - - //=== Tool Tips ===// - - private ItemStack tooltipStack = ItemStack.EMPTY; - - public void renderTooltip(ItemStack stack, double mouseX, double mouseY) { - renderTooltip(stack, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); - } - - public void renderTooltip(ItemStack stack, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - this.tooltipStack = stack; - this.toolTipWithImage(Screen.getTooltipFromItem(this.mc(), stack), stack.getTooltipImage(), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom); - this.tooltipStack = ItemStack.EMPTY; - } - - public void toolTipWithImage(List tooltips, Optional tooltipImage, ItemStack stack, double mouseX, double mouseY) { - toolTipWithImage(tooltips, tooltipImage, stack, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); - } - - public void toolTipWithImage(List tooltips, Optional tooltipImage, ItemStack stack, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - this.tooltipStack = stack; - this.toolTipWithImage(tooltips, tooltipImage, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom); - this.tooltipStack = ItemStack.EMPTY; - } - - public void toolTipWithImage(List tooltip, Optional tooltipImage, double mouseX, double mouseY) { - toolTipWithImage(tooltip, tooltipImage, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); - } - - public void toolTipWithImage(List tooltip, Optional tooltipImage, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - List list = ClientHooks.gatherTooltipComponents(tooltipStack, tooltip, tooltipImage, (int) mouseX, guiWidth(), guiHeight(), font()); - this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); - } - - public void renderTooltip(Component message, double mouseX, double mouseY) { - renderTooltip(message, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); - } - - public void renderTooltip(Component message, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - List list = ClientHooks.gatherTooltipComponents(tooltipStack, List.of(message), Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); - this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); - } - - public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - List list = ClientHooks.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); - this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); - } - - public void componentTooltip(List tooltips, double mouseX, double mouseY, ItemStack stack) { - componentTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f, stack); - } - - public void componentTooltip(List tooltips, double mouseX, double mouseY) { - componentTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f, ItemStack.EMPTY); - } - - public void componentTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ItemStack stack) { - this.tooltipStack = stack; - List list = ClientHooks.gatherTooltipComponents(tooltipStack, tooltips, Optional.empty(), (int) mouseX, guiWidth(), guiHeight(), font()); - this.renderTooltipInternal(list, mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); - this.tooltipStack = ItemStack.EMPTY; - } - - /** - * Warning: This tooltip method with not automatically wrap tooltip lines - */ - public void renderTooltip(List tooltips, double mouseX, double mouseY) { - renderTooltip(tooltips, mouseX, mouseY, 0xf0100010, 0xf0100010, 0x505000ff, 0x5028007f); - } - - /** - * Warning: This tooltip method with not automatically wrap tooltip lines - */ - public void renderTooltip(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - this.renderTooltipInternal(tooltips.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, DefaultTooltipPositioner.INSTANCE); - } - - /** - * Warning: This tooltip method with not automatically wrap tooltip lines - */ - public void renderTooltip(List tooltips, ClientTooltipPositioner positioner, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom) { - this.renderTooltipInternal(tooltips.stream().map(ClientTooltipComponent::create).collect(Collectors.toList()), mouseX, mouseY, backgroundTop, backgroundBottom, borderTop, borderBottom, positioner); - } - - private void renderTooltipInternal(List tooltips, double mouseX, double mouseY, int backgroundTop, int backgroundBottom, int borderTop, int borderBottom, ClientTooltipPositioner positioner) { - if (!tooltips.isEmpty()) { - RenderTooltipEvent.Pre event = ClientHooks.onRenderTooltipPre(tooltipStack, guiGraphicsWrapper(), (int) mouseX, (int) mouseY, guiWidth(), guiHeight(), tooltips, font(), positioner); - if (event.isCanceled()) return; - - int width = 0; - int height = tooltips.size() == 1 ? -2 : 0; - for (ClientTooltipComponent line : tooltips) { - width = Math.max(width, line.getWidth(event.getFont())); - height += line.getHeight(); - } - - Vector2ic position = positioner.positionTooltip(guiWidth(), guiHeight(), event.getX(), event.getY(), width, height); - int xPos = position.x(); - int yPos = Math.max(position.y(), 3); //Default positioner allows negative y-pos for some reason... - - RenderTooltipEvent.Color colorEvent = new RenderTooltipEvent.Color(tooltipStack, guiGraphicsWrapper(), (int) mouseX, (int) mouseY, font(), backgroundTop, borderTop, borderBottom, tooltips); - colorEvent.setBackgroundEnd(backgroundBottom); - NeoForge.EVENT_BUS.post(colorEvent); - - toolTipBackground(xPos - 3, yPos - 3, width + 6, height + 6, colorEvent.getBackgroundStart(), colorEvent.getBackgroundEnd(), colorEvent.getBorderStart(), colorEvent.getBorderEnd(), false); - int linePos = yPos; - - for (int i = 0; i < tooltips.size(); ++i) { - ClientTooltipComponent component = tooltips.get(i); - component.renderText(event.getFont(), xPos, linePos, pose.last().pose(), buffers); - linePos += component.getHeight() + (i == 0 ? 2 : 0); - } - - linePos = yPos; - - for (int i = 0; i < tooltips.size(); ++i) { - ClientTooltipComponent component = tooltips.get(i); - component.renderImage(event.getFont(), xPos, linePos, renderWrapper); - linePos += component.getHeight() + (i == 0 ? 2 : 0); - } - } - } - - public void renderComponentHoverEffect(@Nullable Style style, int mouseX, int mouseY) { - if (style != null && style.getHoverEvent() != null) { - HoverEvent event = style.getHoverEvent(); - HoverEvent.ItemStackInfo stackInfo = event.getValue(HoverEvent.Action.SHOW_ITEM); - if (stackInfo != null) { - renderTooltip(stackInfo.getItemStack(), mouseX, mouseY); - } else { - HoverEvent.EntityTooltipInfo tooltipInfo = event.getValue(HoverEvent.Action.SHOW_ENTITY); - if (tooltipInfo != null) { - if (mc().options.advancedItemTooltips) { - componentTooltip(tooltipInfo.getTooltipLines(), mouseX, mouseY); - } - } else { - Component component = event.getValue(HoverEvent.Action.SHOW_TEXT); - if (component != null) { - renderTooltip(font().split(component, Math.max(this.guiWidth() / 2, 200)), mouseX, mouseY); - } - } - } - } - } - - //=== ItemStacks ===// - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is 32, This must be accounted for when setting the z depth in an element using this render method. - */ - public void renderItem(ItemStack stack, double x, double y) { - renderItem(stack, x, y, 16); - } - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. - */ - public void renderItem(ItemStack stack, double x, double y, double size) { - this.renderItem(mc().player, mc().level, stack, x, y, size, 0); - } - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. - */ - public void renderItem(ItemStack stack, double x, double y, double size, int modelRand) { - this.renderItem(mc().player, mc().level, stack, x, y, size, modelRand); - } - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is 32, This must be accounted for when setting the z depth in an element using this render method. - */ - public void renderFakeItem(ItemStack stack, double x, double y) { - renderFakeItem(stack, x, y, 16); - } - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. - */ - public void renderFakeItem(ItemStack stack, double x, double y, double size) { - this.renderItem(null, mc().level, stack, x, y, size, 0); - } - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is 32, This must be accounted for when setting the z depth in an element using this render method. - */ - public void renderItem(LivingEntity entity, ItemStack stack, double x, double y, int modelRand) { - renderItem(entity, stack, x, y, 16, modelRand); - } - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. - */ - public void renderItem(LivingEntity entity, ItemStack stack, double x, double y, double size, int modelRand) { - this.renderItem(entity, entity.level(), stack, x, y, size, modelRand); - } - - /** - * Renders an item stack on the screen. - * Important Note: Required z clearance is size*2, This must be accounted for when setting the z depth in an element using this render method. - * - * @param size Width and height of the stack in pixels (Standard default is 16) - * @param modelRand A somewhat random value used in model gathering, Not very important, Can just use 0 or x/y position. - */ - public void renderItem(@Nullable LivingEntity entity, @Nullable Level level, ItemStack stack, double x, double y, double size, int modelRand) { - if (!stack.isEmpty()) { - BakedModel bakedmodel = mc().getItemRenderer().getModel(stack, level, entity, modelRand); - pose.pushPose(); - pose.translate(x + (size / 2D), y + (size / 2D), size); - try { - pose.scale((float) size, (float) -size, (float) size); - boolean flag = !bakedmodel.usesBlockLight(); - if (flag) Lighting.setupForFlatItems(); - mc().getItemRenderer().render(stack, ItemDisplayContext.GUI, false, pose, buffers, 0xf000f0, OverlayTexture.NO_OVERLAY, bakedmodel); - this.flush(); - if (flag) Lighting.setupFor3DItems(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered"); - crashreportcategory.setDetail("Item Type", () -> String.valueOf(stack.getItem())); - crashreportcategory.setDetail("Item Components", () -> String.valueOf(stack.getComponents())); - crashreportcategory.setDetail("Item Foil", () -> String.valueOf(stack.hasFoil())); - throw new ReportedException(crashreport); - } - pose.popPose(); - } - } - - /** - * Draw item decorations (Count, Damage, Cool-down) - * This should be rendered at the same position and size as the item. - * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. - * Z depth requirements are the same as the renderItem method. - */ - public void renderItemDecorations(ItemStack stack, double x, double y) { - renderItemDecorations(stack, x, y, 16); - } - - /** - * Draw item decorations (Count, Damage, Cool-down) - * This should be rendered at the same position and size as the item. - * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. - * Z depth requirements are the same as the renderItem method. - */ - public void renderItemDecorations(ItemStack stack, double x, double y, double size) { - this.renderItemDecorations(stack, x, y, size, null); - } - - /** - * Draw item decorations (Count, Damage, Cool-down) - * This should be rendered at the same position and size as the item. - * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. - * Z depth requirements are the same as the renderItem method. - */ - public void renderItemDecorations(ItemStack stack, double x, double y, @Nullable String text) { - renderItemDecorations(stack, x, y, 16, text); - } - - /** - * Draw item decorations (Count, Damage, Cool-down) - * This should be rendered at the same position and size as the item. - * There is no need to fiddle with z offsets or anything, just call renderItemDecorations after renderItem and it will work. - * Z depth requirements are the same as the renderItem method. - */ - public void renderItemDecorations(ItemStack stack, double x, double y, double size, @Nullable String text) { - if (!stack.isEmpty()) { - pose.pushPose(); - float scale = (float) size / 16F; - pose.translate(x, y, (size * 2) - 0.1); - pose.scale(scale, scale, 1F); - pose.translate(-x, -y, 0); - - if (stack.getCount() != 1 || text != null) { - String s = text == null ? String.valueOf(stack.getCount()) : text; - drawString(s, x + 19 - 2 - font().width(s), y + 6 + 3, 0xffffff, true); - } - - if (stack.isBarVisible()) { - int l = stack.getBarWidth(); - int i = stack.getBarColor(); - double j = x + 2; - double k = y + 13; - pose.translate(0.0F, 0.0F, 0.04); - fill(j, k, j + 13, k + 2, 0xff000000); - pose.translate(0.0F, 0.0F, 0.02); - fill(j, k, j + l, k + 1, i | 0xff000000); - } - - LocalPlayer localplayer = mc().player; - float f = localplayer == null ? 0.0F : localplayer.getCooldowns().getCooldownPercent(stack.getItem(), mc().getTimer().getGameTimeDeltaPartialTick(true)); - if (f > 0.0F) { - double i1 = y + Mth.floor(16.0F * (1.0F - f)); - double j1 = i1 + Mth.ceil(16.0F * f); - pose.translate(0.0F, 0.0F, 0.02); - fill(x, i1, x + 16, j1, Integer.MAX_VALUE); - } - - pose.popPose(); - if (size == 16) { - ItemDecoratorHandler.of(stack).render(guiGraphicsWrapper(), font(), stack, (int) x, (int) y); - } - } - } - - //=== Entity? ===// - - //=== Render Utils ===// - - public void pushScissorRect(Rectangle rectangle) { - pushScissorRect(rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height()); - } - - public void pushScissorRect(double x, double y, double width, double height) { - flushIfBatched(); - scissorHandler.pushGuiScissor(x, y, width, height); - } - - public void pushScissor(double xMin, double yMin, double xMax, double yMax) { - flushIfBatched(); - scissorHandler.pushGuiScissor(xMin, yMin, xMax - xMin, yMax - yMin); - } - - public void popScissor() { - scissorHandler.popScissor(); - } - - /** - * Sets the render system shader colour, Effect will vary depending on what is being rendered. - * Ideally this should be avoided in favor of render calls that accept colour. - */ - public void setColor(float red, float green, float blue, float alpha) { - this.flushIfBatched(); - RenderSystem.setShaderColor(red, green, blue, alpha); - } - - //=== Static Utils ===// - - public static boolean isInRect(double minX, double minY, double width, double height, double testX, double testY) { - return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); - } - - public static boolean isInRect(int minX, int minY, int width, int height, double testX, double testY) { - return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); - } - - /** - * Mixes the two input colours by adding up the R, G, B and A values of each input. - */ - public static int mixColours(int colour1, int colour2) { - return mixColours(colour1, colour2, false); - } - - /** - * Mixes the two input colours by adding up the R, G, B and A values of each input. - * - * @param subtract If true, subtract colour2 from colour1, otherwise add colour2 to colour1. - */ - public static int mixColours(int colour1, int colour2, boolean subtract) { - int alpha1 = colour1 >> 24 & 255; - int alpha2 = colour2 >> 24 & 255; - int red1 = colour1 >> 16 & 255; - int red2 = colour2 >> 16 & 255; - int green1 = colour1 >> 8 & 255; - int green2 = colour2 >> 8 & 255; - int blue1 = colour1 & 255; - int blue2 = colour2 & 255; - - int alpha = Mth.clamp(alpha1 + (subtract ? -alpha2 : alpha2), 0, 255); - int red = Mth.clamp(red1 + (subtract ? -red2 : red2), 0, 255); - int green = Mth.clamp(green1 + (subtract ? -green2 : green2), 0, 255); - int blue = Mth.clamp(blue1 + (subtract ? -blue2 : blue2), 0, 255); - - return (alpha & 0xFF) << 24 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | blue & 0xFF; - } - - /** - * Returns a colour half-way between the two input colours. - * The R, G, B and A channels are extracted from each input, - * Then for each chanel, a midpoint is determined, - * And a new colour is constructed based on the midpoint of each channel. - */ - public static int midColour(int colour1, int colour2) { - int alpha1 = colour1 >> 24 & 255; - int alpha2 = colour2 >> 24 & 255; - int red1 = colour1 >> 16 & 255; - int red2 = colour2 >> 16 & 255; - int green1 = colour1 >> 8 & 255; - int green2 = colour2 >> 8 & 255; - int blue1 = colour1 & 255; - int blue2 = colour2 & 255; - return (alpha2 + (alpha1 - alpha2) / 2 & 0xFF) << 24 | (red2 + (red1 - red2) / 2 & 0xFF) << 16 | (green2 + (green1 - green2) / 2 & 0xFF) << 8 | blue2 + (blue1 - blue2) / 2 & 0xFF; - } - - private static float r(int argb) { - return (argb >> 16 & 255) / 255F; - } - - private static float g(int argb) { - return (argb >> 8 & 255) / 255F; - } - - private static float b(int argb) { - return (argb & 255) / 255F; - } - - private static float a(int argb) { - return (argb >>> 24) / 255F; - } - - //Render Type Builders - - public static RenderType texType(ResourceLocation location) { - return RenderType.create("tex_type", DefaultVertexFormat.POSITION_TEX, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() - .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionTexShader)) - .setTextureState(new RenderStateShard.TextureStateShard(location, false, false)) - .setTransparencyState(RenderStateShard.TRANSLUCENT_TRANSPARENCY) - .setCullState(RenderStateShard.NO_CULL) - .createCompositeState(false)); - } - - public static RenderType texColType(ResourceLocation location) { - return RenderType.create("tex_col_type", DefaultVertexFormat.POSITION_TEX_COLOR, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() - .setShaderState(new RenderStateShard.ShaderStateShard(GameRenderer::getPositionTexColorShader)) - .setTextureState(new RenderStateShard.TextureStateShard(location, false, false)) - .setTransparencyState(RenderStateShard.TRANSLUCENT_TRANSPARENCY) - .setCullState(RenderStateShard.NO_CULL) - .createCompositeState(false)); - } - - /** - * This exists to allow thing like the Tooltip events to still function correctly, hopefully without exploding... - */ - public static class RenderWrapper extends GuiGraphics { - - private final GuiRender wrapped; - - private RenderWrapper(GuiRender wrapped) { - super(wrapped.mc(), wrapped.pose(), wrapped.buffers()); - this.wrapped = wrapped; - } - - @Override - public void drawManaged(Runnable runnable) { - wrapped.batchDraw(runnable); - } - - @Override - public void flush() { - wrapped.flush(); - } - } -} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java index 06952dec..b8138094 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java @@ -42,14 +42,14 @@ public void popScissor() { if (active != null) { active.apply(); } else { - RenderSystem.disableScissor(); +// RenderSystem.disableScissor(); } } private record ScissorState(int x, int y, int xMax, int yMax) { private ScissorState apply() { - RenderSystem.enableScissor(x, y, xMax - x, yMax - y); +// RenderSystem.enableScissor(x, y, xMax - x, yMax - y); return this; } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java b/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java index a9724798..f4f16055 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java @@ -1,7 +1,7 @@ package codechicken.lib.gui.modular.lib; import codechicken.lib.gui.modular.lib.geometry.Axis; -import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.Minecraft; import org.jetbrains.annotations.Nullable; import java.util.function.Consumer; @@ -113,7 +113,7 @@ public double sliderRatio() { @Override public boolean canScroll(Axis scrollAxis) { //Controls scrolling left and right when shift key is down. - return (scrollAxis == Axis.Y) != Screen.hasShiftDown(); + return (scrollAxis == Axis.Y) != Minecraft.getInstance().hasShiftDown(); } }; } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java index 0f1d5cfc..3e56c1c0 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java @@ -1,13 +1,18 @@ package codechicken.lib.gui.modular.lib; import codechicken.lib.gui.modular.elements.GuiElement; +import net.covers1624.quack.collection.FastStream; import net.covers1624.quack.util.SneakyUtils; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; +import net.minecraft.client.gui.screens.inventory.tooltip.DefaultTooltipPositioner; +import net.minecraft.locale.Language; import net.minecraft.network.chat.Component; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; -import java.util.Optional; import java.util.function.Supplier; /** @@ -93,15 +98,27 @@ default T setTooltip(@Nullable Supplier> tooltip, int tooltipDel /** * The method responsible for rendering element tool tips. - * Called from {@link GuiElement#renderOverlay(GuiRender, double, double, float, boolean)} + * Called from {@link GuiElement#renderOverlay(GuiGraphics, double, double, float, boolean)} */ - default boolean renderTooltip(GuiRender render, double mouseX, double mouseY) { + default boolean renderTooltip(GuiGraphics graphics, Font font, double mouseX, double mouseY) { Supplier> supplier = getTooltip(); if (supplier == null) return false; List list = supplier.get(); if (list.isEmpty()) return false; - //Run all components though split to account for newline characters in translations - render.componentTooltip(list.stream().flatMap(component -> render.font().getSplitter().splitLines(component, Integer.MAX_VALUE, component.getStyle()).stream()).toList(), mouseX, mouseY); + + graphics.renderTooltip( + font, + FastStream.of(list) + //Run all components though split to account for newline characters in translations + .flatMap(e -> font.getSplitter().splitLines(e, Integer.MAX_VALUE, e.getStyle())) + .map(Language.getInstance()::getVisualOrder) + .map(ClientTooltipComponent::create) + .toList(), + (int) mouseX, + (int) mouseY, + DefaultTooltipPositioner.INSTANCE, + null + ); return true; } } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java index d8998dd2..8bab19f7 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java @@ -1,7 +1,7 @@ package codechicken.lib.gui.modular.lib.container; import codechicken.lib.gui.modular.elements.GuiSlots; -import codechicken.lib.gui.modular.lib.GuiRender; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.MenuAccess; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.Slot; @@ -17,6 +17,6 @@ public interface ContainerScreenAccess extends /** * This is the modular gui friendly method used by elements such as {@link GuiSlots} to render inventory item stacks. */ - void renderSlot(GuiRender render, Slot slot); + void doRenderSlot(GuiGraphics render, Slot slot); } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java b/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java index 4b0cb9ec..8745a71e 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java @@ -1,8 +1,9 @@ package codechicken.lib.gui.modular.lib.container; -import codechicken.lib.data.MCDataInput; import codechicken.lib.inventory.container.data.AbstractDataStore; import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import java.util.function.Supplier; @@ -12,6 +13,7 @@ * Created by brandon3055 on 09/09/2023 */ public class DataSync { + public static final int PKT_SEND_CHANGES = 255; private final ModularGuiContainerMenu containerMenu; private final AbstractDataStore dataStore; @@ -42,7 +44,7 @@ public void detectAndSend() { }); } - public void handleSyncPacket(MCDataInput buf) { + public void handleSyncPacket(RegistryFriendlyByteBuf buf) { dataStore.fromBytes(buf); } } diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/package-info.java b/src/main/java/codechicken/lib/gui/modular/lib/container/package-info.java new file mode 100644 index 00000000..3e54103f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.modular.lib.container; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java index 17f5a19a..8cc6e914 100644 --- a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java @@ -2,7 +2,6 @@ import codechicken.lib.gui.modular.elements.GuiElement; import codechicken.lib.gui.modular.lib.Constraints; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.function.Supplier; @@ -63,7 +62,6 @@ public abstract class ConstrainedGeometry> impl private boolean strictMode = false; - @NotNull public abstract GuiParent getParent(); public GeoRef getParent(GeoParam param) { diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/package-info.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/package-info.java new file mode 100644 index 00000000..ee9de084 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.modular.lib.geometry; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/item/map/package-info.java b/src/main/java/codechicken/lib/gui/modular/lib/package-info.java similarity index 60% rename from src/main/java/codechicken/lib/render/item/map/package-info.java rename to src/main/java/codechicken/lib/gui/modular/lib/package-info.java index 2a862774..d757f46a 100644 --- a/src/main/java/codechicken/lib/render/item/map/package-info.java +++ b/src/main/java/codechicken/lib/gui/modular/lib/package-info.java @@ -1,4 +1,4 @@ @NonNullApi -package codechicken.lib.render.item.map; +package codechicken.lib.gui.modular.lib; import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/item/package-info.java b/src/main/java/codechicken/lib/gui/modular/package-info.java similarity index 63% rename from src/main/java/codechicken/lib/render/item/package-info.java rename to src/main/java/codechicken/lib/gui/modular/package-info.java index 9e594b0b..1a87becf 100644 --- a/src/main/java/codechicken/lib/render/item/package-info.java +++ b/src/main/java/codechicken/lib/gui/modular/package-info.java @@ -1,4 +1,4 @@ @NonNullApi -package codechicken.lib.render.item; +package codechicken.lib.gui.modular; import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java b/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java deleted file mode 100644 index dd707fa8..00000000 --- a/src/main/java/codechicken/lib/gui/modular/sprite/GuiTextures.java +++ /dev/null @@ -1,91 +0,0 @@ -package codechicken.lib.gui.modular.sprite; - -import net.minecraft.resources.ResourceLocation; -import net.neoforged.bus.api.IEventBus; -import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; -import net.neoforged.neoforge.data.loading.DatagenModLoader; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Supplier; - -import static codechicken.lib.CodeChickenLib.MOD_ID; -import static java.util.Objects.requireNonNull; - -/** - * Gui texture handler implementation. - * This sets up a custom atlas that will be populated with all textures in "modid:textures/gui/" - *

    - * Created by brandon3055 on 21/10/2023 - */ -public class GuiTextures { - - public static final GuiTextures CCL = new GuiTextures(MOD_ID); - - private final String modId; - private final @Nullable ModAtlasHolder atlasHolder; - private final Map materialCache = new HashMap<>(); - - public GuiTextures(String modId) { - this.modId = modId; - if (DatagenModLoader.isRunningDataGen()) { - atlasHolder = null; - } else { - atlasHolder = new ModAtlasHolder(modId, "textures/atlas/gui.png", "gui"); - } - } - - /** - * Called to initialize the {@link GuiTextures} helper - * - * @param modBus Your mod event bus. - */ - public void init(IEventBus modBus) { - modBus.addListener(this::onRegisterReloadListeners); - } - - private void onRegisterReloadListeners(RegisterClientReloadListenersEvent event) { - getAtlasHolder().init(); - event.registerReloadListener(getAtlasHolder()); - } - - /** - * @return The underlying {@link ModAtlasHolder} instance. - */ - public ModAtlasHolder getAtlasHolder() { - return requireNonNull(atlasHolder, "AtlasHolder not available when datagen is running."); - } - - /** - * Returns a cached Material for the specified gui texture. - * Warning: Do not use this if you intend to use the material with multiple render types. - * The material will cache the first render type it is used with. - * Instead use {@link #getUncached(String)} - * - * @param texture The texture path relative to "modid:gui/" - */ - public Material get(String texture) { - return materialCache.computeIfAbsent(modId + ":" + texture, e -> getUncached(texture)); - } - - public Material get(Supplier texture) { - return get(texture.get()); - } - - public Supplier getter(Supplier texture) { - return () -> get(texture.get()); - } - - /** - * Use this to retrieve a new uncached material for the specified gui texture. - * Feel free to hold onto the returned material. - * Storing it somewhere is more efficient than recreating it every render frame. - * - * @param texture The texture path relative to "modid:gui/" - * @return A new Material for the specified gui texture. - */ - public Material getUncached(String texture) { - return new Material(getAtlasHolder().atlasLocation(), ResourceLocation.fromNamespaceAndPath(modId, "gui/" + texture), getAtlasHolder()::getSprite); - } -} diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/Material.java b/src/main/java/codechicken/lib/gui/modular/sprite/Material.java deleted file mode 100644 index 68b45d17..00000000 --- a/src/main/java/codechicken/lib/gui/modular/sprite/Material.java +++ /dev/null @@ -1,104 +0,0 @@ -package codechicken.lib.gui.modular.sprite; - -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.texture.SpriteContents; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection; -import net.minecraft.client.resources.metadata.animation.FrameSize; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; - -import java.util.function.Function; - -/** - * This is similar to Minecraft's {@link net.minecraft.client.resources.model.Material} - * This contains the essential data required to render an atlas sprite. - *

    - * The primary purpose of this class is to make porting between MC versions easier. - * It also allows for loading sprites from a custom texture atlas. Minecraft's material class can only load from vanilla atlases. - *

    - * Created by brandon3055 on 20/08/2023 - */ -public class Material { - private final ResourceLocation atlasLocation; - private final ResourceLocation texture; - private final Function spriteFunction; - - @Nullable - private RenderType renderType; - @Nullable - private net.minecraft.client.resources.model.Material vanillaMat; - - public Material(ResourceLocation atlasLocation, ResourceLocation texture, Function spriteFunction) { - this.atlasLocation = atlasLocation; - this.texture = texture; - this.spriteFunction = spriteFunction; - } - - public ResourceLocation atlasLocation() { - return atlasLocation; - } - - public ResourceLocation texture() { - return texture; - } - - public TextureAtlasSprite sprite() { - return spriteFunction.apply(texture()); - } - - /** - * Returns the cached render type for this material. - * The supplied function will be used to create the render type the first time this method is called. - * - * @param typeBuilder a function that will be used to create the render type if it does not already exist. - * @return The render type for this material. - */ - public RenderType renderType(Function typeBuilder) { - if (this.renderType == null) { - this.renderType = typeBuilder.apply(atlasLocation()); - } - return this.renderType; - } - - /** - * Convenience method to create a vertex consumer using this materials render type. - * - * @param buffers bugger source. - * @param typeBuilder a function that will be used to create the render type if it does not already exist. - */ - public VertexConsumer buffer(MultiBufferSource buffers, Function typeBuilder) { - return buffers.getBuffer(renderType(typeBuilder)); - } - - public net.minecraft.client.resources.model.Material getVanillaMat() { - if (vanillaMat == null) { - vanillaMat = new net.minecraft.client.resources.model.Material(atlasLocation, texture); - } - return vanillaMat; - } - - /** - * Convenient method for getting a material from a vanilla texture atlas. - * - * @return an un-cached material from a vanilla atlas. - */ - public static Material fromAtlas(ResourceLocation atlasLocation, String texture) { - return new Material(atlasLocation, ResourceLocation.fromNamespaceAndPath(atlasLocation.getNamespace(), texture), e -> Minecraft.getInstance().getTextureAtlas(atlasLocation).apply(e)); - } - - /** - * Create a material from an existing sprite. - * Note: This will only work with sprites from a vanilla atlas. - */ - @Nullable - public static Material fromSprite(@Nullable TextureAtlasSprite sprite) { - if (sprite == null) return null; - return new Material(sprite.atlasLocation(), sprite.contents().name(), e -> Minecraft.getInstance().getTextureAtlas(sprite.atlasLocation()).apply(e)); - } -} diff --git a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java b/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java deleted file mode 100644 index d1ee738d..00000000 --- a/src/main/java/codechicken/lib/gui/modular/sprite/ModAtlasHolder.java +++ /dev/null @@ -1,107 +0,0 @@ -package codechicken.lib.gui.modular.sprite; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.SpriteLoader; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.PackResources; -import net.minecraft.server.packs.resources.PreparableReloadListener; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.profiling.ProfilerFiller; -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; -import java.util.function.Predicate; -import java.util.stream.Stream; - -/** - * Created by brandon3055 on 20/08/2023 - */ -public class ModAtlasHolder implements PreparableReloadListener, AutoCloseable { - - private final TextureAtlas textureAtlas; - private final ResourceLocation atlasLocation; - private final ResourceLocation atlasInfoLocation; - private final String modid; - - /** - * Defines a mod texture atlas. - * Must be registered as a resource reload listener via RegisterClientReloadListenersEvent - * This is all that is needed to create a custom texture atlas. - * - * @param modid The mod id of the mod registering this atlas. - * @param atlasLocation The texture atlas location. e.g. "textures/atlas/gui.png" (Will have the modid: prefix added automatically) - * @param atlasInfoLocation The path to the atlas json file relative to modid:atlases/ - * e.g. "gui" will point to modid:atlases/gui.json - */ - public ModAtlasHolder(String modid, String atlasLocation, String atlasInfoLocation) { - this.atlasInfoLocation = ResourceLocation.fromNamespaceAndPath(modid, atlasInfoLocation); - this.atlasLocation = ResourceLocation.fromNamespaceAndPath(modid, atlasLocation); - this.textureAtlas = new TextureAtlas(this.atlasLocation); - this.modid = modid; - } - - public void init() { - Minecraft.getInstance().getTextureManager().register(this.textureAtlas.location(), this.textureAtlas); - } - - public ResourceLocation atlasLocation() { - return atlasLocation; - } - - public TextureAtlasSprite getSprite(ResourceLocation resourceLocation) { - return this.textureAtlas.getSprite(resourceLocation); - } - - @Override - public final @NotNull CompletableFuture reload(PreparationBarrier prepBarrier, ResourceManager resourceManager, ProfilerFiller profiler, ProfilerFiller profiler2, Executor executor, Executor executor2) { - Objects.requireNonNull(prepBarrier); - SpriteLoader spriteLoader = SpriteLoader.create(this.textureAtlas); - return spriteLoader.loadAndStitch(new ModResourceManager(resourceManager, modid), this.atlasInfoLocation, 0, executor) - .thenCompose(SpriteLoader.Preparations::waitForUpload) - .thenCompose(prepBarrier::wait) - .thenAcceptAsync((preparations) -> this.apply(preparations, profiler2), executor2); - } - - private void apply(SpriteLoader.Preparations preparations, ProfilerFiller profilerFiller) { - profilerFiller.startTick(); - profilerFiller.push("upload"); - this.textureAtlas.upload(preparations); - profilerFiller.pop(); - profilerFiller.endTick(); - } - - @Override - public void close() { - this.textureAtlas.clearTextureData(); - } - - public static class ModResourceManager implements ResourceManager { - - private final ResourceManager wrapped; - private final String modid; - - public ModResourceManager(ResourceManager wrapped, String modid) { - this.wrapped = wrapped; - this.modid = modid; - } - - @Override - public Map listResources(String pPath, Predicate pFilter) { - return wrapped.listResources(pPath, pFilter.and(e -> e.getNamespace().equals(modid))); - } - - //@formatter:off - @Override public Set getNamespaces() { return wrapped.getNamespaces(); } - @Override public List getResourceStack(ResourceLocation pLocation) { return wrapped.getResourceStack(pLocation); } - @Override public Map> listResourceStacks(String pPath, Predicate pFilter) { return wrapped.listResourceStacks(pPath, pFilter); } - @Override public Stream listPacks() { return wrapped.listPacks(); } - @Override public Optional getResource(ResourceLocation pLocation) { return wrapped.getResource(pLocation); } - //@formatter:on - } -} diff --git a/src/main/java/codechicken/lib/gui/render/CCCustomRenderState.java b/src/main/java/codechicken/lib/gui/render/CCCustomRenderState.java new file mode 100644 index 00000000..8f99c0b8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/render/CCCustomRenderState.java @@ -0,0 +1,32 @@ +package codechicken.lib.gui.render; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.gui.navigation.ScreenRectangle; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.state.GuiElementRenderState; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix3x2f; + +/** + * Created by covers1624 on 4/11/26. + */ +public record CCCustomRenderState( + RenderPipeline pipeline, + TextureSetup textureSetup, + Matrix3x2f pose, + @Nullable ScreenRectangle scissorArea, + @Nullable ScreenRectangle bounds, + VertBuilder builder +) implements GuiElementRenderState { + + @Override + public void buildVertices(VertexConsumer consumer) { + builder.buildVertices(consumer, pose); + } + + public interface VertBuilder { + + void buildVertices(VertexConsumer consumer, Matrix3x2f pose); + } +} diff --git a/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java b/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java new file mode 100644 index 00000000..eb0407d6 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java @@ -0,0 +1,442 @@ +package codechicken.lib.gui.render; + +import codechicken.lib.colour.Colour; +import codechicken.lib.gui.modular.lib.geometry.Borders; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.state.BlitRenderState; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FormattedText; +import net.minecraft.resources.Identifier; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.Mth; +import net.minecraft.util.Util; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Nullable; + +/** + * An extension interface providing many various GUI rendering helpers. + * + * @see GuiGraphics + */ +// TODO document all these, they mostly came from the old GuiRender class from ModularGui, and all had documentation. +public interface GuiGraphicsExtension { + + private GuiGraphics self() { + return (GuiGraphics) this; + } + + default void cc$fillGradientH(Rectangle rect, int col1, int col2) { + cc$fillGradientH(rect.x(), rect.y(), rect.xMax(), rect.yMax(), col1, col2); + } + + default void cc$fillGradientH(double xMin, double yMin, double xMax, double yMax, int col1, int col2) { + cc$fillGradient(xMin, yMin, xMax, yMax, col1, col2, true); + } + + default void cc$fillGradientV(Rectangle rect, int col1, int col2) { + cc$fillGradientV(rect.x(), rect.y(), rect.xMax(), rect.yMax(), col1, col2); + } + + default void cc$fillGradientV(double xMin, double yMin, double xMax, double yMax, int col1, int col2) { + cc$fillGradient(xMin, yMin, xMax, yMax, col1, col2, true); + } + + default void cc$fill(Rectangle rect, int color) { + cc$fill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), color); + } + + default void cc$fill(double xMin, double yMin, double xMax, double yMax, int color) { + cc$fillGradient(xMin, yMin, xMax, yMax, color, color, false); + } + + default void cc$fill(RenderPipeline pipeline, double xMin, double yMin, double xMax, double yMax, int color) { + cc$fillGradient(pipeline, xMin, yMin, xMax, yMax, color, color, false); + } + + default void cc$fillGradient(double xMin, double yMin, double xMax, double yMax, int col1, int col2, boolean hoz) { + cc$fillGradient(RenderPipelines.GUI, xMin, yMin, xMax, yMax, col1, col2, hoz); + } + + default void cc$fillGradient(RenderPipeline pipeline, double xMin, double yMin, double xMax, double yMax, int col1, int col2, boolean hoz) { + cc$submitColoredRectangle(pipeline, TextureSetup.noTexture(), + xMin, xMax, + yMin, yMax, + col1, col2, + hoz + ); + } + + private void cc$submitColoredRectangle(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, int col1, int col2, boolean hoz) { + cc$submitCustom( + pipeline, texture, + x0, x1, + y0, y1, + (consumer, pose) -> { + if (hoz) { + RenderStateUtils.fillGradientH(consumer, pose, x0, x1, y0, y1, col1, col2); + } else { + RenderStateUtils.fillGradientV(consumer, pose, x0, x1, y0, y1, col1, col2); + } + } + ); + } + + default void cc$borderRect(Rectangle rect, double border, int fillColor, int borderColor) { + cc$borderFill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), border, fillColor, borderColor); + } + + default void cc$borderRect(double x, double y, double width, double height, double border, int fillColor, int borderColor) { + cc$borderFill(x, y, x + width, y + height, border, fillColor, borderColor); + } + + default void cc$borderFill(double xMin, double yMin, double xMax, double yMax, double border, int fillColor, int borderColor) { + cc$submitBorderFill(RenderPipelines.GUI, TextureSetup.noTexture(), xMin, xMax, yMin, yMax, border, fillColor, borderColor); + } + + private void cc$submitBorderFill(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, double border, int fillColor, int borderColor) { + cc$submitCustom( + pipeline, texture, + x0, x1, + y0, y1, + (consumer, pose) -> RenderStateUtils.borderFill( + consumer, pose, + x0, x1, + y0, y1, + border, + fillColor, + borderColor + ) + ); + } + + default void cc$shadedRect(Rectangle rect, double border, int topLeftColor, int bottomRightColor, int fillColor) { + cc$shadedFill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), border, topLeftColor, bottomRightColor, fillColor); + } + + default void cc$shadedRect(Rectangle rect, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$shadedFill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), border, topLeftColor, bottomRightColor, cornerMixColor, fillColor); + } + + default void cc$shadedRect(double x, double y, double width, double height, double border, int topLeftColor, int bottomRightColor, int fillColor) { + cc$shadedFill(x, y, x + width, y + height, border, topLeftColor, bottomRightColor, fillColor); + } + + default void cc$shadedRect(double x, double y, double width, double height, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$shadedFill(x, y, x + width, y + height, border, topLeftColor, bottomRightColor, cornerMixColor, fillColor); + } + + default void cc$shadedFill(double xMin, double yMin, double xMax, double yMax, double border, int topLeftColor, int bottomRightColor, int fillColor) { + cc$shadedFill(xMin, yMin, xMax, yMax, border, topLeftColor, bottomRightColor, Colour.mid(topLeftColor, bottomRightColor), fillColor); + } + + default void cc$shadedFill(double xMin, double yMin, double xMax, double yMax, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$submitShadedFill(RenderPipelines.GUI, TextureSetup.noTexture(), + xMin, xMax, + yMin, yMax, + border, + topLeftColor, bottomRightColor, + cornerMixColor, fillColor + ); + } + + private void cc$submitShadedFill(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$submitCustom( + pipeline, texture, + x0, x1, + y0, y1, + (consumer, pose) -> RenderStateUtils.shadedFill( + consumer, pose, + x0, x1, + y0, y1, + border, + topLeftColor, bottomRightColor, + cornerMixColor, fillColor + ) + ); + } + + default void cc$tooltipBackground(double x, double y, double width, double height, int bgColorTop, int bgColorBottom, int borderColorTop, int borderColorBottom, boolean empty) { + cc$tooltipBackground(RenderPipelines.GUI, TextureSetup.noTexture(), x, y, width, height, bgColorTop, bgColorBottom, borderColorTop, borderColorBottom, empty); + } + + default void cc$tooltipBackground(RenderPipeline pipeline, TextureSetup texture, double x, double y, double width, double height, int bgColorTop, int bgColorBottom, int borderColorTop, int borderColorBottom, boolean empty) { + cc$submitTooltipBackground(pipeline, texture, x, x + width, y, y + height, bgColorTop, bgColorBottom, borderColorTop, borderColorBottom, empty); + } + + private void cc$submitTooltipBackground(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, int bgColorTop, int bgColorBottom, int borderColorTop, int borderColorBottom, boolean empty) { + cc$submitCustom(pipeline, texture, x0, x1, y0, y1, (consumer, pose) -> { + RenderStateUtils.fill(consumer, pose, x0 + 1, y0, x1 - 1, y0 + 1, bgColorTop); // Top + RenderStateUtils.fill(consumer, pose, x0 + 1, y1 - 1, x1 - 1, y1, bgColorBottom); // Bottom + RenderStateUtils.fillGradientV(consumer, pose, x0, x0 + 1, y0 + 1, y1 - 1, bgColorTop, bgColorBottom); // Left + RenderStateUtils.fillGradientV(consumer, pose, x1 - 1, x1, y0 + 1, y1 - 1, bgColorTop, bgColorBottom); // Right + if (!empty) { + RenderStateUtils.fillGradientV(consumer, pose, x0 + 1, x1 - 1, y0 + 1, y1 - 1, bgColorTop, bgColorBottom); // Fill + } + RenderStateUtils.fillGradientV(consumer, pose, x0 + 1, x0 + 2, y0 + 1, y1 - 1, borderColorTop, borderColorBottom); // Left Accent + RenderStateUtils.fillGradientV(consumer, pose, x1 - 2, x1 - 1, y0 + 1, y1 - 1, borderColorTop, borderColorBottom); // Right Accent + RenderStateUtils.fill(consumer, pose, x0 + 2, y0 + 1, x1 - 2, y0 + 2, borderColorTop); // Top Accent + RenderStateUtils.fill(consumer, pose, x0 + 2, y1 - 2, x1 - 2, y1 - 1, borderColorBottom); // Bottom Accent + }); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect) { + cc$blitSprite(pipeline, sprite, rect, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, int argb) { + cc$blitSprite(pipeline, sprite, rect.x(), rect.y(), rect.width(), rect.height(), argb); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, double x, double y, double width, double height) { + cc$blitSprite(pipeline, sprite, x, y, width, height, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, double x, double y, double width, double height, int argb) { + cc$blitSprite(pipeline, sprite, 0, x, y, width, height, argb); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, Rectangle rect) { + cc$blitSprite(pipeline, sprite, rotation, rect, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, Rectangle rect, int argb) { + cc$blitSprite(pipeline, sprite, rotation, rect.x(), rect.y(), rect.width(), rect.height(), argb); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, double x, double y, double width, double height) { + cc$blitSprite(pipeline, sprite, rotation, x, y, width, height, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, double x, double y, double width, double height, int argb) { + cc$blit( + pipeline, sprite.atlasLocation(), + x, x + width, + y, y + height, + rotation, + sprite.getU0(), sprite.getU1(), + sprite.getV0(), sprite.getV1(), + argb + ); + } + + default void cc$blitPartialSprite(RenderPipeline pipeline, double x0, double y0, double x1, double y1, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax) { + cc$blitPartialSprite(pipeline, x0, y0, x1, y1, sprite, uMin, vMin, uMax, vMax, 0xFFFFFFFF); + } + + default void cc$blitPartialSprite(RenderPipeline pipeline, double x0, double y0, double x1, double y1, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, int argb) { + float u0 = sprite.getU0(); + float v0 = sprite.getV0(); + float u1 = sprite.getU1(); + float v1 = sprite.getV1(); + float ul = u1 - u0; + float vl = v1 - v0; + cc$blit( + pipeline, + sprite.atlasLocation(), + x0, x1, + y0, y1, + 0, + u0 + (uMin * ul), + u0 + (uMax * ul), + v0 + (vMin * vl), + v0 + (vMax * vl), + argb + ); + } + + private void cc$blit(RenderPipeline pipeline, Identifier atlas, + double x0, double x1, + double y0, double y1, + int rotation, + float u0, float u1, + float v0, float v1, + int color) { + var texture = self().minecraft.getTextureManager().getTexture(atlas); + cc$submitCustom( + pipeline, TextureSetup.singleTexture(texture.getTextureView(), texture.getSampler()), + x0, x1, + y0, y1, + (consumer, pose) -> RenderStateUtils.blit( + consumer, pose, + x0, x1, + y0, y1, + rotation, + u0, u1, + v0, v1, + color + ) + ); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, Borders borders) { + cc$blitDynamicSprite(pipeline, sprite, rect, borders, 0xFFFFFFFF); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, Borders borders, int color) { + cc$blitDynamicSprite(pipeline, sprite, (int) rect.x(), (int) rect.y(), (int) rect.width(), (int) rect.height(), (int) borders.top(), (int) borders.left(), (int) borders.bottom(), (int) borders.right(), color); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + cc$blitDynamicSprite(pipeline, sprite, rect, topBorder, leftBorder, bottomBorder, rightBorder, 0xFFFFFFFF); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int color) { + cc$blitDynamicSprite(pipeline, sprite, (int) rect.x(), (int) rect.y(), (int) rect.width(), (int) rect.height(), topBorder, leftBorder, bottomBorder, rightBorder, color); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + cc$blitDynamicSprite(pipeline, sprite, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, 0xFFFFFFFF); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, + int x, int y, + int width, int height, + int topBorder, int leftBorder, + int bottomBorder, int rightBorder, + int color) { + var texture = self().minecraft.getTextureManager().getTexture(sprite.atlasLocation()); + cc$submitCustom( + pipeline, + TextureSetup.singleTexture(texture.getTextureView(), texture.getSampler()), + x, x + width, + y, y + height, + (consumer, pose) -> RenderStateUtils.blitDynamic( + consumer, pose, + sprite, + x, y, + width, height, + topBorder, leftBorder, + bottomBorder, rightBorder, + color + ) + ); + } + + private void cc$submitCustom(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, CCCustomRenderState.VertBuilder builder) { + var pose = self().pose(); + var scissor = self().peekScissorStack(); + var bounds = BlitRenderState.getBounds((int) x0, (int) y0, (int) x1, (int) y1, pose, scissor); + self().submitGuiElementRenderState(new CCCustomRenderState( + pipeline, + texture, + pose, + scissor, bounds, + builder + )); + } + + default void cc$drawCenteredString(Font font, String text, double x, double y, int color) { + cc$drawCenteredString(font, text, x, y, color, true); + } + + default void cc$drawCenteredString(Font font, String text, double x, double y, int color, boolean drawShadow) { + cc$drawCenteredString(font, Language.getInstance().getVisualOrder(FormattedText.of(text)), x, y, color, drawShadow); + } + + default void cc$drawCenteredString(Font font, Component text, double x, double y, int color) { + cc$drawCenteredString(font, text, x, y, color, true); + } + + default void cc$drawCenteredString(Font font, Component text, double x, double y, int color, boolean drawShadow) { + cc$drawCenteredString(font, text.getVisualOrderText(), x, y, color, drawShadow); + } + + default void cc$drawCenteredString(Font font, FormattedCharSequence text, double x, double y, int color) { + cc$drawCenteredString(font, text, x, y, color, true); + } + + default void cc$drawCenteredString(Font font, FormattedCharSequence text, double x, double y, int color, boolean drawShadow) { + cc$drawString(font, text, x - (double) font.width(text) / 2, y, color, drawShadow); + } + + default void cc$drawString(Font font, @Nullable String text, double x, double y, int color) { + cc$drawString(font, text, x, y, color, true); + } + + default void cc$drawString(Font font, @Nullable String text, double x, double y, int color, boolean drawShadow) { + if (text == null) return; + + cc$drawString(font, Language.getInstance().getVisualOrder(FormattedText.of(text)), x, y, color, drawShadow); + } + + default void cc$drawString(Font font, Component text, double x, double y, int color) { + cc$drawString(font, text, x, y, color, true); + } + + default void cc$drawString(Font font, Component text, double x, double y, int color, boolean drawShadow) { + cc$drawString(font, text.getVisualOrderText(), x, y, color, drawShadow); + } + + default void cc$drawString(Font font, FormattedCharSequence text, double x, double y, int color) { + cc$drawString(font, text, x, y, color, true); + } + + default void cc$drawString(Font font, FormattedCharSequence text, double x, double y, int color, boolean drawShadow) { + self().drawString(font, text, (int) x, (int) y, color, drawShadow); + } + + default void cc$drawScrollingString(Font font, Component text, double x, double y, double maxX, int color, boolean shadow, boolean scissor) { + int textWidth = font.width(text); + double width = maxX - x; + if (textWidth > width) { + double outside = textWidth - width; + double anim = (double) Util.getMillis() / 1000.0; + double e = Math.max(outside * 0.5, 3.0); + double f = Math.sin(1.5707963267948966 * Math.cos(6.283185307179586 * anim / e)) / 2.0 + 0.5; + double offset = Mth.lerp(f, 0.0, outside); + if (scissor) cc$enableScissor(x, y - 1, maxX, y + font.lineHeight + 1); + cc$drawString(font, text, x - offset, y, color, shadow); + if (scissor) cc$disableScissor(); + } else { + cc$drawCenteredString(font, text, (x + maxX) / 2, y, color, shadow); + } + } + + default void cc$textHighlight(double minX, double minY, double maxX, double maxY) { + cc$fill(RenderPipelines.GUI_INVERT, minX, minY, maxX, maxY, -1); + cc$fill(RenderPipelines.GUI_TEXT_HIGHLIGHT, minX, minY, maxX, maxY, -16776961); + } + + default void cc$enableScissor(Rectangle rect) { + cc$enableScissor(rect.x(), rect.y(), rect.xMax(), rect.yMax()); + } + + default void cc$enableScissor(double minX, double minY, double maxX, double maxY) { + self().enableScissor((int) minX, (int) minY, (int) maxX, (int) maxY); + } + + /** + * Only exists for visual symetry for cc$enableScissor. + */ + default void cc$disableScissor() { + self().disableScissor(); + } + + default void cc$renderItem(ItemStack stack, double x, double y, int rand) { + self().renderItem(stack, (int) x, (int) y, rand); + } + + default void cc$renderItem(@Nullable LivingEntity entity, ItemStack stack, double x, double y, int rand) { + if (entity == null) { + self().renderItem(stack, (int) x, (int) y, rand); + } else { + self().renderItem(entity, stack, (int) x, (int) y, rand); + } + } + + default void cc$renderItemDecorations(Font font, ItemStack stack, double x, double y) { + cc$renderItemDecorations(font, stack, x, y, null); + } + + default void cc$renderItemDecorations(Font font, ItemStack stack, double x, double y, @Nullable String text) { + self().renderItemDecorations(font, stack, (int) x, (int) y, text); + } +} diff --git a/src/main/java/codechicken/lib/gui/render/RenderStateUtils.java b/src/main/java/codechicken/lib/gui/render/RenderStateUtils.java new file mode 100644 index 00000000..1e27b096 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/render/RenderStateUtils.java @@ -0,0 +1,141 @@ +package codechicken.lib.gui.render; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import org.joml.Matrix3x2f; + +/** + * Created by covers1624 on 4/11/26. + */ +public class RenderStateUtils { + + public static void fill(VertexConsumer consumer, Matrix3x2f pose, double xMin, double yMin, double xMax, double yMax, int color) { + if (xMax < xMin) { + double min = xMax; + xMax = xMin; + xMin = min; + } + if (yMax < yMin) { + double min = yMax; + yMax = yMin; + yMin = min; + } + + consumer.addVertexWith2DPose(pose, (float) xMax, (float) yMax).setColor(color); //R-B + consumer.addVertexWith2DPose(pose, (float) xMax, (float) yMin).setColor(color); //R-T + consumer.addVertexWith2DPose(pose, (float) xMin, (float) yMin).setColor(color); //L-T + consumer.addVertexWith2DPose(pose, (float) xMin, (float) yMax).setColor(color); //L-B + } + + public static void fillGradientH(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, int col1, int col2) { + consumer.addVertexWith2DPose(pose, (float) x1, (float) y1).setColor(col1); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y0).setColor(col1); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y0).setColor(col2); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y1).setColor(col2); + } + + public static void fillGradientV(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, int col1, int col2) { + consumer.addVertexWith2DPose(pose, (float) x1, (float) y1).setColor(col1); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y0).setColor(col2); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y0).setColor(col2); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y1).setColor(col1); + } + + public static void borderFill(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, double border, int borderColor, int fillColor) { + RenderStateUtils.fill(consumer, pose, x0, y0, x1, y0 + border, borderColor); //Top + RenderStateUtils.fill(consumer, pose, x0, y0 + border, x0 + border, y1 - border, borderColor); //Left + RenderStateUtils.fill(consumer, pose, x0, y1 - border, x1, y1, borderColor); //Bottom + RenderStateUtils.fill(consumer, pose, x1 - border, y0 + border, x1, y1 - border, borderColor); //Right + + //No point rendering fill if there is no fill color + if (fillColor != 0) { + RenderStateUtils.fill(consumer, pose, x0 + border, y0 + border, x1 - border, y1 - border, fillColor); //Fill + } + } + + public static void shadedFill(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + fill(consumer, pose, x0, y0, x1 - border, y0 + border, topLeftColor); //Top + fill(consumer, pose, x0, y0 + border, x0 + border, y1 - border, topLeftColor); //Left + fill(consumer, pose, x0 + border, -border, x1, y1, bottomRightColor); //Bottom + fill(consumer, pose, x1 - border, y0 + border, x1, y1 - border, bottomRightColor); //Right + fill(consumer, pose, x1 - border, y0, x1, y0 + border, cornerMixColor); //Top Right Corner + fill(consumer, pose, x0, y1 - border, x0 + border, y1, cornerMixColor); //Bottom Left Corner + + //No point rendering fill if there is no fill color + if (fillColor != 0) { + fill(consumer, pose, x0 + border, y0 + border, x1 - border, y1 - border, fillColor); //Fill + } + } + + public static void blit(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, int rotation, float u0, float u1, float v0, float v1, int color) { + float[] u = { u1, u0, u0, u1 }; + float[] v = { v0, v0, v1, v1 }; + consumer.addVertexWith2DPose(pose, (float) x0, (float) y0).setUv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).setColor(color); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y1).setUv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).setColor(color); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y1).setUv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).setColor(color); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y0).setUv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).setColor(color); + } + + public static void blitDynamic(VertexConsumer consumer, Matrix3x2f pose, TextureAtlasSprite sprite, int xPos, int yPos, int xSize, int ySize, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int color) { + SpriteContents contents = sprite.contents(); + int texWidth = contents.width(); + int texHeight = contents.height(); + int trimWidth = texWidth - leftBorder - rightBorder; + int trimHeight = texHeight - topBorder - bottomBorder; + if (xSize <= texWidth) trimWidth = Math.min(trimWidth, xSize - rightBorder); + if (xSize <= 0 || ySize <= 0 || trimWidth <= 0 || trimHeight <= 0) return; + + for (int x = 0; x < xSize; ) { + int rWidth = Math.min(xSize - x, trimWidth); + int trimU = 0; + if (x != 0) { + if (x + leftBorder + trimWidth <= xSize) { + trimU = leftBorder; + } else { + trimU = (texWidth - (xSize - x)); + } + } + + //Top & Bottom trim + emitQuad(consumer, pose, sprite, xPos + x, yPos, trimU, 0, rWidth, topBorder, color); + emitQuad(consumer, pose, sprite, xPos + x, yPos + ySize - bottomBorder, trimU, texHeight - bottomBorder, rWidth, bottomBorder, color); + + rWidth = Math.min(xSize - x - leftBorder - rightBorder, trimWidth); + for (int y = 0; y < ySize; ) { + int rHeight = Math.min(ySize - y - topBorder - bottomBorder, trimHeight); + int trimV; + if (y + (texHeight - topBorder - bottomBorder) <= ySize) { + trimV = topBorder; + } else { + trimV = texHeight - (ySize - y); + } + + //Left & Right trim + if (x == 0 && y + topBorder < ySize - bottomBorder) { + emitQuad(consumer, pose, sprite, xPos, yPos + y + topBorder, 0, trimV, leftBorder, rHeight, color); + emitQuad(consumer, pose, sprite, xPos + xSize - rightBorder, yPos + y + topBorder, trimU + texWidth - rightBorder, trimV, rightBorder, rHeight, color); + } + + //Core + if (y + topBorder < ySize - bottomBorder && x + leftBorder < xSize - rightBorder) { + emitQuad(consumer, pose, sprite, xPos + x + leftBorder, yPos + y + topBorder, leftBorder, topBorder, rWidth, rHeight, color); + } + y += trimHeight; + } + x += trimWidth; + } + } + + public static void emitQuad(VertexConsumer builder, Matrix3x2f pose, TextureAtlasSprite sprite, int x, int y, float textureX, float textureY, int width, int height, int color) { + int w = sprite.contents().width(); + int h = sprite.contents().height(); + + //@formatter:off + builder.addVertexWith2DPose(pose, x, y + height).setUv(sprite.getU(textureX / w), sprite.getV((textureY + height) / h)).setColor(color); + builder.addVertexWith2DPose(pose, x + width, y + height).setUv(sprite.getU((textureX + width) / w), sprite.getV((textureY + height) / h)).setColor(color); + builder.addVertexWith2DPose(pose, x + width, y ).setUv(sprite.getU((textureX + width) / w), sprite.getV((textureY / h)) ).setColor(color); + builder.addVertexWith2DPose(pose, x, y ).setUv(sprite.getU(textureX / w), sprite.getV((textureY / h)) ).setColor(color); + //@formatter:on + } +} diff --git a/src/main/java/codechicken/lib/render/block/package-info.java b/src/main/java/codechicken/lib/gui/render/package-info.java similarity index 62% rename from src/main/java/codechicken/lib/render/block/package-info.java rename to src/main/java/codechicken/lib/gui/render/package-info.java index 35d5040c..9beba10e 100644 --- a/src/main/java/codechicken/lib/render/block/package-info.java +++ b/src/main/java/codechicken/lib/gui/render/package-info.java @@ -1,4 +1,4 @@ @NonNullApi -package codechicken.lib.render.block; +package codechicken.lib.gui.render; import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/CCLNetwork.java b/src/main/java/codechicken/lib/internal/CCLNetwork.java new file mode 100644 index 00000000..2511cb8e --- /dev/null +++ b/src/main/java/codechicken/lib/internal/CCLNetwork.java @@ -0,0 +1,51 @@ +package codechicken.lib.internal; + +import codechicken.lib.block.ModularBlockEntity; +import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import codechicken.lib.packet.StreamNetworkChannel; +import codechicken.lib.render.particle.CustomParticleHandler; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.neoforge.network.handling.IPayloadContext; + +import static codechicken.lib.CodeChickenLib.MOD_ID; + +/** + * Created by covers1624 on 28/10/19. + */ +public class CCLNetwork { + + public static final StreamNetworkChannel CHANNEL = new StreamNetworkChannel(MOD_ID) + .optional(); + + public static final StreamNetworkChannel.BidirectionalPacketHandle GUI_SYNC = CHANNEL.playBidirectional("gui_sync", + ModularGuiContainerMenu::handlePacketFromClient, + ModularGuiContainerMenu::handlePacketFromServer + ); + + public static final StreamNetworkChannel.BidirectionalPacketHandle TILE_MESSAGE = CHANNEL.playBidirectional( + "tile_message", + CCLNetwork::handleTileMessageServer, + CCLNetwork::handleTileMessageClient + ); + + public static void init(IEventBus modBus, ModContainer container) { + CHANNEL.init(modBus, container); + + CHANNEL.configurationToClient("config_sync", ConfigSyncManager.ConfigSyncConfigurationTask::new, ConfigSyncManager::readSyncPacket); + } + + private static void handleTileMessageServer(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + if (ctx.player().level().getBlockEntity(packet.readBlockPos()) instanceof ModularBlockEntity tile) { + tile.onInternalServerPacket(packet, ctx); + } + } + + private static void handleTileMessageClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + if (ctx.player().level().getBlockEntity(packet.readBlockPos()) instanceof ModularBlockEntity tile) { + tile.onInternalClientPacket(packet, ctx); + } + } +} diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java index 83f691e3..772b197b 100644 --- a/src/main/java/codechicken/lib/internal/ClientInit.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -2,22 +2,15 @@ import codechicken.lib.CodeChickenLib; import codechicken.lib.config.ConfigCategory; -import codechicken.lib.config.ConfigSyncManager; import codechicken.lib.gui.modular.lib.CursorHelper; -import codechicken.lib.gui.modular.sprite.GuiTextures; -import codechicken.lib.model.ClassModelLoader; -import codechicken.lib.model.CompositeItemModel; import codechicken.lib.render.CCRenderEventHandler; -import codechicken.lib.render.block.BlockRenderingRegistry; +import codechicken.lib.render.CCRenderPipelines; import net.covers1624.quack.util.CrashLock; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; -import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; -import net.neoforged.neoforge.client.event.ModelEvent; -import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; -import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.client.event.AddClientReloadListenersEvent; +import net.neoforged.neoforge.client.event.RegisterRenderPipelinesEvent; import static codechicken.lib.CodeChickenLib.MOD_ID; @@ -28,26 +21,15 @@ public class ClientInit { private static final CrashLock LOCK = new CrashLock("Already Initialized."); - public static boolean catchBlockRenderExceptions; - public static boolean messagePlayerOnRenderExceptionCaught; - public static void init(IEventBus modBus) { LOCK.lock(); loadClientConfig(); CCRenderEventHandler.init(); HighlightHandler.init(); - ExceptionMessageEventHandler.init(); - - GuiTextures.CCL.init(modBus); - modBus.addListener(ClientInit::onClientSetup); - modBus.addListener(ClientInit::onRegisterGeometryLoaders); modBus.addListener(ClientInit::onResourceReload); - } - - private static void onClientSetup(FMLClientSetupEvent event) { - BlockRenderingRegistry.init(); + modBus.addListener(ClientInit::onRegisterPipelines); } private static void loadClientConfig() { @@ -55,31 +37,19 @@ private static void loadClientConfig() { clientTag.delete("block_renderer_dispatcher_misc"); clientTag.delete("catchItemRenderExceptions"); clientTag.delete("attemptRecoveryOnItemRenderException"); - - catchBlockRenderExceptions = clientTag.getValue("catchBlockRenderExceptions") - .setComment( - "With this enabled, CCL will catch all exceptions thrown whilst rendering blocks.", - "If an exception is caught, the block will not be rendered." - ) - .setDefaultBoolean(true) - .getBoolean(); - messagePlayerOnRenderExceptionCaught = clientTag.getValue("messagePlayerOnRenderExceptionCaught") - .setComment( - "With this enabled, CCL will message the player upon an exception from rendering blocks or items.", - "Messages are Rate-Limited to one per 5 seconds in the event that the exception continues." - ) - .setDefaultBoolean(true) - .getBoolean(); + clientTag.delete("catchBlockRenderExceptions"); + clientTag.delete("messagePlayerOnRenderExceptionCaught"); clientTag.save(); } - private static void onRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register(ResourceLocation.fromNamespaceAndPath(MOD_ID, "item_composite"), new CompositeItemModel()); - event.register(ResourceLocation.fromNamespaceAndPath(MOD_ID, "class"), new ClassModelLoader()); + private static void onResourceReload(AddClientReloadListenersEvent event) { + event.addListener(Identifier.fromNamespaceAndPath(MOD_ID, "cursor_helper"), (ResourceManagerReloadListener) e -> CursorHelper.onResourceReload()); } - private static void onResourceReload(RegisterClientReloadListenersEvent event) { - event.registerReloadListener((ResourceManagerReloadListener) e -> CursorHelper.onResourceReload()); + private static void onRegisterPipelines(RegisterRenderPipelinesEvent event) { + event.registerPipeline(CCRenderPipelines.SOLID_TRIANGLES); + event.registerPipeline(CCRenderPipelines.POSITION_COLOR); + event.registerPipeline(CCRenderPipelines.POSITION_COLOR_NO_DEPTH); } } diff --git a/src/main/java/codechicken/lib/internal/DataGenerators.java b/src/main/java/codechicken/lib/internal/DataGenerators.java index 0f09855d..f4ee4ce8 100644 --- a/src/main/java/codechicken/lib/internal/DataGenerators.java +++ b/src/main/java/codechicken/lib/internal/DataGenerators.java @@ -4,16 +4,13 @@ import codechicken.lib.util.CCLTags; import net.covers1624.quack.util.CrashLock; import net.minecraft.core.HolderLookup; -import net.minecraft.data.DataGenerator; import net.minecraft.data.PackOutput; -import net.minecraft.data.tags.ItemTagsProvider; import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.common.Mod; +import net.neoforged.fml.loading.FMLEnvironment; import net.neoforged.neoforge.common.data.BlockTagsProvider; -import net.neoforged.neoforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.common.data.ItemTagsProvider; import net.neoforged.neoforge.data.event.GatherDataEvent; import java.util.concurrent.CompletableFuture; @@ -29,25 +26,21 @@ public class DataGenerators { public static void init(IEventBus modBus) { LOCK.lock(); - modBus.addListener(DataGenerators::gatherDataGenerators); + if (FMLEnvironment.getDist().isClient()) { + modBus.addListener(DataGenerators::gatherDataGenerators); + } } - private static void gatherDataGenerators(GatherDataEvent event) { - DataGenerator gen = event.getGenerator(); - PackOutput output = gen.getPackOutput(); - CompletableFuture lookupProvider = event.getLookupProvider(); - - ExistingFileHelper files = event.getExistingFileHelper(); - BlockTags blockTagsProvider = new BlockTags(output, lookupProvider, files); - gen.addProvider(event.includeServer(), blockTagsProvider); - gen.addProvider(event.includeServer(), new ItemTags(output, lookupProvider, blockTagsProvider.contentsGetter(), files)); - gen.addProvider(event.includeClient() || event.includeServer(), new LangUS(output, LanguageProvider.getDist(event))); + private static void gatherDataGenerators(GatherDataEvent.Client event) { + event.createProvider(BlockTags::new); + event.createProvider(ItemTags::new); + event.createProvider(LangUS::new); } private static class BlockTags extends BlockTagsProvider { - public BlockTags(PackOutput output, CompletableFuture lookupProvider, ExistingFileHelper files) { - super(output, lookupProvider, MOD_ID, files); + public BlockTags(PackOutput output, CompletableFuture lookupProvider) { + super(output, lookupProvider, MOD_ID); } @Override @@ -95,8 +88,8 @@ public String getName() { private static class ItemTags extends ItemTagsProvider { - public ItemTags(PackOutput output, CompletableFuture lookupProvider, CompletableFuture> blockTagProvider, ExistingFileHelper files) { - super(output, lookupProvider, blockTagProvider, MOD_ID, files); + public ItemTags(PackOutput output, CompletableFuture lookupProvider) { + super(output, lookupProvider, MOD_ID); } @Override @@ -144,8 +137,8 @@ public String getName() { public static class LangUS extends LanguageProvider { - public LangUS(PackOutput output, Side side) { - super(output, MOD_ID, "en_us", side); + public LangUS(PackOutput output) { + super(output, MOD_ID, "en_us"); } @Override diff --git a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java b/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java deleted file mode 100644 index bab079c9..00000000 --- a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.internal; - -import net.covers1624.quack.util.CrashLock; -import net.neoforged.neoforge.client.event.ClientTickEvent; -import net.neoforged.neoforge.common.NeoForge; - -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -/** - * Created by covers1624 on 25/07/18. - */ -public class ExceptionMessageEventHandler { - - private static final CrashLock LOCK = new CrashLock("Already Initialized"); - - public static Set exceptionMessageCache = new HashSet<>(); - private static long lastExceptionClear; - - public static void init() { - LOCK.lock(); - NeoForge.EVENT_BUS.addListener(ExceptionMessageEventHandler::clientTick); - } - - private static void clientTick(ClientTickEvent.Post event) { - //Clear the known exceptions every 5 seconds. - long time = System.nanoTime(); - if (TimeUnit.NANOSECONDS.toSeconds(time - lastExceptionClear) > 5) { - lastExceptionClear = time; - exceptionMessageCache.clear(); - } - } -} diff --git a/src/main/java/codechicken/lib/internal/HighlightHandler.java b/src/main/java/codechicken/lib/internal/HighlightHandler.java index c269635f..7f701887 100644 --- a/src/main/java/codechicken/lib/internal/HighlightHandler.java +++ b/src/main/java/codechicken/lib/internal/HighlightHandler.java @@ -1,25 +1,24 @@ package codechicken.lib.internal; import codechicken.lib.colour.EnumColour; +import codechicken.lib.render.CCRenderPipelines; import codechicken.lib.render.RenderUtils; import codechicken.lib.render.buffer.TransformingVertexConsumer; import codechicken.lib.vec.Cuboid6; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexFormat; import net.covers1624.quack.util.CrashLock; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.rendertype.RenderSetup; +import net.minecraft.client.renderer.rendertype.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; import net.neoforged.neoforge.client.event.RenderLevelStageEvent; import net.neoforged.neoforge.common.NeoForge; import org.jetbrains.annotations.Nullable; -import static net.minecraft.client.renderer.RenderStateShard.*; +import static codechicken.lib.CodeChickenLib.MOD_ID; /** * Created by covers1624 on 9/06/18. @@ -35,26 +34,17 @@ public class HighlightHandler { public static BlockPos highlight; public static boolean useDepth = true; - private static final RenderType box = RenderType.create("ccl:box_depth", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, false, true, RenderType.CompositeState.builder() - .setShaderState(POSITION_COLOR_SHADER) - .setTransparencyState(TRANSLUCENT_TRANSPARENCY) - .setWriteMaskState(COLOR_WRITE) - .createCompositeState(false) + private static final RenderType box = RenderType.create( + MOD_ID + ":box", + RenderSetup.builder(CCRenderPipelines.POSITION_COLOR) + .createRenderSetup() ); - private static final DepthTestStateShard DISABLE_DEPTH = new DepthTestStateShard("none", 519) { - @Override - public void setupRenderState() { - RenderSystem.disableDepthTest(); - } - }; - - private static final RenderType boxNoDepth = RenderType.create("ccl:box_no_depth", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, false, true, RenderType.CompositeState.builder() - .setShaderState(POSITION_COLOR_SHADER) - .setTransparencyState(TRANSLUCENT_TRANSPARENCY) - .setWriteMaskState(COLOR_WRITE) - .setDepthTestState(DISABLE_DEPTH) - .createCompositeState(false) + // TODO depth toggle is broken + private static final RenderType boxNoDepth = RenderType.create( + MOD_ID + ":box_no_depth", + RenderSetup.builder(CCRenderPipelines.POSITION_COLOR_NO_DEPTH) + .createRenderSetup() ); public static void init() { @@ -62,13 +52,11 @@ public static void init() { NeoForge.EVENT_BUS.addListener(HighlightHandler::renderLevelLast); } - private static void renderLevelLast(RenderLevelStageEvent event) { - if (event.getStage() != RenderLevelStageEvent.Stage.AFTER_PARTICLES) return; - + private static void renderLevelLast(RenderLevelStageEvent.AfterParticles event) { if (highlight != null) { MultiBufferSource.BufferSource source = Minecraft.getInstance().renderBuffers().bufferSource(); Camera camera = Minecraft.getInstance().gameRenderer.getMainCamera(); - Vec3 cameraPos = camera.getPosition(); + Vec3 cameraPos = camera.position(); PoseStack pStack = event.getPoseStack(); pStack.pushPose(); diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 757bd70e..934c6d98 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -106,51 +106,52 @@ private RenderTask(ItemStack stack, int resolution, Path path) { protected abstract boolean render() throws IOException; protected NativeImage takeItemScreenshot() { - long start = System.nanoTime(); - Minecraft mc = Minecraft.getInstance(); - Matrix4fStack pStack = RenderSystem.getModelViewStack(); - GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); - - if (target == null || target.width < resolution || target.height < resolution) { - if (target == null) { - target = new RenderTarget(true) { }; - } - target.resize(resolution, resolution, Minecraft.ON_OSX); - } - - Matrix4f ortho = new Matrix4f().setOrtho(0, resolution * 16F / resolution, resolution * 16F / resolution, 0, -3000, 3000); - RenderSystem.setProjectionMatrix(ortho, VertexSorting.ORTHOGRAPHIC_Z); - - pStack.pushMatrix(); - pStack.identity(); - RenderSystem.applyModelViewMatrix(); - target.bindWrite(true); - - GL11.glClearColor(0, 0, 0, 0); - GL11.glClearDepth(1.0); - GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); - - Lighting.setupFor3DItems(); - RenderSystem.enableCull(); - long preRender = System.nanoTime(); - if (DEBUG) LOGGER.info("Setup: {}ns", preRender - start); - - guiGraphics.renderItem(stack, 0, 0); - - long postRender = System.nanoTime(); - if (DEBUG) LOGGER.info("Render: {}ns", postRender - preRender); - - NativeImage image = new NativeImage(resolution, resolution, false); - target.bindRead(); - image.downloadTexture(0, false); - image.flipY(); - if (DEBUG) LOGGER.info("Screenshot: {}ns", System.nanoTime() - postRender); - - pStack.popMatrix(); - RenderSystem.applyModelViewMatrix(); - - target.unbindWrite(); - return image; +// long start = System.nanoTime(); +// Minecraft mc = Minecraft.getInstance(); +// Matrix4fStack pStack = RenderSystem.getModelViewStack(); +// GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); +// +// if (target == null || target.width < resolution || target.height < resolution) { +// if (target == null) { +// target = new RenderTarget(true) { }; +// } +// target.resize(resolution, resolution, Minecraft.ON_OSX); +// } +// +// Matrix4f ortho = new Matrix4f().setOrtho(0, resolution * 16F / resolution, resolution * 16F / resolution, 0, -3000, 3000); +// RenderSystem.setProjectionMatrix(ortho, VertexSorting.ORTHOGRAPHIC_Z); +// +// pStack.pushMatrix(); +// pStack.identity(); +// RenderSystem.applyModelViewMatrix(); +// target.bindWrite(true); +// +// GL11.glClearColor(0, 0, 0, 0); +// GL11.glClearDepth(1.0); +// GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); +// +// Lighting.setupFor3DItems(); +// RenderSystem.enableCull(); +// long preRender = System.nanoTime(); +// if (DEBUG) LOGGER.info("Setup: {}ns", preRender - start); +// +// guiGraphics.renderItem(stack, 0, 0); +// +// long postRender = System.nanoTime(); +// if (DEBUG) LOGGER.info("Render: {}ns", postRender - preRender); +// +// NativeImage image = new NativeImage(resolution, resolution, false); +// target.bindRead(); +// image.downloadTexture(0, false); +// image.flipY(); +// if (DEBUG) LOGGER.info("Screenshot: {}ns", System.nanoTime() - postRender); +// +// pStack.popMatrix(); +// RenderSystem.applyModelViewMatrix(); +// +// target.unbindWrite(); +// return image; + return null; } } @@ -239,7 +240,7 @@ protected void serialize() throws IOException { LOGGER.info("Encoding Frame {} / {}", i + 1, frames.size()); NativeImage frame = frames.get(i); try (frame) { - encoder.addFrame(ImageIO.read(new ByteArrayInputStream(frame.asByteArray()))); +// encoder.addFrame(ImageIO.read(new ByteArrayInputStream(frame.asByteArray()))); } } encoder.finish(); diff --git a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java index 81688135..c377d159 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java @@ -6,6 +6,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.ResourceArgument; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; @@ -33,7 +34,7 @@ public class CountCommand { public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("count") - .requires(e -> e.hasPermission(2)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); diff --git a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java index fb0b8619..2ae06e65 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java @@ -7,6 +7,7 @@ import net.covers1624.quack.collection.FastStream; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.ResourceArgument; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; @@ -22,7 +23,7 @@ import java.util.Comparator; import java.util.List; import java.util.Objects; -import java.util.function.Consumer; +import java.util.function.BiConsumer; import java.util.function.Predicate; import static codechicken.lib.math.MathHelper.floor; @@ -38,7 +39,7 @@ public class KillAllCommand { public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("killall") - .requires(e -> e.hasPermission(2)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); @@ -60,16 +61,18 @@ public static void register(CommandDispatcher dispatcher, Co } private static int killAllGracefully(CommandContext ctx, @Nullable EntityType type, Predicate predicate) { - return killEntities(ctx, type, predicate, Entity::kill); + return killEntities(ctx, type, predicate, (l, e) -> e.kill(l)); } private static int killallForce(CommandContext ctx, @Nullable EntityType type, Predicate predicate) { - return killEntities(ctx, type, predicate, Entity::discard); + return killEntities(ctx, type, predicate, (l, e) -> e.discard()); } - private static int killEntities(CommandContext ctx, @Nullable EntityType type, Predicate predicate, Consumer killFunc) { + private static int killEntities(CommandContext ctx, @Nullable EntityType type, Predicate predicate, BiConsumer killFunc) { if (type == EntityType.PLAYER) { - ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.fail.player").withStyle(RED), false); + ctx.getSource().sendSuccess( + () -> Component.translatable("ccl.commands.killall.fail.player").withStyle(RED), + false); return 0; } CommandSourceStack source = ctx.getSource(); @@ -84,7 +87,7 @@ private static int killEntities(CommandContext ctx, @Nullabl .toList(); for (Entity e : entities) { - killFunc.accept(e); + killFunc.accept(world, e); int count = counts.getInt(e.getType()); counts.put(e.getType(), count + 1); } diff --git a/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java b/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java index 41d6b1b8..84e14b44 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java +++ b/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java @@ -4,6 +4,7 @@ import com.mojang.brigadier.context.CommandContext; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; import static net.minecraft.commands.Commands.literal; @@ -16,11 +17,11 @@ public class MiscCommands { public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("meminfo") - .requires(e -> e.hasPermission(4)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .executes(MiscCommands::printMemInfo) ) .then(literal("gc") - .requires(e -> e.hasPermission(4)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .executes(ctx -> { ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.gc.before"), true); printMemInfo(ctx, true); diff --git a/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java b/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java index 66b37ca2..ced8febb 100644 --- a/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java +++ b/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java @@ -4,9 +4,10 @@ import com.mojang.brigadier.context.CommandContext; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.gamerules.GameRules; import static net.minecraft.commands.Commands.literal; @@ -18,7 +19,7 @@ public class DevCommands { public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("setup_dev_world") - .requires(e -> e.hasPermission(4)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .executes(DevCommands::setupWorld) ) ); @@ -27,18 +28,15 @@ public static void register(CommandDispatcher dispatcher, Co private static int setupWorld(CommandContext ctx) { CommandSourceStack source = ctx.getSource(); MinecraftServer server = source.getServer(); - GameRules gameRules = server.getGameRules(); + GameRules gameRules = server.getWorldData().getGameRules(); for (ServerLevel level : server.getAllLevels()) { level.setWeatherParameters(6000, 0, false, false); } - gameRules.getRule(GameRules.RULE_DAYLIGHT) - .set(false, server); - gameRules.getRule(GameRules.RULE_WEATHER_CYCLE) - .set(false, server); - gameRules.getRule(GameRules.RULE_DO_TRADER_SPAWNING) - .set(false, server); + gameRules.set(GameRules.ADVANCE_TIME, false, server); + gameRules.set(GameRules.ADVANCE_WEATHER, false, server); + gameRules.set(GameRules.SPAWN_WANDERING_TRADERS, false, server); return 0; } } diff --git a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java index 1e7191d0..1358fa3e 100644 --- a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java +++ b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java @@ -13,7 +13,7 @@ import mezz.jei.api.registration.IGuiHandlerRegistration; import net.covers1624.quack.collection.FastStream; import net.minecraft.client.renderer.Rect2i; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.world.item.ItemStack; import java.util.ArrayList; @@ -28,13 +28,13 @@ @JeiPlugin public class JEIPlugin implements IModPlugin { - private static final ResourceLocation ID = ResourceLocation.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "jei_plugin"); + private static final Identifier ID = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "jei_plugin"); public JEIPlugin() { } @Override - public ResourceLocation getPluginUid() { + public Identifier getPluginUid() { return ID; } diff --git a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java deleted file mode 100644 index 32a39bb9..00000000 --- a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java +++ /dev/null @@ -1,41 +0,0 @@ -package codechicken.lib.internal.mixin; - -import codechicken.lib.render.item.IItemRenderer; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.neoforged.neoforge.client.ClientHooks; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** - * {@link IItemRenderer} model extension mixin. - *

    - * Created by covers1624 on 9/8/20. - */ -@Mixin (ItemRenderer.class) -abstract class ItemRendererMixin { - - @Inject ( - method = "render", - at = @At ("HEAD"), - cancellable = true - ) - public void onRenderItem(ItemStack stack, ItemDisplayContext context, boolean leftHand, PoseStack mStack, MultiBufferSource buffers, int packedLight, int packedOverlay, BakedModel modelIn, CallbackInfo ci) { - if (modelIn instanceof IItemRenderer) { - ci.cancel(); - mStack.pushPose(); - // If anyone doesn't return an IItemRenderer from here, your doing it wrong. - IItemRenderer renderer = (IItemRenderer) ClientHooks.handleCameraTransforms(mStack, modelIn, context, leftHand); - mStack.translate(-0.5D, -0.5D, -0.5D); - renderer.renderItem(stack, context, mStack, buffers, packedLight, packedOverlay); - mStack.popPose(); - } - } - -} diff --git a/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java b/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java deleted file mode 100644 index 0ad56358..00000000 --- a/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java +++ /dev/null @@ -1,44 +0,0 @@ -package codechicken.lib.internal.mixin; - -import codechicken.lib.render.shader.CCShaderInstance; -import com.mojang.blaze3d.shaders.Program; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceProvider; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.io.IOException; - -import static net.covers1624.quack.util.SneakyUtils.unsafeCast; - -/** - * Created by covers1624 on 9/4/22. - */ -@Mixin (ShaderInstance.class) -public abstract class ShaderInstanceMixin { - - private ShaderInstance self() { - return unsafeCast(this); - } - - @Redirect ( - method = "(Lnet/minecraft/server/packs/resources/ResourceProvider;Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/vertex/VertexFormat;)V", - at = @At ( - value = "INVOKE", - target = "Lnet/minecraft/client/renderer/ShaderInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/Program;" - ) - ) - private Program onGetOrCreate(ResourceProvider provider, Program.Type type, String s) throws IOException { - if (self() instanceof CCShaderInstance instance) { - return instance.compileProgram(provider, type, ResourceLocation.parse(s)); - } - - return callGetOrCreate(provider, type, s); - } - - @Invoker - public abstract Program callGetOrCreate(ResourceProvider provider, Program.Type type, String s); -} diff --git a/src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java b/src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java deleted file mode 100644 index 412f1820..00000000 --- a/src/main/java/codechicken/lib/internal/mixin/compat/EmbeddiumCCLMixin.java +++ /dev/null @@ -1,23 +0,0 @@ -package codechicken.lib.internal.mixin.compat; - -import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; -import org.embeddedt.embeddium.compat.ccl.CCLCompat; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Pseudo; - -/** - * Created by covers1624 on 2/7/25. - */ -@Pseudo -@Mixin (CCLCompat.class) -abstract class EmbeddiumCCLMixin { - - /** - * @author covers1624 - * @reason Its broken and CCL ships its own. - */ - @Overwrite - public static void onClientSetup(FMLClientSetupEvent event) { - } -} diff --git a/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java b/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java index ba833319..440af603 100644 --- a/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java +++ b/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java @@ -2,6 +2,7 @@ import com.mojang.text2speech.Narrator; import net.minecraft.client.GameNarrator; +import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -13,13 +14,13 @@ abstract class GameNarratorMixin { @Redirect ( - method = "", + method = "Lnet/minecraft/client/GameNarrator;(Lnet/minecraft/client/Minecraft;)V", at = @At ( value = "INVOKE", target = "Lcom/mojang/text2speech/Narrator;getNarrator()Lcom/mojang/text2speech/Narrator;" ) ) - private Narrator redirectGetNarator() { + private Narrator redirectGetNarator(Minecraft mc) { // GO AWAY NARRATOR ERRORS! return Narrator.EMPTY; } diff --git a/src/main/java/codechicken/lib/internal/mixin/network/FriendlyByteBufMixin.java b/src/main/java/codechicken/lib/internal/mixin/network/FriendlyByteBufMixin.java new file mode 100644 index 00000000..5616cb9c --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/network/FriendlyByteBufMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.network; + +import codechicken.lib.packet.CCFriendlyByteBufExtension; +import net.minecraft.network.FriendlyByteBuf; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 7/25/26. + */ +@Mixin (FriendlyByteBuf.class) +public class FriendlyByteBufMixin implements CCFriendlyByteBufExtension { +} diff --git a/src/main/java/codechicken/lib/internal/mixin/network/RegistryFriendlyByteBufMixin.java b/src/main/java/codechicken/lib/internal/mixin/network/RegistryFriendlyByteBufMixin.java new file mode 100644 index 00000000..7a688b80 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/network/RegistryFriendlyByteBufMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.network; + +import codechicken.lib.packet.CCRegistryFriendlyByteBufExtension; +import net.minecraft.network.RegistryFriendlyByteBuf; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 7/25/26. + */ +@Mixin (RegistryFriendlyByteBuf.class) +public class RegistryFriendlyByteBufMixin implements CCRegistryFriendlyByteBufExtension { +} diff --git a/src/main/java/codechicken/lib/internal/mixin/network/package-info.java b/src/main/java/codechicken/lib/internal/mixin/network/package-info.java new file mode 100644 index 00000000..94add508 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/network/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.mixin.network; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/mixin/render/GuiGraphicsMixin.java b/src/main/java/codechicken/lib/internal/mixin/render/GuiGraphicsMixin.java new file mode 100644 index 00000000..81a0db72 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/render/GuiGraphicsMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.render; + +import codechicken.lib.gui.render.GuiGraphicsExtension; +import net.minecraft.client.gui.GuiGraphics; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 7/25/26. + */ +@Mixin (GuiGraphics.class) +public class GuiGraphicsMixin implements GuiGraphicsExtension { +} diff --git a/src/main/java/codechicken/lib/internal/mixin/render/OrderedSubmitNodeCollectorMixin.java b/src/main/java/codechicken/lib/internal/mixin/render/OrderedSubmitNodeCollectorMixin.java new file mode 100644 index 00000000..0d6b460a --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/render/OrderedSubmitNodeCollectorMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.render; + +import codechicken.lib.render.extension.CCOrderedSubmitNodeCollectorExtension; +import net.minecraft.client.renderer.OrderedSubmitNodeCollector; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 11/2/25. + */ +@Mixin (OrderedSubmitNodeCollector.class) +public interface OrderedSubmitNodeCollectorMixin extends CCOrderedSubmitNodeCollectorExtension { +} diff --git a/src/main/java/codechicken/lib/model/pipeline/package-info.java b/src/main/java/codechicken/lib/internal/mixin/render/package-info.java similarity index 57% rename from src/main/java/codechicken/lib/model/pipeline/package-info.java rename to src/main/java/codechicken/lib/internal/mixin/render/package-info.java index c23cee20..c220d793 100644 --- a/src/main/java/codechicken/lib/model/pipeline/package-info.java +++ b/src/main/java/codechicken/lib/internal/mixin/render/package-info.java @@ -1,4 +1,4 @@ @NonNullApi -package codechicken.lib.model.pipeline; +package codechicken.lib.internal.mixin.render; import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java deleted file mode 100644 index df072e31..00000000 --- a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java +++ /dev/null @@ -1,36 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.CodeChickenLib; -import codechicken.lib.packet.PacketCustomChannel; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.bus.api.IEventBus; - -import static codechicken.lib.CodeChickenLib.MOD_ID; - -/** - * Created by covers1624 on 28/10/19. - */ -public class CCLNetwork { - - public static final ResourceLocation NET_CHANNEL = ResourceLocation.fromNamespaceAndPath(MOD_ID, "internal"); - public static final PacketCustomChannel channel = new PacketCustomChannel(NET_CHANNEL) - .optional() - .versioned(CodeChickenLib.container().getModInfo().getVersion().toString()) - .clientConfiguration(() -> ClientConfigurationPacketHandler::new) - .client(() -> ClientPacketHandler::new) - .server(() -> ServerPacketHandler::new); - - //Client handled. - public static final int C_ADD_LANDING_EFFECTS = 1; - public static final int C_GUI_SYNC = 20; - - //Server handled. - public static final int S_GUI_SYNC = 20; - - //Login handled. - public static final int L_CONFIG_SYNC = 1; - - public static void init(IEventBus modBus) { - channel.init(modBus); - } -} diff --git a/src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java deleted file mode 100644 index ad1f3b0a..00000000 --- a/src/main/java/codechicken/lib/internal/network/ClientConfigurationPacketHandler.java +++ /dev/null @@ -1,21 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.config.ConfigSyncManager; -import codechicken.lib.packet.ICustomPacketHandler; -import codechicken.lib.packet.PacketCustom; -import net.minecraft.client.Minecraft; - -import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; - -/** - * Created by covers1624 on 5/3/20. - */ -public class ClientConfigurationPacketHandler implements ICustomPacketHandler.IClientConfigurationPacketHandler { - - @Override - public void handlePacket(PacketCustom packet, Minecraft mc) { - switch (packet.getType()) { - case L_CONFIG_SYNC -> ConfigSyncManager.readSyncPacket(packet); - } - } -} diff --git a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java deleted file mode 100644 index 88ddb353..00000000 --- a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; -import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; -import codechicken.lib.packet.PacketCustom; -import codechicken.lib.render.particle.CustomParticleHandler; -import codechicken.lib.vec.Vector3; -import net.minecraft.client.Minecraft; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.state.BlockState; - -import static codechicken.lib.internal.network.CCLNetwork.C_ADD_LANDING_EFFECTS; -import static codechicken.lib.internal.network.CCLNetwork.C_GUI_SYNC; -import static java.util.Objects.requireNonNull; - -/** - * Created by covers1624 on 14/07/2017. - */ -public class ClientPacketHandler implements IClientPacketHandler { - - @Override - public void handlePacket(PacketCustom packet, Minecraft mc) { - switch (packet.getType()) { - case C_ADD_LANDING_EFFECTS -> { - BlockPos pos = packet.readPos(); - Vector3 vec = packet.readVector(); - int numParticles = packet.readVarInt(); - BlockState state = requireNonNull(mc.level).getBlockState(pos); - CustomParticleHandler.addLandingEffects(mc.level, pos, state, vec, numParticles); - } - case C_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromServer(requireNonNull(mc.player), packet); - } - } -} diff --git a/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java deleted file mode 100644 index ef18cc5c..00000000 --- a/src/main/java/codechicken/lib/internal/network/ServerPacketHandler.java +++ /dev/null @@ -1,22 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; -import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; -import codechicken.lib.packet.PacketCustom; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; - -import static codechicken.lib.internal.network.CCLNetwork.S_GUI_SYNC; - -/** - * Created by covers1624 on 14/07/2017. - */ -public class ServerPacketHandler implements IServerPacketHandler { - - @Override - public void handlePacket(PacketCustom packet, ServerPlayer sender) { - switch (packet.getType()) { - case S_GUI_SYNC -> ModularGuiContainerMenu.handlePacketFromClient(sender, packet); - } - } -} diff --git a/src/main/java/codechicken/lib/inventory/InventoryNBT.java b/src/main/java/codechicken/lib/inventory/InventoryNBT.java deleted file mode 100644 index 7656fd07..00000000 --- a/src/main/java/codechicken/lib/inventory/InventoryNBT.java +++ /dev/null @@ -1,86 +0,0 @@ -package codechicken.lib.inventory; - -import codechicken.lib.util.ArrayUtils; -import net.minecraft.core.RegistryAccess; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.Container; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; - -import java.util.Arrays; -import java.util.Objects; - -/** - * IInventory implementation which saves and loads from an NBT tag - */ -public class InventoryNBT implements Container { - - protected final RegistryAccess registries; - protected ItemStack[] items; - protected CompoundTag tag; - - public InventoryNBT(RegistryAccess registries, int size, CompoundTag tag) { - this.registries = registries; - this.tag = tag; - items = new ItemStack[size]; - ArrayUtils.fillArray(items, ItemStack.EMPTY, (Objects::isNull)); - readNBT(); - } - - private void writeNBT() { - tag.put("items", InventoryUtils.writeItemStacksToTag(registries, items, getMaxStackSize())); - } - - private void readNBT() { - if (tag.contains("items")) { - InventoryUtils.readItemStacksFromTag(registries, items, tag.getList("items", 10)); - } - } - - @Override - public int getContainerSize() { - return items.length; - } - - @Override - public boolean isEmpty() { - return ArrayUtils.count(items, (stack -> !stack.isEmpty())) <= 0; - } - - @Override - public ItemStack getItem(int slot) { - return items[slot]; - } - - @Override - public ItemStack removeItem(int slot, int amount) { - return InventoryUtils.decrStackSize(this, slot, amount); - } - - @Override - public ItemStack removeItemNoUpdate(int slot) { - return InventoryUtils.removeStackFromSlot(this, slot); - } - - @Override - public void setItem(int slot, ItemStack stack) { - items[slot] = stack; - setChanged(); - } - - @Override - public void setChanged() { - writeNBT(); - } - - @Override - public void clearContent() { - Arrays.fill(items, ItemStack.EMPTY); - setChanged(); - } - - @Override - public boolean stillValid(Player player) { - return true; - } -} diff --git a/src/main/java/codechicken/lib/inventory/InventoryUtils.java b/src/main/java/codechicken/lib/inventory/InventoryUtils.java index 28151919..33eba49d 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryUtils.java +++ b/src/main/java/codechicken/lib/inventory/InventoryUtils.java @@ -1,16 +1,11 @@ package codechicken.lib.inventory; import codechicken.lib.util.ItemUtils; -import com.google.common.base.Objects; -import net.minecraft.core.HolderLookup; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NumericTag; -import net.minecraft.nbt.Tag; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; import net.neoforged.neoforge.items.IItemHandler; public class InventoryUtils { @@ -78,41 +73,36 @@ public static int incrStackSize(ItemStack base, int addition) { /** * NBT item saving function */ - public static ListTag writeItemStacksToTag(HolderLookup.Provider registries, ItemStack[] items) { - return writeItemStacksToTag(registries, items, 64); + public static void writeItemStacksToOutput(ValueOutput output, ItemStack[] items) { + writeItemStacksToOutput(output, items, 64); } /** * NBT item saving function with support for stack sizes > 32K */ - public static ListTag writeItemStacksToTag(HolderLookup.Provider registries, ItemStack[] items, int maxQuantity) { - ListTag tagList = new ListTag(); + public static void writeItemStacksToOutput(ValueOutput output, ItemStack[] items, int maxQuantity) { + var children = output.childrenList("Items"); for (int i = 0; i < items.length; i++) { - CompoundTag tag = new CompoundTag(); - tag.putShort("Slot", (short) i); - tag.put("Item", items[i].saveOptional(registries)); - if (maxQuantity > Short.MAX_VALUE) { - tag.putInt("Quantity", items[i].getCount()); - } else if (maxQuantity > Byte.MAX_VALUE) { - tag.putShort("Quantity", (short) items[i].getCount()); - } + var stack = items[i]; + if (stack.isEmpty()) continue; - tagList.add(tag); + var child = children.addChild(); + child.putInt("Slot", i); + child.store("Item", ItemStack.SINGLE_ITEM_CODEC, stack); + child.putInt("Quantity", Math.min(stack.getCount(), maxQuantity)); } - return tagList; } /** * NBT item loading function with support for stack sizes > 32K */ - public static void readItemStacksFromTag(HolderLookup.Provider registries, ItemStack[] items, ListTag tagList) { - for (int i = 0; i < tagList.size(); i++) { - CompoundTag tag = tagList.getCompound(i); - int b = tag.getShort("Slot"); - items[b] = ItemStack.parseOptional(registries, tag.getCompound("Item")); - Tag quantTag = tag.get("Quantity"); - if (quantTag instanceof NumericTag quant) { - items[b].setCount(quant.getAsInt()); + public static void readItemStacksFromInput(ValueInput input, ItemStack[] items) { + var children = input.childrenListOrEmpty("Items"); + for (ValueInput child : children) { + var slot = child.getInt("Slot").orElseThrow(); + items[slot] = child.read("Item", ItemStack.SINGLE_ITEM_CODEC).orElse(ItemStack.EMPTY); + if (!items[slot].isEmpty()) { + items[slot].setCount(child.getInt("Quantity").orElseThrow()); } } } @@ -222,10 +212,9 @@ public static boolean canStack(ItemStack stack1, ItemStack stack2) { */ public static void consumeItem(Container inv, int slot) { ItemStack stack = inv.getItem(slot); - Item item = stack.getItem(); - if (item.hasCraftingRemainingItem(stack)) { - ItemStack container = item.getCraftingRemainingItem(stack); - inv.setItem(slot, container); + ItemStack remaining = stack.getCraftingRemainder(); + if (!remaining.isEmpty()) { + inv.setItem(slot, remaining); } else { inv.removeItem(slot, 1); } diff --git a/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java b/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java index 5d03af13..398a360e 100644 --- a/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java +++ b/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java @@ -1,6 +1,7 @@ package codechicken.lib.inventory; import net.minecraft.world.Container; +import net.minecraft.world.entity.ContainerUser; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -97,13 +98,18 @@ public boolean canPlaceItem(int slot, ItemStack stack) { } @Override - public void startOpen(Player player) { - inv.startOpen(player); + public void startOpen(ContainerUser user) { + inv.startOpen(user); } @Override - public void stopOpen(Player player) { - inv.stopOpen(player); + public void stopOpen(ContainerUser user) { + inv.stopOpen(user); + } + + @Override + public List getEntitiesWithContainerOpen() { + return inv.getEntitiesWithContainerOpen(); } @Override diff --git a/src/main/java/codechicken/lib/inventory/container/CCLMenuType.java b/src/main/java/codechicken/lib/inventory/container/CCLMenuType.java deleted file mode 100644 index 7e3ceefe..00000000 --- a/src/main/java/codechicken/lib/inventory/container/CCLMenuType.java +++ /dev/null @@ -1,73 +0,0 @@ -package codechicken.lib.inventory.container; - -import codechicken.lib.data.MCDataByteBuf; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; -import net.minecraft.network.RegistryFriendlyByteBuf; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.flag.FeatureFlag; -import net.minecraft.world.flag.FeatureFlags; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; -import net.neoforged.neoforge.network.IContainerFactory; -import org.jetbrains.annotations.Nullable; - -import java.util.function.Consumer; - -/** - * CCL sugared {@link MenuType}. - *

    - * Created by covers1624 on 28/10/19. - */ -public interface CCLMenuType extends IContainerFactory { - - static MenuType create(CCLMenuType factory) { - return new MenuType<>(factory, FeatureFlags.VANILLA_SET); - } - - static MenuType create(CCLMenuType factory, FeatureFlag... featureFlags) { - return new MenuType<>(factory, FeatureFlags.REGISTRY.subset(featureFlags)); - } - - /** - * Open a menu. - * - * @param player The player. - * @param provider The menu to open. - */ - static void openMenu(ServerPlayer player, MenuProvider provider) { - openMenu(player, provider, null); - } - - /** - * Open a menu. - * - * @param player The player. - * @param provider The menu to open. - * @param packet The packet factory for extra data. - */ - static void openMenu(ServerPlayer player, MenuProvider provider, @Nullable Consumer packet) { - if (packet != null) { - player.openMenu(provider, e -> packet.accept(new MCDataByteBuf(e))); - } else { - player.openMenu(provider); - } - } - - /** - * Overload of {@link #create(int, Inventory, RegistryFriendlyByteBuf)} using an {@link MCDataInput} instead. - * - * @param windowId The window id. - * @param inventory The player inventory. - * @param packet The packet. - * @return The new menu. - */ - T create(int windowId, Inventory inventory, @Nullable MCDataInput packet); - - @Override - default T create(int windowId, Inventory inv, @Nullable RegistryFriendlyByteBuf data) { - return create(windowId, inv, data != null ? new MCDataByteBuf(data) : null); - } -} diff --git a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java index 0965cc09..0f24e696 100644 --- a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java +++ b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java @@ -1,7 +1,6 @@ package codechicken.lib.inventory.container; -import codechicken.lib.packet.PacketCustom; -import net.minecraft.core.NonNullList; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -9,6 +8,8 @@ import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; +import java.util.List; + public abstract class ContainerExtended extends AbstractContainerMenu { @Nullable @@ -25,7 +26,7 @@ protected ContainerExtended(MenuType type, int id, Inventory inv) { public void setSynchronizer(ContainerSynchronizer delegate) { super.setSynchronizer(new ContainerSynchronizer() { @Override - public void sendInitialData(AbstractContainerMenu container, NonNullList stacks, ItemStack carried, int[] data) { + public void sendInitialData(AbstractContainerMenu container, List stacks, ItemStack carried, int[] data) { delegate.sendInitialData(container, stacks, carried, data); if (player != null) { for (int i = 0; i < stacks.size(); i++) { @@ -56,6 +57,11 @@ public void sendCarriedChange(AbstractContainerMenu container, ItemStack stack) public void sendDataChange(AbstractContainerMenu container, int slot, int data) { delegate.sendDataChange(container, slot, data); } + + @Override + public RemoteSlot createSlot() { + return delegate.createSlot(); + } }); } @@ -65,9 +71,8 @@ public void sendLargeStack(ItemStack stack, int slot, ServerPlayer player) { @Override public void clicked(int slot, int dragType, ClickType clickType, Player player) { if (slot >= 0 && slot < slots.size()) { - Slot actualSlot = getSlot(slot); - if (actualSlot instanceof SlotHandleClicks) { - ((SlotHandleClicks) actualSlot).slotClick(this, player, dragType, clickType); + if (getSlot(slot) instanceof SlotHandleClicks handleClicks) { + handleClicks.slotClick(this, player, dragType, clickType); return; } } @@ -182,14 +187,14 @@ public boolean stillValid(Player var1) { * May be called from a client packet handler to handle additional info */ - public void handleOutputPacket(PacketCustom packet) { + public void handleOutputPacket(RegistryFriendlyByteBuf packet) { } /** * May be called from a server packet handler to handle additional info */ - public void handleInputPacket(PacketCustom packet) { + public void handleInputPacket(RegistryFriendlyByteBuf packet) { } /** diff --git a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java index 3a307c96..0c9cc133 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java +++ b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java @@ -1,9 +1,8 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; import java.util.Objects; @@ -31,9 +30,9 @@ public void set(T value) { public void markDirty() { } - public abstract void toBytes(MCDataOutput buf); + public abstract void toBytes(RegistryFriendlyByteBuf buf); - public abstract void fromBytes(MCDataInput buf); + public abstract void fromBytes(RegistryFriendlyByteBuf buf); public abstract Tag toTag(HolderLookup.Provider holders); diff --git a/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java index 4d4222a1..528b6b12 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java @@ -1,11 +1,10 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.ByteTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -21,12 +20,12 @@ public BooleanData(boolean defaultValue) { } @Override - public void toBytes(MCDataOutput buf) { + public void toBytes(RegistryFriendlyByteBuf buf) { buf.writeBoolean(value); } @Override - public void fromBytes(MCDataInput buf) { + public void fromBytes(RegistryFriendlyByteBuf buf) { value = buf.readBoolean(); } @@ -37,6 +36,6 @@ public Tag toTag(HolderLookup.Provider holders) { @Override public void fromTag(HolderLookup.Provider holders, Tag tag) { - value = ((NumericTag) tag).getAsByte() != 0; + value = ((NumericTag) tag).byteValue() != 0; } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/ByteData.java b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java index eed9b431..e922ad12 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/ByteData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java @@ -1,11 +1,10 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.ByteTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -21,12 +20,12 @@ public ByteData(byte defaultValue) { } @Override - public void toBytes(MCDataOutput buf) { + public void toBytes(RegistryFriendlyByteBuf buf) { buf.writeByte(value); } @Override - public void fromBytes(MCDataInput buf) { + public void fromBytes(RegistryFriendlyByteBuf buf) { value = buf.readByte(); } @@ -37,6 +36,6 @@ public Tag toTag(HolderLookup.Provider holders) { @Override public void fromTag(HolderLookup.Provider holders, Tag tag) { - value = ((NumericTag) tag).getAsByte(); + value = ((NumericTag) tag).byteValue(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java index bd63e176..d95a07c4 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java @@ -1,11 +1,10 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.DoubleTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -21,12 +20,12 @@ public DoubleData(double defaultValue) { } @Override - public void toBytes(MCDataOutput buf) { + public void toBytes(RegistryFriendlyByteBuf buf) { buf.writeDouble(value); } @Override - public void fromBytes(MCDataInput buf) { + public void fromBytes(RegistryFriendlyByteBuf buf) { value = buf.readDouble(); } @@ -37,6 +36,6 @@ public Tag toTag(HolderLookup.Provider holders) { @Override public void fromTag(HolderLookup.Provider holders, Tag tag) { - value = ((NumericTag) tag).getAsDouble(); + value = ((NumericTag) tag).doubleValue(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/FloatData.java b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java index be891ae4..d4fd50ed 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/FloatData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java @@ -1,11 +1,10 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.FloatTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -21,12 +20,12 @@ public FloatData(float defaultValue) { } @Override - public void toBytes(MCDataOutput buf) { + public void toBytes(RegistryFriendlyByteBuf buf) { buf.writeFloat(value); } @Override - public void fromBytes(MCDataInput buf) { + public void fromBytes(RegistryFriendlyByteBuf buf) { value = buf.readFloat(); } @@ -37,6 +36,6 @@ public Tag toTag(HolderLookup.Provider holders) { @Override public void fromTag(HolderLookup.Provider holders, Tag tag) { - value = ((NumericTag) tag).getAsFloat(); + value = ((NumericTag) tag).floatValue(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java index 8472aece..4f77f4ad 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java @@ -1,10 +1,9 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.neoforged.neoforge.fluids.FluidStack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,13 +30,13 @@ public void set(FluidStack value) { } @Override - public void toBytes(MCDataOutput buf) { - buf.writeFluidStack(value); + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.cc$writeWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC, value); } @Override - public void fromBytes(MCDataInput buf) { - value = buf.readFluidStack(); + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.cc$readWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC); } @Override diff --git a/src/main/java/codechicken/lib/inventory/container/data/IntData.java b/src/main/java/codechicken/lib/inventory/container/data/IntData.java index 65a9dbe7..426b38d5 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/IntData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/IntData.java @@ -1,11 +1,10 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.IntTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -21,12 +20,12 @@ public IntData(int defaultValue) { } @Override - public void toBytes(MCDataOutput buf) { + public void toBytes(RegistryFriendlyByteBuf buf) { buf.writeVarInt(value); } @Override - public void fromBytes(MCDataInput buf) { + public void fromBytes(RegistryFriendlyByteBuf buf) { value = buf.readVarInt(); } @@ -37,6 +36,6 @@ public Tag toTag(HolderLookup.Provider holders) { @Override public void fromTag(HolderLookup.Provider holders, Tag tag) { - value = ((NumericTag) tag).getAsInt(); + value = ((NumericTag) tag).intValue(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/LongData.java b/src/main/java/codechicken/lib/inventory/container/data/LongData.java index eab6be8f..36e30d14 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/LongData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/LongData.java @@ -1,11 +1,10 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.LongTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -21,12 +20,12 @@ public LongData(long defaultValue) { } @Override - public void toBytes(MCDataOutput buf) { + public void toBytes(RegistryFriendlyByteBuf buf) { buf.writeVarLong(value); } @Override - public void fromBytes(MCDataInput buf) { + public void fromBytes(RegistryFriendlyByteBuf buf) { value = buf.readVarLong(); } @@ -37,6 +36,6 @@ public Tag toTag(HolderLookup.Provider holders) { @Override public void fromTag(HolderLookup.Provider holders, Tag tag) { - value = ((NumericTag) tag).getAsLong(); + value = ((NumericTag) tag).longValue(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/data/ShortData.java b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java index 90762caa..8fe9ebf0 100644 --- a/src/main/java/codechicken/lib/inventory/container/data/ShortData.java +++ b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java @@ -1,11 +1,10 @@ package codechicken.lib.inventory.container.data; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.ShortTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; /** * Created by brandon3055 on 09/09/2023 @@ -21,12 +20,12 @@ public ShortData(short defaultValue) { } @Override - public void toBytes(MCDataOutput buf) { + public void toBytes(RegistryFriendlyByteBuf buf) { buf.writeShort(value); } @Override - public void fromBytes(MCDataInput buf) { + public void fromBytes(RegistryFriendlyByteBuf buf) { value = buf.readShort(); } @@ -37,6 +36,6 @@ public Tag toTag(HolderLookup.Provider holders) { @Override public void fromTag(HolderLookup.Provider holders, Tag tag) { - value = ((NumericTag) tag).getAsShort(); + value = ((NumericTag) tag).shortValue(); } } diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java index e4aae084..1c5bf69e 100644 --- a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java @@ -1,16 +1,12 @@ package codechicken.lib.inventory.container.modular; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; import codechicken.lib.gui.modular.elements.GuiSlots; import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; import codechicken.lib.gui.modular.lib.container.DataSync; import codechicken.lib.gui.modular.lib.container.SlotGroup; import codechicken.lib.gui.modular.lib.geometry.GuiParent; -import codechicken.lib.internal.network.CCLNetwork; -import codechicken.lib.packet.PacketCustom; -import codechicken.lib.vec.Vector3; -import net.minecraft.network.FriendlyByteBuf; +import codechicken.lib.internal.CCLNetwork; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -18,26 +14,24 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; import java.util.function.Consumer; -import static codechicken.lib.internal.network.CCLNetwork.*; - /** * The base abstract ContainerMenu for all modular gui containers. *

    * Created by brandon3055 on 08/09/2023 */ public abstract class ModularGuiContainerMenu extends AbstractContainerMenu { + private static final Logger LOGGER = LogManager.getLogger(); public final Inventory inventory; @@ -96,15 +90,16 @@ protected SlotGroup remoteSlotGroup() { } //=== Network ===// + /** * Send a packet to the client side container. * * @param packetId message id, Can be any value from 0 to 254, 255 is used by the {@link DataSync} system. * @param packetWriter Use this callback to write your data to the packet. */ - public void sendPacketToClient(int packetId, Consumer packetWriter) { + public void sendPacketToClient(int packetId, Consumer packetWriter) { if (inventory.player instanceof ServerPlayer serverPlayer) { - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_GUI_SYNC, inventory.player.registryAccess()); + var packet = CCLNetwork.GUI_SYNC.toClient(inventory.player); packet.writeByte(containerId); packet.writeByte((byte) packetId); packetWriter.accept(packet); @@ -118,34 +113,36 @@ public void sendPacketToClient(int packetId, Consumer packetWriter * @param packetId message id, Can be any value from 0 to 255 * @param packetWriter Use this callback to write your data to the packet. */ - public void sendPacketToServer(int packetId, Consumer packetWriter) { - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, S_GUI_SYNC, inventory.player.registryAccess()); + public void sendPacketToServer(int packetId, Consumer packetWriter) { + var packet = CCLNetwork.GUI_SYNC.toServer(); packet.writeByte(containerId); packet.writeByte((byte) packetId); packetWriter.accept(packet); packet.sendToServer(); } - public static void handlePacketFromClient(Player player, MCDataInput packet) { + public static void handlePacketFromClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { int containerId = packet.readByte(); int packetId = packet.readByte() & 0xFF; + var player = ctx.player(); if (player.containerMenu instanceof ModularGuiContainerMenu menu && menu.containerId == containerId) { - menu.handlePacketFromClient(player, packetId, packet); + menu.handlePacketFromClient(packet, ctx, packetId); } } /** * Override this in your container menu implementation in order to receive packets sent via {@link #sendPacketToServer(int, Consumer)} */ - public void handlePacketFromClient(Player player, int packetId, MCDataInput packet) { + public void handlePacketFromClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx, int packetId) { } - public static void handlePacketFromServer(Player player, MCDataInput packet) { + public static void handlePacketFromServer(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { int containerId = packet.readByte(); int packetId = packet.readByte() & 0xFF; + var player = ctx.player(); if (player.containerMenu instanceof ModularGuiContainerMenu menu && menu.containerId == containerId) { - menu.handlePacketFromServer(player, packetId, packet); + menu.handlePacketFromServer(packet, ctx, packetId); } } @@ -154,7 +151,7 @@ public static void handlePacketFromServer(Player player, MCDataInput packet) { *

    * Don't forget to call super if you plan on using the {@link DataSync} system. */ - public void handlePacketFromServer(Player player, int packetId, MCDataInput packet) { + public void handlePacketFromServer(RegistryFriendlyByteBuf packet, IPayloadContext ctx, int packetId) { if (packetId == 255) { int index = packet.readByte() & 0xFF; if (dataSyncs.size() > index) { @@ -179,7 +176,7 @@ public static boolean canStacksMerge(ItemStack stack1, ItemStack stack2) { * Maybe just the ability to specify which zones each group quick-moves to... */ @Override - public ItemStack quickMoveStack(@NotNull Player player, int slotIndex) { + public ItemStack quickMoveStack(Player player, int slotIndex) { Slot slot = getSlot(slotIndex); if (!slot.hasItem()) { return ItemStack.EMPTY; diff --git a/src/main/java/codechicken/lib/math/InterpHelper.java b/src/main/java/codechicken/lib/math/InterpHelper.java index 170bedc9..4bdd06a6 100644 --- a/src/main/java/codechicken/lib/math/InterpHelper.java +++ b/src/main/java/codechicken/lib/math/InterpHelper.java @@ -18,21 +18,23 @@ package codechicken.lib.math; +import org.joml.Vector2d; + /** * @author covers1624 */ public class InterpHelper { - private final float[][] posCache = new float[4][2]; - private final float[] valCache = new float[4]; + private final Vector2d[] posCache = { new Vector2d(), new Vector2d(), new Vector2d(), new Vector2d() }; + private final double[] valCache = new double[4]; - private float x0; - private float x1; - private float y0; - private float y1; + private double x0; + private double x1; + private double y0; + private double y1; - private float rX; - private float rY; + private double rX; + private double rY; private int p00; private int p10; @@ -42,43 +44,27 @@ public class InterpHelper { /** * Resets the interp helper with the given quad. Does not care what order the vertices are in. */ - public void reset(float dx0, float dy0, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { - - float[] vec0 = this.posCache[0]; - float[] vec1 = this.posCache[1]; - float[] vec2 = this.posCache[2]; - float[] vec3 = this.posCache[3]; - - vec0[0] = dx0; - vec1[0] = dx1; - vec2[0] = dx2; - vec3[0] = dx3; - - vec0[1] = dy0; - vec1[1] = dy1; - vec2[1] = dy2; - vec3[1] = dy3; - } + public void reset(double dx0, double dy0, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { + posCache[0].set(dx0, dy0); + posCache[1].set(dx1, dy1); + posCache[2].set(dx2, dy2); + posCache[3].set(dx3, dy3); - /** - * Call when you are ready to use the InterpHelper. - */ - public void setup() { - this.p00 = 0;// Bottom Left is always first. - this.x0 = this.posCache[this.p00][0]; - this.y0 = this.posCache[this.p00][1]; + p00 = 0;// Bottom Left is always first. + x0 = posCache[p00].x; + y0 = posCache[p00].y; for (int i = 1; i < 4; i++) { - float x = this.posCache[i][0]; - float y = this.posCache[i][1]; - if (this.y0 == y) { - this.p10 = i;// Bottom right. - this.x1 = x; - } else if (this.x0 == x) { - this.p01 = i;// Top left. - this.y1 = y; + double x = posCache[i].x; + double y = posCache[i].y; + if (y0 == y) { + p10 = i;// Bottom right. + x1 = x; + } else if (x0 == x) { + p01 = i;// Top left. + y1 = y; } else { // Top right. - this.p11 = i; + p11 = i; } } } @@ -89,9 +75,29 @@ public void setup() { * @param x X interp location. * @param y Y interp location. */ - public void locate(float x, float y) { - this.rX = (x - this.x0) / (this.x1 - this.x0); - this.rY = (y - this.y0) / (this.y1 - this.y0); + public void locate(double x, double y) { + rX = (x - x0) / (x1 - x0); + rY = (y - y0) / (y1 - y0); + } + + /** + * Interpolates using the already computed coefficients. + * + * @param q0 Value at dx0 dy0 + * @param q1 Value at dx1 dy1 + * @param q2 Value at dx2 dy2 + * @param q3 Value at dx3 dy3 + * @return The result. + */ + public double interpolate(double q0, double q1, double q2, double q3) { + valCache[0] = q0; + valCache[1] = q1; + valCache[2] = q2; + valCache[3] = q3; + double f0 = (valCache[p00] * (1 - rX)) + (valCache[p10] * rX); + double f1 = (valCache[p01] * (1 - rX)) + (valCache[p11] * rX); + + return (f0 * (1 - rY)) + (f1 * rY); } /** @@ -104,13 +110,13 @@ public void locate(float x, float y) { * @return The result. */ public float interpolate(float q0, float q1, float q2, float q3) { - this.valCache[0] = q0; - this.valCache[1] = q1; - this.valCache[2] = q2; - this.valCache[3] = q3; - float f0 = (this.valCache[this.p00] * (1 - this.rX)) + (this.valCache[this.p10] * this.rX); - float f1 = (this.valCache[this.p01] * (1 - this.rX)) + (this.valCache[this.p11] * this.rX); + valCache[0] = q0; + valCache[1] = q1; + valCache[2] = q2; + valCache[3] = q3; + double f0 = (valCache[p00] * (1 - rX)) + (valCache[p10] * rX); + double f1 = (valCache[p01] * (1 - rX)) + (valCache[p11] * rX); - return (f0 * (1 - this.rY)) + (f1 * this.rY); + return (float) ((f0 * (1 - rY)) + (f1 * rY)); } } diff --git a/src/main/java/codechicken/lib/math/MathHelper.java b/src/main/java/codechicken/lib/math/MathHelper.java index 95e13884..14487d4e 100644 --- a/src/main/java/codechicken/lib/math/MathHelper.java +++ b/src/main/java/codechicken/lib/math/MathHelper.java @@ -308,4 +308,12 @@ public static int toSide(BlockPos pos) { if (pos.getX() > 0) return Direction.EAST; return null; } + + public static boolean isInRect(double minX, double minY, double width, double height, double testX, double testY) { + return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); + } + + public static boolean isInRect(int minX, int minY, int width, int height, double testX, double testY) { + return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); + } } diff --git a/src/main/java/codechicken/lib/model/CachedFormat.java b/src/main/java/codechicken/lib/model/CachedFormat.java deleted file mode 100644 index dcce52e9..00000000 --- a/src/main/java/codechicken/lib/model/CachedFormat.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model; - -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * A simple VertexFormat cache. - * This caches the existence of attributes and their indexes. - * - * @author covers1624 - */ -public class CachedFormat { - - private static final Map formatCache = new ConcurrentHashMap<>(); - public static final CachedFormat BLOCK = new CachedFormat(DefaultVertexFormat.BLOCK); - - /** - * Lookup or create the CachedFormat for a given VertexFormat. - * - * @param format The format to lookup. - * @return The CachedFormat. - */ - public static CachedFormat lookup(VertexFormat format) { - //Hotwire the common one. - if (format == DefaultVertexFormat.BLOCK) { - return BLOCK; - } - return formatCache.computeIfAbsent(format, CachedFormat::new); - } - - public final VertexFormat format; - - public final boolean hasPosition; - public final boolean hasNormal; - public final boolean hasColor; - public final boolean hasUV; - public final boolean hasOverlay; - public final boolean hasLightMap; - - public final int positionIndex; - public final int normalIndex; - public final int colorIndex; - public final int uvIndex; - public final int overlayIndex; - public final int lightMapIndex; - - public final int elementCount; - - /** - * Caches the vertex format element indexes for efficiency. - * - * @param format The format. - */ - private CachedFormat(VertexFormat format) { - this.format = format; - List elements = format.getElements(); - elementCount = elements.size(); - - boolean hasPosition = false; - boolean hasNormal = false; - boolean hasColor = false; - boolean hasUV = false; - boolean hasOverlay = false; - boolean hasLightMap = false; - - int positionIndex = -1; - int normalIndex = -1; - int colorIndex = -1; - int uvIndex = -1; - int overlayIndex = -1; - int lightMapIndex = -1; - - for (int i = 0; i < elementCount; i++) { - VertexFormatElement element = elements.get(i); - switch (element.usage()) { - case POSITION: - if (hasPosition) { - throw new IllegalStateException("Found 2 position elements.."); - } - hasPosition = true; - positionIndex = i; - break; - case NORMAL: - if (hasNormal) { - throw new IllegalStateException("Found 2 normal elements.."); - } - hasNormal = true; - normalIndex = i; - break; - case COLOR: - if (hasColor) { - throw new IllegalStateException("Found 2 color elements.."); - } - hasColor = true; - colorIndex = i; - break; - case UV: - switch (element.index()) { - case 0 -> { - if (hasUV) { - throw new IllegalStateException("Found 2 UV elements.."); - } - hasUV = true; - uvIndex = i; - } - case 1 -> { - if (hasOverlay) { - throw new IllegalStateException("Found 2 Overlay elements.."); - } - hasOverlay = true; - overlayIndex = i; - } - case 2 -> { - if (hasLightMap) { - throw new IllegalStateException("Found 2 LightMap elements.."); - } - hasLightMap = true; - lightMapIndex = i; - } - } - break; - } - } - - this.hasPosition = hasPosition; - this.hasNormal = hasNormal; - this.hasColor = hasColor; - this.hasUV = hasUV; - this.hasOverlay = hasOverlay; - this.hasLightMap = hasLightMap; - - this.positionIndex = positionIndex; - this.normalIndex = normalIndex; - this.colorIndex = colorIndex; - this.uvIndex = uvIndex; - this.overlayIndex = overlayIndex; - this.lightMapIndex = lightMapIndex; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof CachedFormat other)) { - return false; - } - return other.elementCount == elementCount && - other.positionIndex == positionIndex && - other.normalIndex == normalIndex && - other.colorIndex == colorIndex && - other.uvIndex == uvIndex && - other.lightMapIndex == lightMapIndex; - } - - @Override - public int hashCode() { - int result = 1; - result = 31 * result + elementCount; - result = 31 * result + positionIndex; - result = 31 * result + normalIndex; - result = 31 * result + colorIndex; - result = 31 * result + uvIndex; - result = 31 * result + lightMapIndex; - return result; - } -} diff --git a/src/main/java/codechicken/lib/model/ClassModelLoader.java b/src/main/java/codechicken/lib/model/ClassModelLoader.java deleted file mode 100644 index 627c232a..00000000 --- a/src/main/java/codechicken/lib/model/ClassModelLoader.java +++ /dev/null @@ -1,51 +0,0 @@ -package codechicken.lib.model; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import net.covers1624.quack.gson.JsonUtils; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.Material; -import net.minecraft.client.resources.model.ModelBaker; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; -import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; -import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.function.Function; - -import static net.covers1624.quack.util.SneakyUtils.unsafeCast; - -/** - * Created by covers1624 on 13/11/23. - */ -public class ClassModelLoader implements IGeometryLoader { - - @Override - public Geometry read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) throws JsonParseException { - try { - Class clazz = Class.forName(JsonUtils.getString(jsonObject, "class")); - Constructor ctor = unsafeCast(clazz.getConstructor()); - return new Geometry(ctor); - } catch (ClassNotFoundException | NoSuchMethodException ex) { - throw new RuntimeException(ex); - } - } - - public record Geometry(Constructor ctor) implements IUnbakedGeometry { - - @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { - try { - return ctor.newInstance(); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) { - throw new RuntimeException("Failed to construct class.", ex); - } - } - } -} diff --git a/src/main/java/codechicken/lib/model/CompositeItemModel.java b/src/main/java/codechicken/lib/model/CompositeItemModel.java deleted file mode 100644 index 07b2422c..00000000 --- a/src/main/java/codechicken/lib/model/CompositeItemModel.java +++ /dev/null @@ -1,129 +0,0 @@ -package codechicken.lib.model; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.gson.*; -import com.mojang.math.Transformation; -import net.covers1624.quack.collection.FastStream; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.*; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.neoforged.neoforge.client.model.CompositeModel; -import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; -import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; -import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; -import net.neoforged.neoforge.client.model.geometry.UnbakedGeometryHelper; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; - -/** - * Similar to Forge's {@link CompositeModel}, with support for children to have overrides. - *

    - * Created by covers1624 on 8/9/23. - */ -public class CompositeItemModel implements IGeometryLoader { - - @Override - public Geometry read(JsonObject jsonObject, JsonDeserializationContext ctx) throws JsonParseException { - JsonObject childrenObj = jsonObject.getAsJsonObject("children"); - if (childrenObj == null) throw new JsonParseException("Composite model requires children."); - - Map children = FastStream.of(childrenObj.entrySet()) - .toImmutableMap(Map.Entry::getKey, e -> ctx.deserialize(e.getValue(), BlockModel.class)); - - List itemPasses; - JsonArray itemPassesArr = jsonObject.getAsJsonArray("item_render_order"); - if (itemPassesArr != null) { - itemPasses = FastStream.of(itemPassesArr) - .map(JsonElement::getAsString) - .peek(e -> { - if (!children.containsKey(e)) { - throw new JsonParseException("Invalid child in item_render_order." + e + " does not exist."); - } - }) - .toImmutableList(); - } else { - itemPasses = ImmutableList.copyOf(children.keySet()); - } - - return new Geometry(children, itemPasses); - } - - public record Geometry(Map children, List itemPasses) implements IUnbakedGeometry { - - @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { - TextureAtlasSprite particle = spriteGetter.apply(context.getMaterial("particle")); - ModelState effectiveState = composeState(context.getRootTransform(), modelState); - - ImmutableMap children = FastStream.of(this.children.entrySet()) - .filter(e -> context.isComponentVisible(e.getKey(), true)) - .toImmutableMap(Map.Entry::getKey, e -> e.getValue().bake(baker, e.getValue(), spriteGetter, effectiveState, true)); - - ImmutableList itemPasses = FastStream.of(this.itemPasses) - .map(children::get) - .toImmutableList(); - - class Overrides extends ItemOverrides { - - @Nullable - @Override - public BakedModel resolve(BakedModel pModel, ItemStack pStack, @Nullable ClientLevel pLevel, @Nullable LivingEntity pEntity, int pSeed) { - ImmutableMap mappedChildren = FastStream.of(children.entrySet()) - .toImmutableMap(Map.Entry::getKey, e -> e.getValue().getOverrides().resolve(e.getValue(), pStack, pLevel, pEntity, pSeed)); - - ImmutableList iPasses = FastStream.of(Geometry.this.itemPasses) - .map(mappedChildren::get) - .toImmutableList(); - - return new CompositeModel.Baked( - context.isGui3d(), - context.useBlockLight(), - context.useAmbientOcclusion(), - particle, - context.getTransforms(), - this, - mappedChildren, - iPasses - ); - } - } - - return new CompositeModel.Baked( - context.isGui3d(), - context.useBlockLight(), - context.useAmbientOcclusion(), - particle, - context.getTransforms(), - new Overrides(), - children, - itemPasses - ); - } - - @Override - public void resolveParents(Function modelGetter, IGeometryBakingContext context) { - children.values().forEach(value -> value.resolveParents(modelGetter)); - } - - @Override - public Set getConfigurableComponentNames() { - return children.keySet(); - } - - private static ModelState composeState(Transformation rootTransform, ModelState state) { - if (rootTransform.isIdentity()) return state; - - return UnbakedGeometryHelper.composeRootTransformIntoModelState(state, rootTransform); - } - } -} diff --git a/src/main/java/codechicken/lib/model/DummyBakedModel.java b/src/main/java/codechicken/lib/model/DummyBakedModel.java deleted file mode 100644 index b82f2bb3..00000000 --- a/src/main/java/codechicken/lib/model/DummyBakedModel.java +++ /dev/null @@ -1,56 +0,0 @@ -package codechicken.lib.model; - -import codechicken.lib.texture.TextureUtils; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; - -import java.util.Collections; -import java.util.List; - -/** - * Simple dummy model. - * Created by covers1624 on 7/25/2016. - */ -public class DummyBakedModel implements BakedModel { - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - return Collections.emptyList(); - } - - @Override - public boolean useAmbientOcclusion() { - return false; - } - - @Override - public boolean isGui3d() { - return false; - } - - @Override - public boolean usesBlockLight() { - return false; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return TextureUtils.getMissingSprite(); - } - - @Override - public ItemOverrides getOverrides() { - return ItemOverrides.EMPTY; - } -} diff --git a/src/main/java/codechicken/lib/model/IVertexConsumer.java b/src/main/java/codechicken/lib/model/IVertexConsumer.java deleted file mode 100644 index b53466b1..00000000 --- a/src/main/java/codechicken/lib/model/IVertexConsumer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model; - -import codechicken.lib.util.VertexUtils; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; - -public interface IVertexConsumer { - - VertexFormat getVertexFormat(); - - void setQuadTint(int tint); - - void setQuadOrientation(Direction orientation); - - void setApplyDiffuseLighting(boolean diffuse); - - void setTexture(TextureAtlasSprite texture); - - void put(int element, float... data); - - /** - * Assumes the data is already completely unpacked. - * You must always copy the data from the quad provided to an internal cache. - * basically: - * this.quad.put(quad); - * - * @param quad The quad to copy data from. - */ - void put(Quad quad); - - default void put(BakedQuad quad) { - VertexUtils.putQuad(this, quad); - } -} diff --git a/src/main/java/codechicken/lib/model/IVertexProducer.java b/src/main/java/codechicken/lib/model/IVertexProducer.java deleted file mode 100644 index 4a6917c9..00000000 --- a/src/main/java/codechicken/lib/model/IVertexProducer.java +++ /dev/null @@ -1,9 +0,0 @@ -package codechicken.lib.model; - -public interface IVertexProducer { - - /** - * @param consumer consumer to receive the vertex data this producer can provide - */ - void pipe(IVertexConsumer consumer); -} diff --git a/src/main/java/codechicken/lib/model/ItemQuadBakery.java b/src/main/java/codechicken/lib/model/ItemQuadBakery.java deleted file mode 100644 index 6f47991b..00000000 --- a/src/main/java/codechicken/lib/model/ItemQuadBakery.java +++ /dev/null @@ -1,36 +0,0 @@ -package codechicken.lib.model; - -import com.mojang.math.Transformation; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.BlockElement; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.neoforge.client.model.SimpleModelState; -import net.neoforged.neoforge.client.model.geometry.UnbakedGeometryHelper; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by covers1624 on 13/02/2017. - */ -public class ItemQuadBakery { - - public static final SimpleModelState IDENTITY = new SimpleModelState(Transformation.identity()); - - public static List bakeItem(TextureAtlasSprite... sprites) { - return bakeItem(IDENTITY, sprites); - } - - public static List bakeItem(ModelState state, TextureAtlasSprite... sprites) { - List quads = new LinkedList<>(); - for (int i = 0; i < sprites.length; i++) { - TextureAtlasSprite sprite = sprites[i]; - List unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite); - quads.addAll(UnbakedGeometryHelper.bakeElements(unbaked, e -> sprite, state)); - } - return quads; - } - -} diff --git a/src/main/java/codechicken/lib/model/PerspectiveModel.java b/src/main/java/codechicken/lib/model/PerspectiveModel.java deleted file mode 100644 index 993f08b0..00000000 --- a/src/main/java/codechicken/lib/model/PerspectiveModel.java +++ /dev/null @@ -1,48 +0,0 @@ -package codechicken.lib.model; - -import codechicken.lib.util.TransformUtils; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Transformation; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.world.item.ItemDisplayContext; -import org.jetbrains.annotations.Nullable; -import org.joml.Vector3f; - -/** - * A simple {@link BakedModel} implementation, with automatic handling of - * {@link PerspectiveModelState}s. - *

    - * Created by covers1624 on 9/7/22. - * - * @see TransformUtils - */ -public interface PerspectiveModel extends BakedModel { - - /** - * The {@link PerspectiveModelState} for this model. - * - * @return The state or {@code null} for vanilla behaviour. - */ - @Nullable - PerspectiveModelState getModelState(); - - @Override - default BakedModel applyTransform(ItemDisplayContext context, PoseStack pStack, boolean leftFlip) { - PerspectiveModelState modelState = getModelState(); - if (modelState != null) { - Transformation transform = getModelState().getTransform(context); - - Vector3f trans = transform.getTranslation(); - pStack.translate(trans.x(), trans.y(), trans.z()); - - pStack.mulPose(transform.getLeftRotation()); - - Vector3f scale = transform.getScale(); - pStack.scale(scale.x(), scale.y(), scale.z()); - - pStack.mulPose(transform.getRightRotation()); - return this; - } - return BakedModel.super.applyTransform(context, pStack, leftFlip); - } -} diff --git a/src/main/java/codechicken/lib/model/PerspectiveModelState.java b/src/main/java/codechicken/lib/model/PerspectiveModelState.java deleted file mode 100644 index 22f584cf..00000000 --- a/src/main/java/codechicken/lib/model/PerspectiveModelState.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.model; - -import codechicken.lib.util.TransformUtils; -import com.google.common.collect.ImmutableMap; -import com.mojang.math.Transformation; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.world.item.ItemDisplayContext; - -import java.util.Map; - -/** - * A simple {@link ModelState} implementation which - * is composed of multiple {@link Transformation}s. - *

    - * Created by covers1624 on 9/7/22. - * @see TransformUtils - */ -public class PerspectiveModelState implements ModelState { - - public static final PerspectiveModelState IDENTITY = new PerspectiveModelState(ImmutableMap.of()); - - private final Map transforms; - private final boolean isUvLocked; - - public PerspectiveModelState(Map transforms) { - this(transforms, false); - } - - public PerspectiveModelState(Map transforms, boolean isUvLocked) { - this.transforms = ImmutableMap.copyOf(transforms); - this.isUvLocked = isUvLocked; - } - - public Transformation getTransform(ItemDisplayContext context) { - return transforms.getOrDefault(context, Transformation.identity()); - } - - @Override - public boolean isUvLocked() { - return isUvLocked; - } -} diff --git a/src/main/java/codechicken/lib/model/Quad.java b/src/main/java/codechicken/lib/model/Quad.java index 8dbee83e..0ddd8ad6 100644 --- a/src/main/java/codechicken/lib/model/Quad.java +++ b/src/main/java/codechicken/lib/model/Quad.java @@ -20,38 +20,41 @@ import codechicken.lib.math.InterpHelper; import codechicken.lib.math.MathHelper; -import codechicken.lib.util.VertexUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; +import codechicken.lib.vec.uv.UV; +import net.minecraft.client.model.geom.builders.UVPair; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import net.minecraft.util.ARGB; import net.minecraft.world.phys.AABB; +import net.neoforged.neoforge.client.model.quad.BakedColors; +import net.neoforged.neoforge.client.model.quad.BakedNormals; import org.jetbrains.annotations.Nullable; +import org.joml.Vector3fc; import static java.util.Objects.requireNonNull; /** - * A simple easy to manipulate quad format. Can be reset and then used on a different format. + * A mutable {@link BakedQuad}. * * @author covers1624 */ -public class Quad implements IVertexProducer, IVertexConsumer { - - private @Nullable CachedFormat format; - +public class Quad { + + public Vertex[] vertices = { + new Vertex(), + new Vertex(), + new Vertex(), + new Vertex() + }; public int tintIndex = -1; - public @Nullable Direction orientation; - public boolean diffuseLighting = true; + public @Nullable Direction direction; public @Nullable TextureAtlasSprite sprite; - - public Vertex[] vertices = new Vertex[4]; - public boolean full; - - // Not copied. - private int vertexIndex = 0; + public boolean shade = false; + public int lightEmission = 0; + public boolean ambientOcclusion = true; // Cache for normal computation. private final Vector3 v1 = new Vector3(); @@ -59,93 +62,15 @@ public class Quad implements IVertexProducer, IVertexConsumer { private final Vector3 t = new Vector3(); private final Cuboid6 c = new Cuboid6(); - /** - * Use this if you reset the quad each time you use it. - */ public Quad() { } - /** - * use this if you want to initialize the quad with a format. - * - * @param format The format. - */ - public Quad(CachedFormat format) { - this.format = format; - } - - public final CachedFormat format() { - return requireNonNull(format, "Quad does not have a format assigned yet."); - } - - @Override - public VertexFormat getVertexFormat() { - return format().format; - } - - @Override - public void setQuadTint(int tint) { - tintIndex = tint; - } - - @Override - public void setQuadOrientation(Direction orientation) { - this.orientation = orientation; - } - - @Override - public void setApplyDiffuseLighting(boolean diffuse) { - diffuseLighting = diffuse; - } - - @Override - public void setTexture(TextureAtlasSprite texture) { - sprite = texture; - } - - @Override - public void put(int element, float... data) { - if (full) { - throw new RuntimeException("Unable to add data when full."); - } - Vertex v = vertices[vertexIndex]; - if (v == null) { - v = new Vertex(format()); - vertices[vertexIndex] = v; - } - System.arraycopy(data, 0, v.raw[element], 0, data.length); - if (element == (format().elementCount - 1)) { - vertexIndex++; - if (vertexIndex == 4) { - vertexIndex = 0; - full = true; - if (orientation == null) { - calculateOrientation(false); - } - } - } - } - - @Override - public void put(Quad quad) { + public Quad(Quad quad) { copyFrom(quad); } - @Override - public void pipe(IVertexConsumer consumer) { - if (consumer instanceof IVertexConsumer) { - consumer.put(this); - } else { - consumer.setQuadTint(tintIndex); - consumer.setQuadOrientation(orientation); - consumer.setApplyDiffuseLighting(diffuseLighting); - consumer.setTexture(sprite); - for (Vertex v : vertices) { - for (int e = 0; e < format.elementCount; e++) { - consumer.put(e, v.raw[e]); - } - } - } + public Quad(BakedQuad quad) { + copyFrom(quad); } /** @@ -181,14 +106,92 @@ public void clamp(AABB bb) { */ public void clamp(Cuboid6 cuboid) { for (Vertex vertex : vertices) { - float[] vec = vertex.vec(); - vec[0] = (float) MathHelper.clip(vec[0], cuboid.min.x, cuboid.max.x); - vec[1] = (float) MathHelper.clip(vec[1], cuboid.min.y, cuboid.max.y); - vec[2] = (float) MathHelper.clip(vec[2], cuboid.min.z, cuboid.max.z); + vertex.vec.x = MathHelper.clip(vertex.vec.x, cuboid.min.x, cuboid.max.x); + vertex.vec.y = MathHelper.clip(vertex.vec.y, cuboid.min.y, cuboid.max.y); + vertex.vec.z = MathHelper.clip(vertex.vec.z, cuboid.min.z, cuboid.max.z); } calculateOrientation(true); } + /** + * Reinterpolate this quad's UV's and Colors after some transformation. + *

    + * You will have needed to use {@link #resetInterp(InterpHelper, int)} prior + * to your transformations in order for reinterpolation to not output garbage. + * + * @param interp Your interpolation helper. + */ + public void reinterpolate(InterpHelper interp) { + requireNonNull(direction, "Quad must have a direction, side needed to compute dx/dy"); + reinterpolate(interp, direction.ordinal() >> 1); + } + + private void reinterpolate(InterpHelper interp, int side) { + reinterpolateUV(interp, side); + reinterpolateColor(interp, side); + } + + private void reinterpolateUV(InterpHelper interp, int side) { + double u0 = vertices[0].uv.u; + double v0 = vertices[0].uv.v; + + double u1 = vertices[1].uv.u; + double v1 = vertices[1].uv.v; + + double u2 = vertices[2].uv.u; + double v2 = vertices[2].uv.v; + + double u3 = vertices[3].uv.u; + double v3 = vertices[3].uv.v; + + for (int v = 0; v < 4; v++) { + interp.locate(vertices[v].dx(side), vertices[v].dy(side)); + var uv = vertices[v].uv; + uv.set( + interpUV(interp, uv.u, u0, u1, u2, u3), + interpUV(interp, uv.v, v0, v1, v2, v3) + ); + } + } + + private void reinterpolateColor(InterpHelper interp, int side) { + int c0 = vertices[0].color; + int c1 = vertices[1].color; + int c2 = vertices[2].color; + int c3 = vertices[3].color; + + for (int v = 0; v < 4; v++) { + interp.locate(vertices[v].dx(side), vertices[v].dy(side)); + var c = vertices[v].color; + vertices[v].color = ARGB.colorFromFloat( + interpColor(interp, ARGB.alphaFloat(c), + ARGB.alphaFloat(c0), + ARGB.alphaFloat(c1), + ARGB.alphaFloat(c2), + ARGB.alphaFloat(c3) + ), + interpColor(interp, ARGB.redFloat(c), + ARGB.redFloat(c0), + ARGB.redFloat(c1), + ARGB.redFloat(c2), + ARGB.redFloat(c3) + ), + interpColor(interp, ARGB.greenFloat(c), + ARGB.greenFloat(c0), + ARGB.greenFloat(c1), + ARGB.greenFloat(c2), + ARGB.greenFloat(c3) + ), + interpColor(interp, ARGB.blueFloat(c), + ARGB.blueFloat(c0), + ARGB.blueFloat(c1), + ARGB.blueFloat(c2), + ARGB.blueFloat(c3) + ) + ); + } + } + /** * Re-calculates the Orientation of this quad, * optionally the normal vector. @@ -196,150 +199,127 @@ public void clamp(Cuboid6 cuboid) { * @param setNormal If the normal vector should be updated. */ public void calculateOrientation(boolean setNormal) { - v1.set(vertices[3].vec()).subtract(t.set(vertices[1].vec())); - v2.set(vertices[2].vec()).subtract(t.set(vertices[0].vec())); + v1.set(vertices[3].vec).subtract(t.set(vertices[1].vec)); + v2.set(vertices[2].vec).subtract(t.set(vertices[0].vec)); Vector3 normal = v2.crossProduct(v1).normalize(); - if (format().hasNormal && setNormal) { + if (setNormal) { for (Vertex vertex : vertices) { - vertex.normal()[0] = (float) normal.x; - vertex.normal()[1] = (float) normal.y; - vertex.normal()[2] = (float) normal.z; - vertex.normal()[3] = 0; + vertex.normal.set(normal); } } - orientation = Direction.getNearest(normal.x, normal.y, normal.z); + direction = Direction.getApproximateNearest(normal.x, normal.y, normal.z); } /** - * Used to create a new quad complete copy of this one. - * - * @return The new quad. + * @return A complete copy of this quad. */ public Quad copy() { - if (!full) { - throw new RuntimeException("Only copying full quads is supported."); - } - Quad quad = new Quad(format()); - quad.tintIndex = tintIndex; - quad.orientation = orientation; - quad.diffuseLighting = diffuseLighting; - quad.sprite = sprite; - quad.full = true; - for (int i = 0; i < 4; i++) { - quad.vertices[i] = vertices[i].copy(); - } - return quad; + return new Quad(this); } /** - * Copies the data inside the given quad to this one. This ignores VertexFormat, please make sure your quads are in - * the same format. + * Copy the data from the given {@link BakedQuad} into this quad. * - * @param quad The Quad to copy from. + * @param quad The {@link BakedQuad} to copy from. * @return This quad. */ - public Quad copyFrom(Quad quad) { - tintIndex = quad.tintIndex; - orientation = quad.orientation; - diffuseLighting = quad.diffuseLighting; - sprite = quad.sprite; - full = quad.full; - for (int v = 0; v < 4; v++) { - for (int e = 0; e < format().elementCount; e++) { - System.arraycopy(quad.vertices[v].raw[e], 0, vertices[v].raw[e], 0, 4); - } + public Quad copyFrom(BakedQuad quad) { + var normals = quad.bakedNormals(); + var colors = quad.bakedColors(); + for (int i = 0; i < 4; i++) { + vertices[i].set( + quad.position(i), + quad.packedUV(i), + normals.normal(i), + colors.color(i) + ); } + tintIndex = quad.tintIndex(); + direction = quad.direction(); + sprite = quad.sprite(); + shade = quad.shade(); + lightEmission = quad.lightEmission(); + ambientOcclusion = quad.hasAmbientOcclusion(); return this; } /** - * Reset the quad to the new format. + * Copies the data from the given {@link Quad} into this quad. * - * @param format The new format. + * @param quad The {@link Quad} to copy from. + * @return This quad. */ - public void reset(CachedFormat format) { - this.format = format; - tintIndex = -1; - orientation = null; - diffuseLighting = true; - sprite = null; + public Quad copyFrom(Quad quad) { for (int i = 0; i < vertices.length; i++) { - Vertex v = vertices[i]; - if (v == null) { - vertices[i] = v = new Vertex(format); - } - v.reset(format); + vertices[i].copyFrom(quad.vertices[i]); } - vertexIndex = 0; - full = false; - } - - /** - * Rewind this Quad without completely resetting it. - */ - public void rewind() { - vertexIndex = 0; - full = false; + tintIndex = quad.tintIndex; + direction = quad.direction; + sprite = quad.sprite; + shade = quad.shade; + lightEmission = quad.lightEmission; + ambientOcclusion = quad.ambientOcclusion; + return this; } /** - * Bakes this Quad to a BakedQuad. + * Bakes this {@link Quad} to a {@link BakedQuad}. * - * @return The BakedQuad. + * @return The {@link BakedQuad}. */ public BakedQuad bake() { - int[] packedData = new int[format().format.getVertexSize()]; - for (int v = 0; v < 4; v++) { - for (int e = 0; e < format().elementCount; e++) { - VertexUtils.pack(vertices[v].raw[e], packedData, format().format, v, e); - } - } + return new BakedQuad( + vertices[0].vec.vector3f(), + vertices[1].vec.vector3f(), + vertices[2].vec.vector3f(), + vertices[3].vec.vector3f(), + vertices[0].packUV(), + vertices[1].packUV(), + vertices[2].packUV(), + vertices[3].packUV(), + tintIndex, + requireNonNull(direction, "Direction not computed."), + requireNonNull(sprite, "Quad requires a sprite."), + shade, + lightEmission, + BakedNormals.of( + vertices[0].packNormal(), + vertices[1].packNormal(), + vertices[2].packNormal(), + vertices[3].packNormal() + ), + BakedColors.of( + vertices[0].color, + vertices[1].color, + vertices[2].color, + vertices[3].color + ), + ambientOcclusion + ); + } + + private static float interpColor(InterpHelper interp, float orig, float a, float b, float c, float d) { + if (a == b && b == c && c == d) return orig; - return makeQuad(packedData); + return interp.interpolate(a, b, c, d); } - // Broken out as a stub for mixins to target easier. - private BakedQuad makeQuad(int[] packedData) { - if (format().format != DefaultVertexFormat.BLOCK) { - throw new IllegalStateException("Unable to bake this quad to the specified format. " + format().format); - } - requireNonNull(orientation, "Quad requires an orientation."); - requireNonNull(sprite, "Quad requires a sprite."); - return new BakedQuad(packedData, tintIndex, orientation, sprite, diffuseLighting); + private static double interpUV(InterpHelper interp, double orig, double a, double b, double c, double d) { + if (a == b && b == c && c == d) return orig; + + return interp.interpolate(a, b, c, d); } - /** - * A simple vertex format. - */ public static class Vertex { - public CachedFormat format; + public Vector3 vec = new Vector3(); + public UV uv = new UV(); + public Vector3 normal = new Vector3(); + public int color = 0xFFFFFFFF; - /** - * The raw data. - */ - public float[][] raw; - - // References to the arrays inside raw. - private float @Nullable [] vec; - private float @Nullable [] normal; - private float @Nullable [] color; - private float @Nullable [] uv; - private float @Nullable [] overlay; - private float @Nullable [] lightmap; - - /** - * Create a new Vertex. - * - * @param format The format for the vertex. - */ - public Vertex(CachedFormat format) { - this.format = format; - raw = new float[format.elementCount][4]; - preProcess(); - } + public Vertex() { } /** * Creates a new Vertex using the data inside the other. A copy! @@ -347,59 +327,20 @@ public Vertex(CachedFormat format) { * @param other The other. */ public Vertex(Vertex other) { - format = other.format; - raw = other.raw.clone(); - for (int v = 0; v < format.elementCount; v++) { - raw[v] = other.raw[v].clone(); - } - preProcess(); + copyFrom(other); } - /** - * Pulls references to the individual element's arrays inside raw. Modifying the individual element arrays will - * update raw. - */ - public void preProcess() { - if (format.hasPosition) { - vec = raw[format.positionIndex]; - } - if (format.hasNormal) { - normal = raw[format.normalIndex]; - } - if (format.hasColor) { - color = raw[format.colorIndex]; - } - if (format.hasUV) { - uv = raw[format.uvIndex]; - } - if (format.hasOverlay) { - overlay = raw[format.overlayIndex]; - } - if (format.hasLightMap) { - lightmap = raw[format.lightMapIndex]; - } - } - - // @formatter:off - public final float[] vec() { return requireNonNull(vec, "Vertex does not have the position element.");} - public final float[] normal() { return requireNonNull(normal, "Vertex does not have the normal element.");} - public final float[] color() { return requireNonNull(color, "Vertex does not have the colour element.");} - public final float[] uv() { return requireNonNull(uv, "Vertex does not have the uv element.");} - public final float[] overlay() { return requireNonNull(overlay, "Vertex does not have the overlay element.");} - public final float[] lightmap() { return requireNonNull(lightmap, "Vertex does not have the lightmap element.");} - // @formatter:on - /** * Gets the 2d X coord for the given axis. * * @param s The axis. side >> 1 * @return The x coord. */ - public float dx(int s) { + public double dx(int s) { if (s <= 1) { - return vec()[0]; + return vec.x; } else { - return vec()[2]; + return vec.z; } } @@ -409,103 +350,69 @@ public float dx(int s) { * @param s The axis. side >> 1 * @return The y coord. */ - public float dy(int s) { + public double dy(int s) { if (s > 0) { - return vec()[1]; + return vec.y; } else { - return vec()[2]; + return vec.z; } } /** - * Interpolates the new color values for this Vertex using the others as a reference. + * Copies this Vertex to a new one. * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * @return The same Vertex. + * @return The new Vertex. */ - public Vertex interpColorFrom(InterpHelper interpHelper, Vertex[] others) { - for (int e = 0; e < 4; e++) { - float p1 = others[0].color()[e]; - float p2 = others[1].color()[e]; - float p3 = others[2].color()[e]; - float p4 = others[3].color()[e]; - // Only interpolate if colors are different. - if (p1 != p2 || p2 != p3 || p3 != p4) { - color()[e] = interpHelper.interpolate(p1, p2, p3, p4); - } - } - return this; + public Vertex copy() { + return new Vertex(this); } /** - * Interpolates the new UV values for this Vertex using the others as a reference. + * Copy the data in the given Vertex into this vertex. * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * @return The same Vertex. + * @param other The other vertex. */ - public Vertex interpUVFrom(InterpHelper interpHelper, Vertex[] others) { - for (int e = 0; e < 2; e++) { - float p1 = others[0].uv()[e]; - float p2 = others[1].uv()[e]; - float p3 = others[2].uv()[e]; - float p4 = others[3].uv()[e]; - if (p1 != p2 || p2 != p3 || p3 != p4) { - uv()[e] = interpHelper.interpolate(p1, p2, p3, p4); - } - } - return this; + public void copyFrom(Vertex other) { + vec.set(other.vec); + uv.set(other.uv); + normal.set(other.normal); + color = other.color; } /** - * Interpolates the new LightMap values for this Vertex using the others as a reference. + * Set the data in this Vertex from the provided packed data. * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * @return The same Vertex. + * @param vec The vector. + * @param packedUV The packed UV. + * @param packedNormal The packed normals. + * @param packedColor The packed color. */ - public Vertex interpLightMapFrom(InterpHelper interpHelper, Vertex[] others) { - for (int e = 0; e < 2; e++) { - float p1 = others[0].lightmap()[e]; - float p2 = others[1].lightmap()[e]; - float p3 = others[2].lightmap()[e]; - float p4 = others[3].lightmap()[e]; - if (p1 != p2 || p2 != p3 || p3 != p4) { - lightmap()[e] = interpHelper.interpolate(p1, p2, p3, p4); - } - } - return this; + public void set(Vector3fc vec, long packedUV, int packedNormal, int packedColor) { + this.vec.set(vec); + uv.set( + UVPair.unpackU(packedUV), + UVPair.unpackV(packedUV) + ); + normal.set( + BakedNormals.unpackX(packedNormal), + BakedNormals.unpackY(packedNormal), + BakedNormals.unpackZ(packedNormal) + ); + color = packedColor; } /** - * Copies this Vertex to a new one. - * - * @return The new Vertex. + * @return The UV repacked into a long. */ - public Vertex copy() { - return new Vertex(this); + public long packUV() { + return UVPair.pack((float) uv.u, (float) uv.v); } /** - * Resets the Vertex to a new format. Expands the raw array if needed. - * - * @param format The format to reset to. + * @return The Normals repacked into an int. */ - public void reset(CachedFormat format) { - // If the format is different and our raw array is smaller, then expand it. - if (!this.format.equals(format) && format.elementCount > raw.length) { - raw = new float[format.elementCount][4]; - } - this.format = format; - - vec = null; - normal = null; - color = null; - uv = null; - lightmap = null; - - preProcess(); + public int packNormal() { + return BakedNormals.pack((float) normal.x, (float) normal.y, (float) normal.z); } } } diff --git a/src/main/java/codechicken/lib/model/pipeline/IPipelineElementFactory.java b/src/main/java/codechicken/lib/model/QuadAlphaOverride.java similarity index 61% rename from src/main/java/codechicken/lib/model/pipeline/IPipelineElementFactory.java rename to src/main/java/codechicken/lib/model/QuadAlphaOverride.java index b1ebb01f..58f95981 100644 --- a/src/main/java/codechicken/lib/model/pipeline/IPipelineElementFactory.java +++ b/src/main/java/codechicken/lib/model/QuadAlphaOverride.java @@ -16,13 +16,26 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline; +package codechicken.lib.model; + +import codechicken.lib.colour.Colour; +import codechicken.lib.model.Quad.Vertex; /** + * This transformer simply overrides the alpha of the quad. + * Only operates if the format has color. + * * @author covers1624 */ -@FunctionalInterface -public interface IPipelineElementFactory { +public class QuadAlphaOverride extends QuadTransformer { + + public float alphaOverride; - T create(); + @Override + public boolean transform(Quad quad) { + for (Vertex v : quad.vertices) { + v.color = Colour.replace(v.color, 3, alphaOverride); + } + return true; + } } diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java b/src/main/java/codechicken/lib/model/QuadClamper.java similarity index 59% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java rename to src/main/java/codechicken/lib/model/QuadClamper.java index 3bf0e5a2..2aea9c5f 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java +++ b/src/main/java/codechicken/lib/model/QuadClamper.java @@ -16,41 +16,22 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; -import codechicken.lib.model.IVertexConsumer; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; import codechicken.lib.vec.Cuboid6; import net.minecraft.world.phys.AABB; /** * This transformer simply clamps the vertices inside the provided box. - * You probably want to Re-Interpolate the UV's, Color, and Lmap, see {@link QuadReInterpolator} + * You probably want to Re-Interpolate the UV's, Color, etc, see {@link QuadReInterpolator} * * @author covers1624 */ public class QuadClamper extends QuadTransformer { - public static IPipelineElementFactory FACTORY = QuadClamper::new; - private final Cuboid6 clampBounds = new Cuboid6(); - QuadClamper() { - super(); - } - - public QuadClamper(IVertexConsumer parent, AABB bounds) { - super(parent); - clampBounds.set(bounds); - } - - public QuadClamper(IVertexConsumer parent, Cuboid6 bounds) { - super(parent); - clampBounds.set(bounds); - } - public void setClampBounds(AABB bounds) { clampBounds.set(bounds); } @@ -60,23 +41,23 @@ public void setClampBounds(Cuboid6 bounds) { } @Override - public boolean transform() { - assert quad.orientation != null; - int s = quad.orientation.ordinal() >> 1; + public boolean transform(Quad quad) { + assert quad.direction != null; + int s = quad.direction.ordinal() >> 1; quad.clamp(clampBounds); // Check if the quad would be invisible and cull it. Vertex[] vertices = quad.vertices; - float x1 = vertices[0].dx(s); - float x2 = vertices[1].dx(s); - float x3 = vertices[2].dx(s); - float x4 = vertices[3].dx(s); + double x1 = vertices[0].dx(s); + double x2 = vertices[1].dx(s); + double x3 = vertices[2].dx(s); + double x4 = vertices[3].dx(s); - float y1 = vertices[0].dy(s); - float y2 = vertices[1].dy(s); - float y3 = vertices[2].dy(s); - float y4 = vertices[3].dy(s); + double y1 = vertices[0].dy(s); + double y2 = vertices[1].dy(s); + double y3 = vertices[2].dy(s); + double y4 = vertices[3].dy(s); // These comparisons are safe as we are comparing clamped values. boolean flag1 = x1 == x2 && x2 == x3 && x3 == x4; diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java b/src/main/java/codechicken/lib/model/QuadCornerKicker.java similarity index 75% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java rename to src/main/java/codechicken/lib/model/QuadCornerKicker.java index 33b06429..879a9b3e 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java +++ b/src/main/java/codechicken/lib/model/QuadCornerKicker.java @@ -16,11 +16,9 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; import net.minecraft.core.Direction; import net.minecraft.core.Direction.AxisDirection; import net.minecraft.core.Vec3i; @@ -43,9 +41,6 @@ */ public class QuadCornerKicker extends QuadTransformer { - // The factory for pipeline creation. - public static final IPipelineElementFactory FACTORY = QuadCornerKicker::new; - // Simple horizonal lookups. public static int[][] horizonals = new int[][] { // Around Y axis, NSWE. @@ -66,10 +61,6 @@ public class QuadCornerKicker extends QuadTransformer { private AABB box; private double thickness; - QuadCornerKicker() { - super(); - } - /** * Set's the side this Facade / Cover is attached to. * @@ -111,30 +102,27 @@ public void setThickness(double thickness) { } @Override - public boolean transform() { - assert quad.orientation != null; - int side = quad.orientation.ordinal(); - if (side != mySide && side != (mySide ^ 1)) { - for (int hoz : horizonals[mySide]) { - if (side != hoz && side != (hoz ^ 1)) { - if ((facadeMask & (1 << hoz)) != 0) { - Corner corner = Corner.fromSides(mySide ^ 1, side, hoz); - for (Vertex vertex : quad.vertices) { - float x = vertex.vec()[0]; - float y = vertex.vec()[1]; - float z = vertex.vec()[2]; - if (epsComp(x, corner.pX(box)) && epsComp(y, corner.pY(box)) && epsComp(z, corner.pZ(box))) { - Vec3i vec = Direction.BY_3D_DATA[hoz].getNormal(); - x -= vec.getX() * thickness; - y -= vec.getY() * thickness; - z -= vec.getZ() * thickness; - vertex.vec()[0] = x; - vertex.vec()[1] = y; - vertex.vec()[2] = z; - } - } - } - } + public boolean transform(Quad quad) { + assert quad.direction != null; + int side = quad.direction.ordinal(); + if (side == mySide || side == (mySide ^ 1)) return true; + + for (int hoz : horizonals[mySide]) { + if (side == hoz || side == (hoz ^ 1)) continue; + if ((facadeMask & (1 << hoz)) == 0) continue; + + Corner corner = Corner.fromSides(mySide ^ 1, side, hoz); + for (Vertex vertex : quad.vertices) { + double x = vertex.vec.x; + double y = vertex.vec.y; + double z = vertex.vec.z; + if (!epsComp(x, corner.pX(box)) || !epsComp(y, corner.pY(box)) || !epsComp(z, corner.pZ(box))) continue; + + Vec3i vec = Direction.BY_3D_DATA[hoz].getUnitVec3i(); + x -= vec.getX() * thickness; + y -= vec.getY() * thickness; + z -= vec.getZ() * thickness; + vertex.vec.set(x, y, z); } } diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java b/src/main/java/codechicken/lib/model/QuadFaceStripper.java similarity index 63% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java rename to src/main/java/codechicken/lib/model/QuadFaceStripper.java index a4827488..dba208f7 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java +++ b/src/main/java/codechicken/lib/model/QuadFaceStripper.java @@ -16,12 +16,9 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; -import codechicken.lib.model.IVertexConsumer; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; import codechicken.lib.vec.Cuboid6; import net.minecraft.core.Direction; import net.minecraft.world.phys.AABB; @@ -29,28 +26,16 @@ import static net.minecraft.core.Direction.AxisDirection.POSITIVE; /** - * This transformer strips quads that are on faces. + * This transformer strips quads that lie exactly on the faces of the provided bounds. * Simply set the bounds for the faces, and the strip mask. * * @author covers1624 */ public class QuadFaceStripper extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadFaceStripper::new; - private final Cuboid6 bounds = new Cuboid6(); private int mask; - QuadFaceStripper() { - super(); - } - - public QuadFaceStripper(IVertexConsumer parent, AABB bounds, int mask) { - super(parent); - this.bounds.set(bounds); - this.mask = mask; - } - /** * The bounds of the faces, * used as the .. bounds, if all vertices of a quad @@ -81,38 +66,38 @@ public void setMask(int mask) { } @Override - public boolean transform() { - assert quad.orientation != null; - if (mask == 0) { - return true;// No mask, nothing changes. - } + public boolean transform(Quad quad) { + assert quad.direction != null; + // No mask, nothing changes. + if (mask == 0) return true; + // If the bit for this quad is set, then check if we should strip. - if ((mask & (1 << quad.orientation.ordinal())) != 0) { - Direction.AxisDirection dir = quad.orientation.getAxisDirection(); + if ((mask & (1 << quad.direction.ordinal())) != 0) { + Direction.AxisDirection dir = quad.direction.getAxisDirection(); Vertex[] vertices = quad.vertices; - switch (quad.orientation.getAxis()) { + switch (quad.direction.getAxis()) { case X -> { float bound = (float) (dir == POSITIVE ? bounds.max.x : bounds.min.x); - float x1 = vertices[0].vec()[0]; - float x2 = vertices[1].vec()[0]; - float x3 = vertices[2].vec()[0]; - float x4 = vertices[3].vec()[0]; + double x1 = vertices[0].vec.x; + double x2 = vertices[1].vec.x; + double x3 = vertices[2].vec.x; + double x4 = vertices[3].vec.x; return x1 != x2 || x2 != x3 || x3 != x4 || x4 != bound; } case Y -> { float bound = (float) (dir == POSITIVE ? bounds.max.y : bounds.min.y); - float y1 = vertices[0].vec()[1]; - float y2 = vertices[1].vec()[1]; - float y3 = vertices[2].vec()[1]; - float y4 = vertices[3].vec()[1]; + double y1 = vertices[0].vec.y; + double y2 = vertices[1].vec.y; + double y3 = vertices[2].vec.y; + double y4 = vertices[3].vec.y; return y1 != y2 || y2 != y3 || y3 != y4 || y4 != bound; } case Z -> { float bound = (float) (dir == POSITIVE ? bounds.max.z : bounds.min.z); - float z1 = vertices[0].vec()[2]; - float z2 = vertices[1].vec()[2]; - float z3 = vertices[2].vec()[2]; - float z4 = vertices[3].vec()[2]; + double z1 = vertices[0].vec.z; + double z2 = vertices[1].vec.z; + double z3 = vertices[2].vec.z; + double z4 = vertices[3].vec.z; return z1 != z2 || z2 != z3 || z3 != z4 || z4 != bound; } } diff --git a/src/main/java/codechicken/lib/model/QuadReInterpolator.java b/src/main/java/codechicken/lib/model/QuadReInterpolator.java new file mode 100644 index 00000000..67763216 --- /dev/null +++ b/src/main/java/codechicken/lib/model/QuadReInterpolator.java @@ -0,0 +1,43 @@ +/* + * This file is part of CodeChickenLib. + * Copyright (c) 2018, covers1624, All rights reserved. + * + * CodeChickenLib is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 2.1 of the License, or + * (at your option) any later version. + * + * CodeChickenLib 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with CodeChickenLib. If not, see . + */ + +package codechicken.lib.model; + +import codechicken.lib.math.InterpHelper; + +/** + * Reinterpolates quad properties after vertices have been transformed. + * + * @author covers1624 + */ +public class QuadReInterpolator extends QuadTransformer { + + private final InterpHelper interpHelper = new InterpHelper(); + + @Override + public void beforeTransform(Quad quad) { + assert quad.direction != null; + quad.resetInterp(interpHelper, quad.direction.ordinal() >> 1); + } + + @Override + public boolean transform(Quad quad) { + quad.reinterpolate(interpHelper); + return true; + } +} diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java b/src/main/java/codechicken/lib/model/QuadTinter.java similarity index 58% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java rename to src/main/java/codechicken/lib/model/QuadTinter.java index 326b5442..4cea728a 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java +++ b/src/main/java/codechicken/lib/model/QuadTinter.java @@ -16,53 +16,35 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; -import codechicken.lib.model.IVertexConsumer; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; +import net.minecraft.util.ARGB; /** * This transformer tints quads.. * Feed it the output of BlockColors.colorMultiplier. + * Colors are in ARGB, Alpha is completely ignored. * Color format: 0000 RRRR GGGG BBBB * * @author covers1624 */ public class QuadTinter extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadTinter::new; - private int tint; - QuadTinter() { - super(); - } - - public QuadTinter(IVertexConsumer consumer, int tint) { - super(consumer); - this.tint = tint; - } - public QuadTinter setTint(int tint) { this.tint = tint; return this; } @Override - public boolean transform() { - // Nuke tintIndex. + public boolean transform(Quad quad) { + if (tint == -1) return true; + quad.tintIndex = -1; - if (format.hasColor) { - float r = (tint >> 0x10 & 0xFF) / 255F; - float g = (tint >> 0x08 & 0xFF) / 255F; - float b = (tint & 0xFF) / 255F; - for (Vertex v : quad.vertices) { - v.color()[0] *= r; - v.color()[1] *= g; - v.color()[2] *= b; - } + for (Vertex v : quad.vertices) { + v.color = ARGB.multiply(v.color, tint | 0xFF000000); } return true; } diff --git a/src/main/java/codechicken/lib/model/QuadTransformer.java b/src/main/java/codechicken/lib/model/QuadTransformer.java new file mode 100644 index 00000000..225223e1 --- /dev/null +++ b/src/main/java/codechicken/lib/model/QuadTransformer.java @@ -0,0 +1,82 @@ +/* + * This file is part of CodeChickenLib. + * Copyright (c) 2018, covers1624, All rights reserved. + * + * CodeChickenLib is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 2.1 of the License, or + * (at your option) any later version. + * + * CodeChickenLib 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with CodeChickenLib. If not, see . + */ + +package codechicken.lib.model; + +import java.util.Arrays; + +/** + * A {@link Quad} transformer. + * + * @author covers1624 + */ +public abstract class QuadTransformer { + + /** + * Transform the given quad. + * + * @param quad The quad to transform. + * @param transformers The transformers to apply. + * @return If the transforms completed. + * {@code false} if the quad should be discarded. + */ + public static boolean transform(Quad quad, QuadTransformer... transformers) { + return transform(quad, Arrays.asList(transformers)); + } + + /** + * Transform the given quad. + * + * @param quad The quad to transform. + * @param transformers The transformers to apply. + * @return If the transforms completed. + * {@code false} if the quad should be discarded. + */ + public static boolean transform(Quad quad, Iterable transformers) { + transformers.forEach(e -> e.beforeTransform(quad)); + + for (QuadTransformer transformer : transformers) { + if (!transformer.transform(quad)) { + return false; // Discarded + } + } + return true; + } + + /** + * Called before any transformation is performed on the quad. + * + * @param quad The quad. + */ + public void beforeTransform(Quad quad) { } + + /** + * Transform the quad. + * + * @return If transformation should continue. + * If {@code false}, the quad will be discarded. + */ + public abstract boolean transform(Quad quad); + + // Should be small enough. + private final static double EPSILON = 0.00001; + + public static boolean epsComp(double a, double b) { + return a == b || Math.abs(a - b) < EPSILON; + } +} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java b/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java deleted file mode 100644 index 5865a9a7..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java +++ /dev/null @@ -1,124 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.PerspectiveModel; -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.render.particle.IModelParticleProvider; -import codechicken.lib.util.VertexUtils; -import codechicken.lib.vec.Vector3; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.neoforged.neoforge.client.model.data.ModelData; -import net.neoforged.neoforge.common.util.ConcatenatedListView; -import org.jetbrains.annotations.Nullable; - -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Created by covers1624 on 1/02/2017. - */ -@Deprecated // These may go away unless there is sufficient need for generic implementations like these. -public abstract class AbstractBakedPropertiesModel implements PerspectiveModel, IModelParticleProvider, BakedModel { - - protected final ModelProperties properties; - - public AbstractBakedPropertiesModel(ModelProperties properties) { - this.properties = properties; - } - - @Override - public boolean useAmbientOcclusion() { - return properties.isAmbientOcclusion(); - } - - @Override - public boolean isGui3d() { - return properties.isGui3d(); - } - - @Override - public boolean isCustomRenderer() { - return properties.isBuiltInRenderer(); - } - - @Override - public boolean usesBlockLight() { - return properties.usesBlockLight(); - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return properties.getParticleTexture(); - } - - protected List getAllQuads(BlockState state, ModelData modelData) { - List> quadsList = new LinkedList<>(); - for (RenderType layer : getRenderTypes(state, RandomSource.create(42), modelData)) { - quadsList.add(getQuads(state, null, RandomSource.create(0), modelData, layer)); - for (Direction face : Direction.BY_3D_DATA) { - quadsList.add(getQuads(state, face, RandomSource.create(0), modelData, layer)); - } - } - return ConcatenatedListView.of(quadsList); - } - - @Override - public Set getHitEffects(BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData) { - Vector3 vec = new Vector3(traceResult.getLocation()).subtract(traceResult.getBlockPos()); - return getAllQuads(state, modelData).stream() - .filter(quad -> quad.getDirection() == traceResult.getDirection()) - .filter(quad -> checkDepth(quad, vec, traceResult.getDirection())) - .map(BakedQuad::getSprite) - .collect(Collectors.toSet()); - } - - protected boolean checkDepth(BakedQuad quad, Vector3 hit, Direction hitFace) { - int[] quadData = quad.getVertices(); - CachedFormat format = CachedFormat.lookup(DefaultVertexFormat.BLOCK); - - Vector3 posVec = new Vector3(); - float[] pos = new float[4]; - for (int v = 0; v < 4; v++) { - VertexUtils.unpack(quadData, pos, format.format, v, format.positionIndex); - posVec.add(pos[0], pos[1], pos[2]); - } - posVec.divide(4); - - double diff = switch (hitFace.getAxis()) { - case X -> Math.abs(hit.x - posVec.x); - case Y -> Math.abs(hit.y - posVec.y); - case Z -> Math.abs(hit.z - posVec.z); - }; - return !(diff > 0.01); - } - - @Override - public Set getDestroyEffects(BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data) { - return getAllQuads(state, data).stream().map(BakedQuad::getSprite).collect(Collectors.toSet()); - } - - @Nullable - @Override - public PerspectiveModelState getModelState() { - return properties instanceof ModelProperties.PerspectiveProperties props ? props.getTransforms() : null; - } - - @Override - public BakedModel applyTransform(ItemDisplayContext context, PoseStack pStack, boolean leftFlip) { - return PerspectiveModel.super.applyTransform(context, pStack, leftFlip); - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java b/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java deleted file mode 100644 index 258bf2f3..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java +++ /dev/null @@ -1,242 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties.PerspectiveBuilder; -import codechicken.lib.texture.TextureUtils; -import codechicken.lib.util.Copyable; -import codechicken.lib.util.TransformUtils; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import org.jetbrains.annotations.Nullable; - -import static java.util.Objects.requireNonNull; - -/** - * Created by covers1624 on 19/11/2016. - */ -@Deprecated // These may go away unless there is sufficient need for generic implementations like these. -public class ModelProperties implements Copyable { - - public static final ModelProperties DEFAULT_ITEM = ModelProperties.builder() - .withAO(true) - .build(); - public static final ModelProperties DEFAULT_BLOCK = ModelProperties.builder() - .withAO(true) - .withGui3D(true) - .withUsesBlockLight(true) - .build(); - - private final boolean isAO; - private final boolean isGui3D; - private final boolean isBuiltInRenderer; - private final boolean usesBlockLight; - - @Nullable - private TextureAtlasSprite particle; - - private ModelProperties(boolean isAO, boolean isGui3D, boolean usesBlockLight, boolean isBuiltInRenderer, TextureAtlasSprite particle) { - this.isAO = isAO; - this.isGui3D = isGui3D; - this.isBuiltInRenderer = isBuiltInRenderer; - this.usesBlockLight = usesBlockLight; - this.particle = particle; - } - - private ModelProperties(ModelProperties other) { - this.isAO = other.isAO; - this.isGui3D = other.isGui3D; - this.isBuiltInRenderer = other.isBuiltInRenderer; - this.usesBlockLight = other.usesBlockLight; - this.particle = other.particle; - } - - public static ModelProperties fromModel(BakedModel model) { - return new ModelProperties(model.useAmbientOcclusion(), model.isGui3d(), model.usesBlockLight(), model.isCustomRenderer(), model.getParticleIcon()); - } - - public boolean isAmbientOcclusion() { - return isAO; - } - - public boolean isGui3d() { - return isGui3D; - } - - public boolean isBuiltInRenderer() { - return isBuiltInRenderer; - } - - public boolean usesBlockLight() { - return usesBlockLight; - } - - public TextureAtlasSprite getParticleTexture() { - return maybeMissingTexture(particle); - } - - @Override - public ModelProperties copy() { - return new ModelProperties(this); - } - - public static Builder builder() { - return new Builder(); - } - - public Builder toBuilder() { - return new Builder(this); - } - - private static TextureAtlasSprite maybeMissingTexture(@Nullable TextureAtlasSprite sprite) { - if (sprite == null) { - sprite = TextureUtils.getMissingSprite(); - } - return sprite; - } - - /** - * Created by covers1624 on 21/02/2017. - */ - public static class PerspectiveProperties extends ModelProperties { - - public static final PerspectiveProperties DEFAULT_ITEM = ModelProperties.builder() - .copyFrom(ModelProperties.DEFAULT_ITEM) - .withTransforms(TransformUtils.DEFAULT_ITEM) - .build(); - public static final PerspectiveProperties DEFAULT_BLOCK = ModelProperties.builder() - .copyFrom(ModelProperties.DEFAULT_BLOCK) - .withTransforms(TransformUtils.DEFAULT_BLOCK) - .build(); - - private final PerspectiveModelState transforms; - - private PerspectiveProperties(PerspectiveProperties properties) { - this(properties.getTransforms(), properties); - } - - private PerspectiveProperties(PerspectiveModelState transforms, ModelProperties properties) { - super(properties); - this.transforms = transforms; - } - - public PerspectiveModelState getTransforms() { - return transforms; - } - - @Override - public PerspectiveProperties copy() { - return new PerspectiveProperties(this); - } - - @Override - public PerspectiveBuilder toBuilder() { - return new PerspectiveBuilder(this); - } - - public static class PerspectiveBuilder extends Builder { - - private @Nullable PerspectiveModelState transforms; - - protected PerspectiveBuilder(PerspectiveProperties properties) { - super(properties); - transforms = properties.transforms; - } - - protected PerspectiveBuilder(Builder builder) { - super(builder.isAO, builder.isAO, builder.usesBlockLight, builder.isBuiltInRenderer, builder.particle); - } - - @Override - public PerspectiveBuilder withTransforms(PerspectiveModelState transforms) { - this.transforms = transforms; - return this; - } - - @Override - public PerspectiveProperties build() { - return new PerspectiveProperties(requireNonNull(transforms), super.build()); - } - } - } - - public static class Builder { - - private boolean isAO; - private boolean isGui3D; - private boolean isBuiltInRenderer; - private boolean usesBlockLight; - private @Nullable TextureAtlasSprite particle; - - protected Builder() { - } - - protected Builder(ModelProperties properties) { - isAO = properties.isAO; - isGui3D = properties.isGui3D; - usesBlockLight = properties.usesBlockLight; - isBuiltInRenderer = properties.isBuiltInRenderer; - particle = properties.particle; - } - - protected Builder(boolean isAO, boolean isGui3D, boolean usesBlockLight, boolean isBuiltInRenderer, @Nullable TextureAtlasSprite particle) { - this.isAO = isAO; - this.isGui3D = isGui3D; - this.usesBlockLight = usesBlockLight; - this.isBuiltInRenderer = isBuiltInRenderer; - this.particle = particle; - } - - public Builder copyFrom(BakedModel model) { - isAO = model.useAmbientOcclusion(); - isGui3D = model.isGui3d(); - usesBlockLight = model.usesBlockLight(); - isBuiltInRenderer = model.isCustomRenderer(); - particle = model.getParticleIcon(); - return this; - } - - public Builder copyFrom(ModelProperties properties) { - isAO = properties.isAO; - isGui3D = properties.isGui3D; - isBuiltInRenderer = properties.isBuiltInRenderer; - particle = properties.particle; - return this; - } - - public Builder withAO(boolean isAO) { - this.isAO = isAO; - return this; - } - - public Builder withGui3D(boolean isGui3D) { - this.isGui3D = isGui3D; - return this; - } - - public Builder withUsesBlockLight(boolean usesBlockLight) { - this.usesBlockLight = usesBlockLight; - return this; - } - - public Builder withBuiltInRenderer(boolean builtInRenderer) { - isBuiltInRenderer = builtInRenderer; - return this; - } - - public Builder withParticle(TextureAtlasSprite sprite) { - particle = sprite; - return this; - } - - public PerspectiveBuilder withTransforms(PerspectiveModelState transforms) { - PerspectiveBuilder builder = new PerspectiveBuilder(this); - builder.withTransforms(transforms); - return builder; - } - - public ModelProperties build() { - return new ModelProperties(isAO, isGui3D, usesBlockLight, isBuiltInRenderer, maybeMissingTexture(particle)); - } - - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java b/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java deleted file mode 100644 index 94854b7d..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java +++ /dev/null @@ -1,61 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.texture.TextureUtils; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; - -import java.util.Collections; -import java.util.List; - -/** - * Created by covers1624 on 29/06/2017. - */ -public class OverrideListModel implements BakedModel { - - private final ItemOverrides overrides; - - public OverrideListModel(ItemOverrides overrides) { - this.overrides = overrides; - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - return Collections.emptyList(); - } - - @Override - public boolean useAmbientOcclusion() { - return false; - } - - @Override - public boolean isGui3d() { - return false; - } - - @Override - public boolean usesBlockLight() { - return false; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return TextureUtils.getMissingSprite(); - } - - @Override - public ItemOverrides getOverrides() { - return overrides; - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java deleted file mode 100644 index e06f7a78..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java +++ /dev/null @@ -1,63 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -/** - * Created by covers1624 on 25/11/2016. - */ -@Deprecated // These may go away unless there is sufficient need for generic implementations like these. -public class PerspectiveAwareBakedModel extends AbstractBakedPropertiesModel { - - private final Map> faceQuads; - private final List generalQuads; - - public PerspectiveAwareBakedModel(Map> faceQuads, PerspectiveModelState transforms, ModelProperties properties) { - this(faceQuads, ImmutableList.of(), transforms, properties); - } - - public PerspectiveAwareBakedModel(List generalQuads, PerspectiveModelState transforms, ModelProperties properties) { - this(ImmutableMap.of(), generalQuads, transforms, properties); - } - - public PerspectiveAwareBakedModel(Map> faceQuads, List generalQuads, PerspectiveModelState transforms, ModelProperties properties) { - this(faceQuads, generalQuads, properties.toBuilder().withTransforms(transforms).build()); - } - - public PerspectiveAwareBakedModel(Map> faceQuads, PerspectiveProperties properties) { - this(faceQuads, ImmutableList.of(), properties); - } - - public PerspectiveAwareBakedModel(List generalQuads, PerspectiveProperties properties) { - this(ImmutableMap.of(), generalQuads, properties); - } - - public PerspectiveAwareBakedModel(Map> faceQuads, List generalQuads, PerspectiveProperties properties) { - super(properties); - this.faceQuads = ImmutableMap.copyOf(faceQuads); - this.generalQuads = ImmutableList.copyOf(generalQuads); - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - if (side == null) return generalQuads; - - return faceQuads.getOrDefault(side, List.of()); - } - - @Override - public ItemOverrides getOverrides() { - return ItemOverrides.EMPTY; - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java deleted file mode 100644 index 610efe86..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java +++ /dev/null @@ -1,71 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import com.google.common.collect.ImmutableMap; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.neoforge.client.ChunkRenderTypeSet; -import net.neoforged.neoforge.client.model.data.ModelData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -/** - * Created by covers1624 on 19/11/2016. - */ -@Deprecated // These may go away unless there is sufficient need for generic implementations like these. -public class PerspectiveAwareLayeredModel extends AbstractBakedPropertiesModel { - - private final Map> unculledQuads; - private final Map>> faceQuads; - private final RenderType generallayer; - private final ChunkRenderTypeSet chunkLayers; - - public PerspectiveAwareLayeredModel(Map>> faceQuads, PerspectiveProperties properties) { - this(faceQuads, ImmutableMap.of(), properties, RenderType.solid()); - } - - public PerspectiveAwareLayeredModel(Map>> faceQuads, Map> unculledQuads, PerspectiveProperties properties, RenderType generallayer) { - super(properties); - this.faceQuads = ImmutableMap.copyOf(faceQuads); - this.unculledQuads = ImmutableMap.copyOf(unculledQuads); - this.generallayer = generallayer; - chunkLayers = ChunkRenderTypeSet.union(ChunkRenderTypeSet.of(faceQuads.keySet()), ChunkRenderTypeSet.of(unculledQuads.keySet())); - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - return getQuads(state, side, rand, ModelData.EMPTY, null); - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand, ModelData data, @Nullable RenderType layer) { - if (layer == null) { - layer = generallayer; - } - if (side == null) { - return unculledQuads.getOrDefault(layer, List.of()); - } - Map> faceQuadMap = faceQuads.get(layer); - if (faceQuadMap != null) { - return faceQuadMap.getOrDefault(side, List.of()); - } - return List.of(); - } - - @Override - public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) { - return chunkLayers; - } - - @Override - public ItemOverrides getOverrides() { - return ItemOverrides.EMPTY; - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java b/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java deleted file mode 100644 index 7c9fc03f..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java +++ /dev/null @@ -1,119 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.util.TransformUtils; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.ItemBlockRenderTypes; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.neoforge.client.model.data.ModelData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collections; -import java.util.List; -import java.util.function.Function; - -/** - * A simple wrapper item model. - * Created by covers1624 on 5/07/2017. - */ -public abstract class WrappedItemModel implements BakedModel { - - protected final BakedModel wrapped; - protected final ModelState parentState; - protected @Nullable LivingEntity entity; - protected @Nullable ClientLevel world; - - private final ItemOverrides overrideList = new ItemOverrides() { - @Override - public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel world, @Nullable LivingEntity entity, int seed) { - WrappedItemModel.this.entity = entity; - WrappedItemModel.this.world = world == null ? entity == null ? null : (ClientLevel) entity.level() : null; - return originalModel; - } - }; - - public WrappedItemModel(BakedModel wrapped) { - this.wrapped = wrapped; - parentState = TransformUtils.stateFromItemTransforms(wrapped.getTransforms()); - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - return Collections.emptyList(); - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return wrapped.getParticleIcon(); - } - - @Override - public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { - return wrapped.getParticleIcon(data); - } - - @Override - public ItemOverrides getOverrides() { - return overrideList; - } - - /** - * Render the wrapped model. - *

    - * This does not take into account all the special edge cases hardcoded into - * {@link ItemRenderer#render(ItemStack, ItemDisplayContext, boolean, PoseStack, MultiBufferSource, int, int, BakedModel)}. - * - * @param stack The stack. - * @param pStack The pose stack. - * @param buffers The {@link MultiBufferSource}. - * @param packedLight The packed light coords. See {@link LightTexture}. - * @param packedOverlay The packed Overlay coords. See {@link OverlayTexture}. - * @param fabulous If fabulous is required. (not sure on this desc, might be inaccurate as its value in vanilla - * is mixed with the aforementioned hardcoded edge cases.) - */ - protected void renderWrapped(ItemStack stack, PoseStack pStack, MultiBufferSource buffers, int packedLight, int packedOverlay, boolean fabulous) { - renderWrapped(stack, pStack, buffers, packedLight, packedOverlay, fabulous, Function.identity()); - } - - /** - * Overload of {@link #renderWrapped(ItemStack, PoseStack, MultiBufferSource, int, int, boolean)}. - *

    - * Except, with a callback to wrap the {@link VertexConsumer} used. - * - * @param stack The stack. - * @param pStack The pose stack. - * @param buffers The {@link MultiBufferSource}. - * @param packedLight The packed light coords. See {@link LightTexture}. - * @param packedOverlay The packed Overlay coords. See {@link OverlayTexture}. - * @param fabulous If fabulous is required. (not sure on this desc, might be inaccurate as its value in vanilla - * is mixed with the aforementioned hardcoded edge cases.) - */ - // TODO this needs to be redesigned so other IItemRenderers can be used as override models. - protected void renderWrapped(ItemStack stack, PoseStack pStack, MultiBufferSource buffers, int packedLight, int packedOverlay, boolean fabulous, Function consOverride) { - BakedModel model = wrapped.getOverrides().resolve(wrapped, stack, world, entity, 0); - if (model == null) return; // What? - - ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer(); - RenderType rType = ItemBlockRenderTypes.getRenderType(stack, fabulous); - VertexConsumer builder = ItemRenderer.getFoilBuffer(buffers, rType, true, stack.hasFoil()); - itemRenderer.renderModelLists(model, stack, packedLight, packedOverlay, pStack, consOverride.apply(builder)); - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java b/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java deleted file mode 100644 index fbe7fd63..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; -import org.jetbrains.annotations.Nullable; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.Map; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -/** - * The BakedPipeline! - * Basically this allows us to efficiently transform a BakedQuad, - * the Pipeline has Elements, each element has a name, state and a transformer, - * you can enable and disable elements easily, you can also grab the underlying - * transformer for the element if you need to set its state before rendering. - *

    - * The BakedPipeline is final once created, you cannot add or remove elements, - * you should not need to add or remove them runtime, enable and disable exist. - *

    - * You must use the Builder class to construct a BakedPipeline, see {@link #builder} - *

    - * Transformers run on a mutable state inside each transformer, allowing for easy reuse. - * It is recommended to store your pipeline inside a ThreadLocal because 'minecraft'. - *

    - * Each Transformer should be smart enough to expand itself for each newly sized VertexFormat it comes across, - * meaning that the internal states for the transformers can be safely shared across VertexFormats, this reduces - * array creations, and generally makes the system as efficient as it is. - *

    - * To use the system: - * Grab any elements you need to set state data on first, using {@link #getElement(String, Class)} - * transformers should NOT clear their state on pipeline Reset's so set any global data on elements now. - * Assuming you are looping over a set of quads to transform, next you need to {@link #reset} the pipeline, - * Now you should disable / enable any optional elements that are needed, NOTE: Element states are reset when resetting - * the pipeline. - * Now you will need to call {@link #prepare(IVertexConsumer)} on the pipeline, here you will pass your collector, - * usually {@link Quad}. - * Now final step, simply pipe the quad you want to transform INTO the pipeline 'quad.pipe(pipeline)' - * And that's it! hell, Pipe a pipeline into each other for all i care, the system is efficient enough that there - * would be no performance penalty for doing so. - * - * @author covers1624 - */ -public class BakedPipeline implements IVertexConsumer { - - private final PipelineElement[] elements; - private final Map> nameLookup; - private @Nullable IPipelineConsumer first; - - private final Quad unpacker = new Quad(); - - private BakedPipeline(PipelineElement[] elements) { - this.elements = elements; - nameLookup = Arrays.stream(elements).collect(Collectors.toMap(e -> e.name, e -> e)); - } - - /** - * Used to create a BakedPipeline. - * - * @return The builder. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Used to reset the pipeline for the next quad. - * MUST be called between quads. - * - * @param format The format. - */ - public void reset(VertexFormat format) { - reset(CachedFormat.lookup(format)); - } - - /** - * Used to reset the pipeline for the next quad. - * MUST be called between quads. - * - * @param format The format. - */ - public void reset(CachedFormat format) { - unpacker.reset(format); - for (PipelineElement element : elements) { - element.reset(format); - } - first = null; - } - - /** - * Get an element from the pipeline. - * - * @param name The name of the element. - * @param clazz The Class of the element, used to safe cast. - * @return The element. - */ - public T getElement(String name, Class clazz) { - PipelineElement element = nameLookup.get(name); - if (element != null) { - if (!clazz.isAssignableFrom(element.consumer.getClass())) { - throw new IllegalArgumentException("Element with name " + name + " is not assignable from reference class."); - } - return clazz.cast(element.consumer); - } - throw new IllegalArgumentException("Element with name " + name + " does not exist."); - } - - /** - * Used to enable an element on the pipeline with the specified name. - * - * @param name The elements name. - */ - public void enableElement(String name) { - setElementState(name, true); - } - - /** - * Used to disable an element on the pipeline with the specified name. - * - * @param name The elements name. - */ - public void disableElement(String name) { - setElementState(name, false); - } - - /** - * Used to set the state of an element on the pipeline. - * - * @param name The name of the element. - * @param enabled The state to set it to. - */ - public void setElementState(String name, boolean enabled) { - PipelineElement element = nameLookup.get(name); - if (element != null) { - element.isEnabled = enabled; - return; - } - throw new IllegalArgumentException("Element with name " + name + " does not exist."); - } - - /** - * Call when you are ready to use the pipeline. - * This builds the internal state of the Elements getting things ready to transform. - * - * @param collector The IVertexConsumer that should collect the transformed quad. - */ - public void prepare(IVertexConsumer collector) { - if (elements.length == 0) throw new IllegalStateException("No elements in the pipeline."); - - IPipelineConsumer next = null; - for (PipelineElement element : elements) { - if (element.isEnabled) { - if (first == null) { - first = element.consumer; - } else { - assert next != null; - next.setParent(element.consumer); - } - next = element.consumer; - } - } - assert next != null; - next.setParent(collector); - } - - @Override - public VertexFormat getVertexFormat() { - check(); - assert first != null; - return first.getVertexFormat(); - } - - @Override - public void setQuadTint(int tint) { - check(); - unpacker.setQuadTint(tint); - } - - @Override - public void setQuadOrientation(Direction orientation) { - check(); - unpacker.setQuadOrientation(orientation); - } - - @Override - public void setApplyDiffuseLighting(boolean diffuse) { - check(); - unpacker.setApplyDiffuseLighting(diffuse); - } - - @Override - public void setTexture(TextureAtlasSprite texture) { - check(); - unpacker.setTexture(texture); - } - - @Override - public void put(int element, float... data) { - check(); - unpacker.put(element, data); - if (unpacker.full) { - onFull(); - } - } - - @Override - public void put(Quad quad) { - check(); - unpacker.put(quad); - } - - private void check() { - if (first == null) { - throw new IllegalStateException("Pipeline used before prepare was called."); - } - } - - private void onFull() { - assert first != null; - first.setInputQuad(unpacker); - first.put(unpacker); - } - - /** - * Internal class, used to hold a PipelineElement's state. - */ - public static class PipelineElement { - - public final String name; - public final boolean defaultState; - public final T consumer; - public boolean isEnabled; - - public PipelineElement(String name, boolean defaultState, T consumer) { - this.name = name; - this.defaultState = defaultState; - this.consumer = consumer; - } - - public void reset(CachedFormat format) { - isEnabled = defaultState; - consumer.setParent(null); - consumer.reset(format); - } - } - - /** - * The builder associated with the BakedPipeline. - * You must create a BakedPipeline with this, - * once created a pipeline cannot be modified, - * modifying should not be needed as you can enable - * and disable elements with ease. - */ - public static class Builder { - - private final LinkedList> elements = new LinkedList<>(); - - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @return The same builder. - */ - public Builder addFirst(String name, IPipelineElementFactory factory) { - return addFirst(name, factory, true); - } - - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @return The same builder. - */ - public Builder addFirst(String name, IPipelineElementFactory factory, boolean defaultState) { - return addFirst(name, factory, defaultState, e -> { - }); - } - - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @param defaultsSetter A callback used to set any defaults on the transformer. - * @return The same builder. - */ - public Builder addFirst(String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter) { - PipelineElement element = makeElement(name, factory, defaultState); - defaultsSetter.accept(element.consumer); - elements.addFirst(element); - return this; - } - - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @return The same builder. - */ - public Builder addElement(String name, IPipelineElementFactory factory) { - return addElement(name, factory, true); - } - - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @return The same builder. - */ - public Builder addElement(String name, IPipelineElementFactory factory, boolean defaultState) { - return addElement(name, factory, defaultState, e -> { - }); - } - - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @param defaultsSetter A callback used to set any defaults on the transformer. - * @return The same builder. - */ - public Builder addElement(String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter) { - PipelineElement element = makeElement(name, factory, defaultState); - defaultsSetter.accept(element.consumer); - elements.add(element); - return this; - } - - // Internal method, used to construct the PipelineElement class. - private PipelineElement makeElement(String name, IPipelineElementFactory factory, boolean defaultState) { - if (elements.stream().anyMatch(p -> p.name.equals(name))) { - throw new IllegalArgumentException("Unable to add element with duplicate name: " + name); - } - return new PipelineElement<>(name, defaultState, factory.create()); - } - - /** - * Call this once you are finished to build your BakedPipeline! - * - * @return The new Pipeline. - */ - public BakedPipeline build() { - return new BakedPipeline(elements.toArray(new PipelineElement[0])); - } - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java b/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java deleted file mode 100644 index 89ff5e54..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad; -import codechicken.lib.model.pipeline.transformers.QuadReInterpolator; -import org.jetbrains.annotations.Nullable; - -/** - * Anything implementing this may be used in the BakedPipeline. - * - * @author covers1624 - */ -public interface IPipelineConsumer extends IVertexConsumer { - - /** - * The quad at the start of the transformation. - * This is useful for obtaining the vertex data before any transformations have been applied, - * such as interpolation, See {@link QuadReInterpolator}. - * When overriding this make sure you call setInputQuad on your parent consumer too. - * - * @param quad The quad. - */ - void setInputQuad(Quad quad); - - /** - * Resets the Consumer to the new format. - * This should resize any internal arrays if needed, ready for the new vertex data. - * - * @param format The format to reset to. - */ - void reset(CachedFormat format); - - /** - * Sets the parent consumer. - * This consumer may choose to not pipe any data, - * that's fine, but if it does, it MUST pipe the data to the one provided here. - * - * @param parent The parent. - */ - void setParent(@Nullable IVertexConsumer parent); -} diff --git a/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java b/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java deleted file mode 100644 index ac2aa55f..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; -import org.jetbrains.annotations.Nullable; - -import javax.annotation.OverridingMethodsMustInvokeSuper; - -import static java.util.Objects.requireNonNull; - -/** - * Base class for a simple QuadTransformer. - * Operates on BakedQuads. - * QuadTransformers can be piped into each other at no performance penalty. - * - * @author covers1624 - */ -public abstract class QuadTransformer implements IVertexConsumer, IPipelineConsumer { - - protected final Quad quad; - protected @Nullable CachedFormat format; - protected @Nullable IVertexConsumer consumer; - - /** - * Used for the BakedPipeline. - */ - protected QuadTransformer() { - quad = new Quad(); - } - - public QuadTransformer(IVertexConsumer consumer) { - this(consumer.getVertexFormat(), consumer); - } - - public QuadTransformer(VertexFormat format, IVertexConsumer consumer) { - this(CachedFormat.lookup(format), consumer); - } - - public QuadTransformer(CachedFormat format, IVertexConsumer consumer) { - this.format = format; - this.consumer = consumer; - quad = new Quad(format); - } - - @Override - @OverridingMethodsMustInvokeSuper - public void reset(CachedFormat format) { - this.format = format; - quad.reset(format); - } - - @Override - public void setParent(@Nullable IVertexConsumer parent) { - consumer = parent; - } - - @Override - @OverridingMethodsMustInvokeSuper - public void setInputQuad(Quad quad) { - if (consumer instanceof IPipelineConsumer) { - ((IPipelineConsumer) consumer).setInputQuad(quad); - } - } - - // @formatter:off - @Override public VertexFormat getVertexFormat() { return requireNonNull(format).format; } - @Override public void setQuadTint( int tint ) { quad.setQuadTint( tint ); } - @Override public void setQuadOrientation( Direction orientation ) { quad.setQuadOrientation( orientation ); } - @Override public void setApplyDiffuseLighting( boolean diffuse ) { quad.setApplyDiffuseLighting( diffuse ); } - @Override public void setTexture( TextureAtlasSprite texture ) { quad.setTexture( texture ); } - // @formatter:on - - @Override - public void put(int element, float... data) { - quad.put(element, data); - if (quad.full) { - onFull(); - } - } - - @Override - public void put(Quad quad) { - this.quad.put(quad); - onFull(); - } - - /** - * Called to transform the vertices. - * - * @return If the transformer should pipe the quad. - */ - public abstract boolean transform(); - - public void onFull() { - if (transform()) { - quad.pipe(requireNonNull(consumer)); - } - } - - // Should be small enough. - private final static double EPSILON = 0.00001; - - public static boolean epsComp(float a, float b) { - if (a == b) { - return true; - } else { - return Math.abs(a - b) < EPSILON; - } - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java deleted file mode 100644 index 77f5f796..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline.transformers; - -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; - -/** - * This transformer simply overrides the alpha of the quad. - * Only operates if the format has color. - * - * @author covers1624 - */ -public class QuadAlphaOverride extends QuadTransformer { - - public static final IPipelineElementFactory FACTORY = QuadAlphaOverride::new; - - private float alphaOverride; - - QuadAlphaOverride() { - super(); - } - - public QuadAlphaOverride(IVertexConsumer consumer, float alphaOverride) { - super(consumer); - this.alphaOverride = alphaOverride; - } - - public QuadAlphaOverride setAlphaOverride(float alphaOverride) { - this.alphaOverride = alphaOverride; - return this; - } - - @Override - public boolean transform() { - if (format.hasColor) { - for (Vertex v : quad.vertices) { - v.color()[3] = alphaOverride; - } - } - return true; - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java deleted file mode 100644 index 03611722..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline.transformers; - -import codechicken.lib.math.InterpHelper; -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.Quad; -import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; - -/** - * This transformer Re-Interpolates the Color, UV's and LightMaps. - * Use this after all transformations that translate vertices in the pipeline. - *

    - * This Transformation can only be used in the BakedPipeline. - * - * @author covers1624 - */ -public class QuadReInterpolator extends QuadTransformer { - - public static final IPipelineElementFactory FACTORY = QuadReInterpolator::new; - - private final Quad interpCache = new Quad(); - private final InterpHelper interpHelper = new InterpHelper(); - - QuadReInterpolator() { - super(); - } - - @Override - public void reset(CachedFormat format) { - super.reset(format); - interpCache.reset(format); - } - - @Override - public void setInputQuad(Quad quad) { - super.setInputQuad(quad); - assert quad.orientation != null; - quad.resetInterp(interpHelper, quad.orientation.ordinal() >> 1); - } - - @Override - public boolean transform() { - assert quad.orientation != null; - int s = quad.orientation.ordinal() >> 1; - if (format.hasColor || format.hasUV || format.hasLightMap) { - interpCache.copyFrom(quad); - interpHelper.setup(); - for (Vertex v : quad.vertices) { - interpHelper.locate(v.dx(s), v.dy(s)); - if (format.hasColor) { - v.interpColorFrom(interpHelper, interpCache.vertices); - } - if (format.hasUV) { - v.interpUVFrom(interpHelper, interpCache.vertices); - } - if (format.hasLightMap) { - v.interpLightMapFrom(interpHelper, interpCache.vertices); - } - } - } - return true; - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java b/src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java deleted file mode 100644 index 50811589..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@NonNullApi -package codechicken.lib.model.pipeline.transformers; - -import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/packet/CCFriendlyByteBufExtension.java b/src/main/java/codechicken/lib/packet/CCFriendlyByteBufExtension.java new file mode 100644 index 00000000..017b3f8c --- /dev/null +++ b/src/main/java/codechicken/lib/packet/CCFriendlyByteBufExtension.java @@ -0,0 +1,130 @@ +package codechicken.lib.packet; + +import codechicken.lib.vec.Cuboid6; +import codechicken.lib.vec.Vector3; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; + +/** + * An extension interface containing various helpers + * for reading and writing to {@link FriendlyByteBuf}. + *

    + * Created by covers1624 on 10/31/25. + * @see FriendlyByteBuf + * @see CCRegistryFriendlyByteBufExtension + */ +public interface CCFriendlyByteBufExtension { + + private FriendlyByteBuf self() { + return (FriendlyByteBuf) this; + } + + // region Signed var primitives. + + /** + * Writes a Signed Variable length int. + * Favourable for numbers {@code <= -1} + * + * @param i The int. + * @return The same stream. + */ + default FriendlyByteBuf cc$writeSignedVarInt(int i) { + SignedVarInt.write(self(), i); + return self(); + } + + /** + * Reads a Variable length signed int. + * + * @return The int. + * @see CCFriendlyByteBufExtension#cc$writeSignedVarInt + */ + default int cc$readSignedVarInt() { + return SignedVarInt.read(self()); + } + + /** + * Writes a Signed Variable length long. + * Favourable for numbers {@code <= -1} + * + * @param i The long. + * @return The same stream. + */ + default FriendlyByteBuf cc$writeSignedVarLong(long i) { + SignedVarLong.write(self(), i); + return self(); + } + + /** + * Reads a Variable length signed long. + * + * @return The long. + * @see CCFriendlyByteBufExtension#cc$writeSignedVarLong + */ + default long cc$readSignedVarLong() { + return SignedVarLong.read(self()); + } + // endregion + + /** + * Write to the stream with a {@link StreamEncoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @param thing The thing to write. + * @return The same stream. + */ + default FriendlyByteBuf cc$writeWithCodec(StreamEncoder codec, T thing) { + codec.encode(self(), thing); + return self(); + } + + /** + * Read from the stream with a {@link StreamDecoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @return The thing that was read. + */ + default T cc$readWithCodec(StreamDecoder codec) { + return codec.decode(self()); + } + + /** + * Write a {@link Vector3} to the stream. + * + * @param vec The vector. + * @return The same stream. + */ + default FriendlyByteBuf writeVector3(Vector3 vec) { + return cc$writeWithCodec(Vector3.STREAM_CODEC, vec); + } + + /** + * Read a {@link Vector3} from the stream. + * + * @return The vector. + */ + default Vector3 readVector3() { + return cc$readWithCodec(Vector3.STREAM_CODEC); + } + + /** + * Write a {@link Cuboid6} to the stream. + * + * @param cuboid The cuboid. + * @return The same stream. + */ + default FriendlyByteBuf writeCuboid6(Cuboid6 cuboid) { + return cc$writeWithCodec(Cuboid6.STREAM_CODEC, cuboid); + } + + /** + * Read a {@link Cuboid6} from the stream. + * + * @return The cuboid. + */ + default Cuboid6 readCuboid6() { + return cc$readWithCodec(Cuboid6.STREAM_CODEC); + } +} diff --git a/src/main/java/codechicken/lib/packet/CCRegistryFriendlyByteBufExtension.java b/src/main/java/codechicken/lib/packet/CCRegistryFriendlyByteBufExtension.java new file mode 100644 index 00000000..73aaa4e4 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/CCRegistryFriendlyByteBufExtension.java @@ -0,0 +1,44 @@ +package codechicken.lib.packet; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; + +/** + * An extension interface containing various helpers + * for reading and writing to {@link RegistryFriendlyByteBuf}. + *

    + * Created by covers1624 on 10/31/25. + * + * @see RegistryFriendlyByteBuf + * @see CCFriendlyByteBufExtension + */ +public interface CCRegistryFriendlyByteBufExtension extends CCFriendlyByteBufExtension { + + private RegistryFriendlyByteBuf self() { + return (RegistryFriendlyByteBuf) this; + } + + /** + * Write to the stream with a {@link StreamEncoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @param thing The thing to write. + * @return The same stream. + */ + default RegistryFriendlyByteBuf cc$writeWithRegistryCodec(StreamEncoder codec, T thing) { + codec.encode(self(), thing); + return self(); + } + + /** + * Read from the stream with a {@link StreamDecoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @return The thing that was read. + */ + default T cc$readWithRegistryCodec(StreamDecoder codec) { + return codec.decode(self()); + } +} diff --git a/src/main/java/codechicken/lib/packet/CCStreamCodecs.java b/src/main/java/codechicken/lib/packet/CCStreamCodecs.java new file mode 100644 index 00000000..c7ed0208 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/CCStreamCodecs.java @@ -0,0 +1,230 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import net.minecraft.network.Utf8String; +import net.minecraft.network.VarInt; +import net.minecraft.network.VarLong; +import net.minecraft.network.codec.StreamCodec; + +/** + * Created by covers1624 on 10/31/25. + */ +public final class CCStreamCodecs { + + public static final StreamCodec BYTE_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + buf.writeBytes(arr); + }, + buf -> { + int len = VarInt.read(buf); + byte[] arr = new byte[len]; + buf.readBytes(arr); + return arr; + } + ); + + public static final StreamCodec CHAR_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (char v : arr) { + buf.writeChar(v); + } + }, + buf -> { + int len = VarInt.read(buf); + char[] arr = new char[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readChar(); + } + return arr; + } + ); + + public static final StreamCodec SHORT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (short v : arr) { + buf.writeShort(v); + } + }, + buf -> { + int len = VarInt.read(buf); + short[] arr = new short[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readShort(); + } + return arr; + } + ); + + public static final StreamCodec INT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (int v : arr) { + buf.writeInt(v); + } + }, + buf -> { + int len = VarInt.read(buf); + int[] arr = new int[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readInt(); + } + return arr; + } + ); + + public static final StreamCodec VAR_INT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (int v : arr) { + VarInt.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + int[] arr = new int[len]; + for (int i = 0; i < len; i++) { + arr[i] = VarInt.read(buf); + } + return arr; + } + ); + + public static final StreamCodec SIGNED_VAR_INT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (int v : arr) { + SignedVarInt.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + int[] arr = new int[len]; + for (int i = 0; i < len; i++) { + arr[i] = SignedVarInt.read(buf); + } + return arr; + } + ); + + public static final StreamCodec LONG_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (long v : arr) { + buf.writeLong(v); + } + }, + buf -> { + int len = VarInt.read(buf); + long[] arr = new long[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readLong(); + } + return arr; + } + ); + + public static final StreamCodec VAR_LONG_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (long v : arr) { + VarLong.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + long[] arr = new long[len]; + for (int i = 0; i < len; i++) { + arr[i] = VarLong.read(buf); + } + return arr; + } + ); + + public static final StreamCodec SIGNED_VAR_LONG_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (long v : arr) { + SignedVarLong.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + long[] arr = new long[len]; + for (int i = 0; i < len; i++) { + arr[i] = SignedVarLong.read(buf); + } + return arr; + } + ); + + public static final StreamCodec FLOAT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (float v : arr) { + buf.writeFloat(v); + } + }, + buf -> { + int len = VarInt.read(buf); + float[] arr = new float[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readFloat(); + } + return arr; + } + ); + + public static final StreamCodec DOUBLE_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (double v : arr) { + buf.writeDouble(v); + } + }, + buf -> { + int len = VarInt.read(buf); + double[] arr = new double[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readDouble(); + } + return arr; + } + ); + + public static final StreamCodec BOOLEAN_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (boolean v : arr) { + buf.writeBoolean(v); + } + }, + buf -> { + int len = VarInt.read(buf); + boolean[] arr = new boolean[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readBoolean(); + } + return arr; + } + ); + + public static final StreamCodec STRING_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (String v : arr) { + Utf8String.write(buf, v, Short.MAX_VALUE); + } + }, + buf -> { + int len = VarInt.read(buf); + String[] arr = new String[len]; + for (int i = 0; i < len; i++) { + arr[i] = Utf8String.read(buf, Short.MAX_VALUE); + } + return arr; + } + ); +} diff --git a/src/main/java/codechicken/lib/packet/ConfigurationStreamPacket.java b/src/main/java/codechicken/lib/packet/ConfigurationStreamPacket.java new file mode 100644 index 00000000..1e6845ce --- /dev/null +++ b/src/main/java/codechicken/lib/packet/ConfigurationStreamPacket.java @@ -0,0 +1,36 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +/** + * Created by covers1624 on 10/31/25. + */ +public class ConfigurationStreamPacket extends FriendlyByteBuf implements CustomPacketPayload { + + private final CustomPacketPayload.Type type; + + ConfigurationStreamPacket(CustomPacketPayload.Type type, ByteBuf source) { + super(source); + this.type = type; + } + + public static StreamCodec createCodec(Type type) { + return StreamCodec.of( + (buf, p) -> buf.writeBytes(p, 0, p.writerIndex()), + (buf) -> { + var packet = new ConfigurationStreamPacket(type, Unpooled.buffer(buf.readableBytes())); + buf.readBytes(packet); + return packet; + } + ); + } + + @Override + public Type type() { + return type; + } +} diff --git a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java index 40ddeafe..078e318f 100644 --- a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java @@ -11,8 +11,10 @@ /** * Created by covers1624 on 2/03/2017. */ +@Deprecated (forRemoval = true) public interface ICustomPacketHandler { + @Deprecated (forRemoval = true) interface IClientPacketHandler extends ICustomPacketHandler { /** @@ -24,6 +26,7 @@ interface IClientPacketHandler extends ICustomPacketHandler { void handlePacket(PacketCustom packet, Minecraft mc); } + @Deprecated (forRemoval = true) interface IServerPacketHandler extends ICustomPacketHandler { /** @@ -38,6 +41,7 @@ interface IServerPacketHandler extends ICustomPacketHandler { /** * Used with {@link RegisterConfigurationTasksEvent} to send packets to the client during the configuration phase. */ + @Deprecated (forRemoval = true) interface IClientConfigurationPacketHandler extends ICustomPacketHandler { /** @@ -51,6 +55,7 @@ interface IClientConfigurationPacketHandler extends ICustomPacketHandler { // TODO this is tricky, as we don't have any context to identify the sending client and have a meaningful back/forth. // Its likely not incredibly useful for our uses cases here. + @Deprecated (forRemoval = true) @ApiStatus.Experimental interface IServerConfigurationPacketHandler extends ICustomPacketHandler { diff --git a/src/main/java/codechicken/lib/packet/PacketCustom.java b/src/main/java/codechicken/lib/packet/PacketCustom.java index 6425ecf3..014e264a 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustom.java +++ b/src/main/java/codechicken/lib/packet/PacketCustom.java @@ -16,8 +16,8 @@ import net.minecraft.network.codec.StreamEncoder; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; @@ -33,9 +33,10 @@ import java.util.UUID; //Tasty Cheese! +@Deprecated (forRemoval = true) public final class PacketCustom extends MCDataByteBuf { - private final ResourceLocation channel; + private final Identifier channel; private final boolean inbound; private final int type; private final @Nullable RegistryAccess registryAccess; @@ -48,7 +49,7 @@ public final class PacketCustom extends MCDataByteBuf { registryAccess = pkt.registryAccess(); } - public PacketCustom(ResourceLocation channel, int type, @Nullable RegistryAccess registryAccess) { + public PacketCustom(Identifier channel, int type, @Nullable RegistryAccess registryAccess) { super(Unpooled.buffer(), registryAccess); if (!MathHelper.between(0, type, 255)) { throw new RuntimeException("Invalid packet type, Must be between 0 and 255. Got: " + type); @@ -68,7 +69,7 @@ public int getType() { return type; } - public ResourceLocation getChannel() { + public Identifier getChannel() { return channel; } @@ -180,7 +181,7 @@ public void sendToServer() { @Override public PacketCustom writeDoubleBuffer(DoubleBuffer buffer) { super.writeDoubleBuffer(buffer); return this; } @Override public PacketCustom writeVector(Vector3 vec) { super.writeVector(vec); return this; } @Override public PacketCustom writeCuboid(Cuboid6 cuboid) { super.writeCuboid(cuboid); return this; } - @Override public PacketCustom writeResourceLocation(ResourceLocation loc) { super.writeResourceLocation(loc); return this; } + @Override public PacketCustom writeResourceLocation(Identifier loc) { super.writeResourceLocation(loc); return this; } @Override public PacketCustom writeDirection(Direction dir) { super.writeDirection(dir); return this; } @Override public PacketCustom writePos(BlockPos pos) { super.writePos(pos); return this; } @Override public PacketCustom writeVec3i(Vec3i vec) { super.writeVec3i(vec); return this; } @@ -191,9 +192,9 @@ public void sendToServer() { @Override public PacketCustom writeItemStack(ItemStack stack) { super.writeItemStack(stack); return this; } @Override public PacketCustom writeTextComponent(Component component) { super.writeTextComponent(component); return this; } @Override public PacketCustom writeRegistryIdDirect(Registry registry, T entry) { super.writeRegistryIdDirect(registry, entry); return this; } - @Override public PacketCustom writeRegistryIdDirect(Registry registry, ResourceLocation entry) { super.writeRegistryIdDirect(registry, entry); return this; } + @Override public PacketCustom writeRegistryIdDirect(Registry registry, Identifier entry) { super.writeRegistryIdDirect(registry, entry); return this; } @Override public PacketCustom writeRegistryId(Registry registry, T entry) { super.writeRegistryId(registry, entry); return this; } - @Override public PacketCustom writeRegistryId(Registry registry, ResourceLocation entry) { super.writeRegistryId(registry, entry); return this; } + @Override public PacketCustom writeRegistryId(Registry registry, Identifier entry) { super.writeRegistryId(registry, entry); return this; } @Override public PacketCustom writeByteBuf(ByteBuf buf) { super.writeByteBuf(buf); return this; } @Override public PacketCustom append(ByteBuf buf) { super.append(buf); return this; } //@formatter:on diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java index 72f31efe..c89a6ff8 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -10,10 +10,11 @@ import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.level.ServerPlayer; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.client.network.event.RegisterClientPayloadHandlersEvent; import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; import net.neoforged.neoforge.network.handling.IPayloadContext; import net.neoforged.neoforge.network.registration.HandlerThread; @@ -27,11 +28,12 @@ /** * Created by covers1624 on 3/7/24. */ +@Deprecated (forRemoval = true) public class PacketCustomChannel { private static final Logger LOGGER = LoggerFactory.getLogger(PacketCustomChannel.class); - public final ResourceLocation channel; + public final Identifier channel; private @Nullable String version; private boolean optional; @@ -41,7 +43,7 @@ public class PacketCustomChannel { private @Nullable IClientPacketHandler client; private @Nullable IServerPacketHandler server; - public PacketCustomChannel(ResourceLocation channel) { + public PacketCustomChannel(Identifier channel) { this.channel = channel; } @@ -56,7 +58,7 @@ public PacketCustomChannel optional() { } public PacketCustomChannel clientConfiguration(Supplier> supplier) { - if (FMLEnvironment.dist.isClient()) { + if (FMLEnvironment.getDist().isClient()) { clientConfiguration = supplier.get().get(); } return this; @@ -69,7 +71,7 @@ public PacketCustomChannel clientConfiguration(Supplier> supplier) { - if (FMLEnvironment.dist.isClient()) { + if (FMLEnvironment.getDist().isClient()) { client = supplier.get().get(); } return this; @@ -82,6 +84,9 @@ public PacketCustomChannel server(Supplier> suppl public void init(IEventBus modBus) { modBus.addListener(this::onRegisterPayloadHandlerEvent); + if (FMLEnvironment.getDist().isClient()) { + modBus.addListener(this::onRegisterClientPayloads); + } } private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event) { @@ -103,27 +108,15 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event) { type, codec, (payload, context) -> { - switch (context.flow()) { - case CLIENTBOUND -> { - if (client != null) { - enqueue(context, payload, () -> { - client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); - }); - } - } - case SERVERBOUND -> { - if (server != null) { - enqueue(context, payload, () -> { - server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player()); - }); - } - } + if (server != null) { + enqueue(context, payload, () -> { + server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player()); + }); } - } ); registrar.configurationToClient( - type, + new CustomPacketPayload.Type<>(channel.withPrefix("configuration/")), codec, (payload, context) -> { if (clientConfiguration != null) { @@ -135,6 +128,20 @@ private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event) { ); } + private void onRegisterClientPayloads(RegisterClientPayloadHandlersEvent event) { + event.register( + new CustomPacketPayload.Type(channel), + HandlerThread.NETWORK, + (payload, context) -> { + if (client != null) { + enqueue(context, payload, () -> { + client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + } + } + ); + } + private static void enqueue(IPayloadContext context, PacketCustom.Pkt payload, Runnable runnable) { context.enqueueWork(() -> { try { diff --git a/src/main/java/codechicken/lib/packet/PacketSender.java b/src/main/java/codechicken/lib/packet/PacketSender.java index 9d9c0615..d6134b57 100644 --- a/src/main/java/codechicken/lib/packet/PacketSender.java +++ b/src/main/java/codechicken/lib/packet/PacketSender.java @@ -33,7 +33,7 @@ public class PacketSender { * @return The packet. */ public static Packet toClientPacket(CustomPacketPayload payload) { - return new ClientboundCustomPayloadPacket(payload); + return payload.toVanillaClientbound(); } /** @@ -237,7 +237,7 @@ public static void sendToOps(Packet packet) { PlayerList playerList = getCurrentServer().getPlayerList(); ServerOpList opList = playerList.getOps(); for (ServerPlayer player : playerList.getPlayers()) { - if (opList.get(player.getGameProfile()) != null) { + if (opList.get(player.nameAndId()) != null) { sendToPlayer(packet, player); } } @@ -253,7 +253,7 @@ public static void sendToOps(Packet packet) { * @return The packet. */ public static Packet toServerPacket(CustomPacketPayload payload) { - return new ServerboundCustomPayloadPacket(payload); + return payload.toVanillaServerbound(); } /** diff --git a/src/main/java/codechicken/lib/packet/SignedVarInt.java b/src/main/java/codechicken/lib/packet/SignedVarInt.java new file mode 100644 index 00000000..1534f7f6 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/SignedVarInt.java @@ -0,0 +1,19 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import net.minecraft.network.VarInt; + +/** + * Created by covers1624 on 10/31/25. + */ +public final class SignedVarInt { + + public static ByteBuf write(ByteBuf buf, int i) { + return VarInt.write(buf, i >= 0 ? 2 * i : -2 * (i + 1) + 1); + } + + public static int read(ByteBuf buf) { + int i = VarInt.read(buf); + return (i & 1) == 0 ? i >>> 1 : -(i >>> 1) - 1; + } +} diff --git a/src/main/java/codechicken/lib/packet/SignedVarLong.java b/src/main/java/codechicken/lib/packet/SignedVarLong.java new file mode 100644 index 00000000..f7b2b3eb --- /dev/null +++ b/src/main/java/codechicken/lib/packet/SignedVarLong.java @@ -0,0 +1,20 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import net.minecraft.network.VarInt; +import net.minecraft.network.VarLong; + +/** + * Created by covers1624 on 10/31/25. + */ +public final class SignedVarLong { + + public static ByteBuf write(ByteBuf buf, long i) { + return VarLong.write(buf, i >= 0 ? 2 * i : -2 * (i + 1) + 1); + } + + public static long read(ByteBuf buf) { + long i = VarLong.read(buf); + return (i & 1) == 0 ? i >>> 1 : -(i >>> 1) - 1; + } +} diff --git a/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java b/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java index 64b533c0..5a6eb87a 100644 --- a/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java @@ -12,6 +12,7 @@ /** * Created by covers1624 on 21/5/20. */ +@Deprecated (forRemoval = true) public class SimpleClientPacketHandler implements IClientPacketHandler { private static final Logger LOGGER = LogManager.getLogger(); diff --git a/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java b/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java index ec6fa48b..619fbe43 100644 --- a/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java @@ -12,6 +12,7 @@ /** * Created by covers1624 on 21/5/20. */ +@Deprecated (forRemoval = true) public class SimpleServerPacketHandler implements IServerPacketHandler { private static final Logger LOGGER = LogManager.getLogger(); diff --git a/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java b/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java new file mode 100644 index 00000000..0d86ab11 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java @@ -0,0 +1,377 @@ +package codechicken.lib.packet; + +import codechicken.lib.internal.CCLNetwork; +import io.netty.buffer.Unpooled; +import net.covers1624.quack.util.CrashLock; +import net.minecraft.client.Minecraft; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.configuration.ServerConfigurationPacketListener; +import net.minecraft.resources.Identifier; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.neoforge.network.configuration.ICustomConfigurationTask; +import net.neoforged.neoforge.network.connection.ConnectionType; +import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * A simple Stream based network channel, very similar to the NeoForge api, however + * provides raw, stream-based packets. + *

    + * You would construct one of these and store it statically, see {@link CCLNetwork} for inspiration. + *

    + * Created by covers1624 on 10/26/25. + */ +public final class StreamNetworkChannel { + + private final CrashLock LOCK = new CrashLock("Already initialized."); + + private final String namespace; + private boolean optional; + + private final Map> packets = new HashMap<>(); + + /** + * Create a new network channel. + * + * @param namespace The namespace, usually your mod id. + */ + public StreamNetworkChannel(String namespace) { + this.namespace = namespace; + } + + /** + * Called with your mod event bus and mod container. + * + * @param bus Your mod event bus. + * @param container Your mod container. + */ + public void init(IEventBus bus, ModContainer container) { + LOCK.lock(); + bus.addListener(RegisterPayloadHandlersEvent.class, e -> onRegisterPayloadHandlerEvent(e, container)); + bus.addListener(this::onGameConfigurationEvent); + } + + /** + * Mark this network channel as optional, not required on the client/server. + * + * @return The same channel. + */ + public StreamNetworkChannel optional() { + this.optional = true; + return this; + } + + /** + * Register a packet to be set to the client during gameplay. + * + * @param name The name of the packet. + * @param handler The handler for the packet. + * @return A hande to construct packets. + */ + public ClientPacketHandle playToClient(String name, PlayHandler handler) { + var type = createType("play", name, PlayPacketType::new); + type.clientHandler = handler; + return type; + } + + /** + * Register a packet to be set to the server during gameplay. + * + * @param name The name of the packet. + * @param handler The handler for the packet. + * @return A hande to construct packets. + */ + public ServerPacketHandle playToServer(String name, PlayHandler handler) { + var type = createType("play", name, PlayPacketType::new); + type.serverHandler = handler; + return type; + } + + /** + * Register a packet to be set to either the client or the server during gameplay. + * + * @param name The name of the packet. + * @param serverHandler The handler for the packet server-side. + * @param clientHandler The handler for the packet client-side. + * @return A hande to construct packets. + */ + public BidirectionalPacketHandle playBidirectional(String name, PlayHandler serverHandler, PlayHandler clientHandler) { + var type = createType("play", name, PlayPacketType::new); + type.clientHandler = clientHandler; + type.serverHandler = serverHandler; + return type; + } + + /** + * Register a packet to configure a connecting client. + * + * @param name The name of the packet. + * @param factory The factory to construct a {@link ICustomConfigurationTask}. + * @param handler The handler for the packet client-side. + */ + public void configurationToClient(String name, ConfigurationTaskFactory factory, ConfigurationHandler handler) { + createType("configuration", name, id -> new ConfigurationPacketType(id, factory, handler)); + } + + // region Events + private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event, ModContainer container) { + var registrar = event.registrar(container.getModInfo().getVersion().toString()); + if (optional) registrar = registrar.optional(); + + for (PacketType type : packets.values()) { + type.register(registrar); + } + } + + private void onGameConfigurationEvent(RegisterConfigurationTasksEvent event) { + for (PacketType type : packets.values()) { + if (type instanceof ConfigurationPacketType cType) { + event.register(cType.getTask(event.getListener())); + } + } + } + // endregion + + private > T createType(String phase, String name, Function func) { + var id = makeId("play", name); + if (packets.containsKey(id)) throw new IllegalArgumentException("Packet with name " + name + " for the " + phase + " phase is already registered."); + + var type = func.apply(id); + packets.put(id, type); + return type; + } + + private Identifier makeId(String prefix, String name) { + return Identifier.fromNamespaceAndPath(namespace, prefix + "/" + name); + } + + // region Registration internal + private static abstract sealed class PacketType permits PlayPacketType, ConfigurationPacketType { + + protected final CustomPacketPayload.Type type; + + private PacketType(Identifier id) { + type = new CustomPacketPayload.Type<>(id); + } + + public abstract void register(PayloadRegistrar registrar); + } + + private static final class PlayPacketType extends PacketType implements BidirectionalPacketHandle { + + private @Nullable PlayHandler clientHandler; + private @Nullable PlayHandler serverHandler; + + private PlayPacketType(Identifier id) { + super(id); + } + + @Override + public void register(PayloadRegistrar registrar) { + var codec = StreamPacket.createCodec(type); + + if (clientHandler != null && serverHandler != null) { + registrar.playBidirectional(type, codec, serverHandler::accept, clientHandler::accept); + } else if (clientHandler != null) { + registrar.playToClient(type, codec, clientHandler::accept); + } else if (serverHandler != null) { + registrar.playToServer(type, codec, serverHandler::accept); + } else { + throw new IllegalStateException("Expected clientHandler or serverHandler to be non-null? This should not actually be possible."); + } + } + + @Override + public StreamPacket.ToClient toClient(RegistryAccess registryAccess) { + return new StreamPacket.ToClient( + type, + Unpooled.buffer(), + registryAccess, + ConnectionType.NEOFORGE + ); + } + + @Override + public StreamPacket.ToServer toServer() { + return new StreamPacket.ToServer( + type, + Unpooled.buffer(), + Minecraft.getInstance().getConnection().registryAccess(), + ConnectionType.NEOFORGE + ); + } + } + + private static final class ConfigurationPacketType extends PacketType { + + public final ConfigurationTask.Type configurationType; + private final ConfigurationTaskFactory factory; + private final ConfigurationHandler handler; + + private ConfigurationPacketType(Identifier id, ConfigurationTaskFactory factory, ConfigurationHandler handler) { + super(id); + this.factory = factory; + this.handler = handler; + configurationType = new ConfigurationTask.Type(type.id()); + } + + @Override + public void register(PayloadRegistrar registrar) { + var codec = ConfigurationStreamPacket.createCodec(type); + + registrar.configurationToClient( + type, + codec, + handler::accept + ); + } + + public ConfigurationTask getTask(ServerConfigurationPacketListener listener) { + var context = new ConfigurationContext() { + + @Override + public ConfigurationStreamPacket newPacket() { + return new ConfigurationStreamPacket(type, Unpooled.buffer()); + } + + @Override + public ServerConfigurationPacketListener packetListener() { + return listener; + } + }; + return factory.apply(configurationType, context); + } + } + // endregion + + /** + * A helpful interface for the gameplay packet handler type. + */ + public interface PlayHandler extends BiConsumer { + + @Override + void accept(RegistryFriendlyByteBuf packet, IPayloadContext ctx); + } + + /** + * A helpful interface for the configuration phase packet handler type. + */ + public interface ConfigurationHandler extends BiConsumer { + + @Override + void accept(FriendlyByteBuf packet, IPayloadContext ctx); + } + + /** + * The context available when executing a configuration task. + */ + public interface ConfigurationContext { + + /** + * Create a new packet to be sent on the configuration channel. + * + * @return The packet. + */ + ConfigurationStreamPacket newPacket(); + + /** + * @return The active configuration packet listener. + */ + ServerConfigurationPacketListener packetListener(); + } + + /** + * A factory for constructing {@link ICustomConfigurationTask} instances. Usually a record, storing both the type and context. + */ + public interface ConfigurationTaskFactory extends BiFunction { } + + /** + * A handle for constructing client-bound packets. + */ + public interface ClientPacketHandle { + + /** + * Construct a packet bound for a client. + * + * @param registryAccess The {@link RegistryAccess} instance. + * @return The packet. + */ + StreamPacket.ToClient toClient(RegistryAccess registryAccess); + + /** + * Construct a packet bound for a client. + * + * @param level A level to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(Level level) { + return toClient(level.registryAccess()); + } + + /** + * Construct a packet bound for a client. + * + * @param player A player to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(Player player) { + return toClient(player.registryAccess()); + } + + /** + * Construct a packet bound for a client. + * + * @param tile A BlockEntity to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(BlockEntity tile) { + return toClient(tile.getLevel()); + } + + /** + * Construct a packet bound for a client. + * + * @param entity An entity to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(Entity entity) { + return toClient(entity.level()); + } + } + + /** + * A handle for constructing server-bound packets. + */ + public interface ServerPacketHandle { + + /** + * Construct a packet bound for the server. + * + * @return The packet. + */ + StreamPacket.ToServer toServer(); + } + + /** + * A handle for constructing a packet bound for a client or the server. + */ + public interface BidirectionalPacketHandle extends ClientPacketHandle, ServerPacketHandle { } +} diff --git a/src/main/java/codechicken/lib/packet/StreamPacket.java b/src/main/java/codechicken/lib/packet/StreamPacket.java new file mode 100644 index 00000000..920ad4a1 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/StreamPacket.java @@ -0,0 +1,204 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.core.BlockPos; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.network.connection.ConnectionType; +import org.jetbrains.annotations.Nullable; + +/** + * An outbound packet for a specific {@link StreamNetworkChannel} packet. + *

    + * You will generally only ever see one of the subclasses, {@link ToClient} or {@link ToServer}. + *

    + * Created by covers1624 on 10/30/25. + */ +//Tasty Cheese! +public sealed class StreamPacket extends RegistryFriendlyByteBuf implements CustomPacketPayload permits StreamPacket.ToClient, StreamPacket.ToServer { + + private final Type type; + + StreamPacket(Type type, ByteBuf source, RegistryAccess registryAccess, ConnectionType connectionType) { + super(source, registryAccess, connectionType); + this.type = type; + } + + @Override + public Type type() { + return type; + } + + static StreamCodec createCodec(Type type) { + return StreamCodec.of( + (buf, p) -> buf.writeBytes(p, 0, p.writerIndex()), + (buf) -> { + var packet = new StreamPacket(type, Unpooled.buffer(buf.readableBytes()), buf.registryAccess(), ConnectionType.NEOFORGE); + buf.readBytes(packet); + return packet; + } + ); + } + + /** + * A client-bound packet, write your data, then use one of the various send methods, + * or {@link #toVanilla()} to send it out a vanilla path. + */ + public static final class ToClient extends StreamPacket { + + ToClient(Type type, ByteBuf source, RegistryAccess registryAccess, ConnectionType connectionType) { + super(type, source, registryAccess, connectionType); + } + + /** + * Wrap this packet into a vanilla {@link Packet}. + * + * @return The vanilla packet. + */ + public Packet toVanilla() { + return PacketSender.toClientPacket(this); + } + + /** + * Send the given packet to the specified player. If the specified player is {@code null}, + * sends the packet to all connected clients. + * + * @param player The receiver. {@code null} for all players. + */ + public void sendToPlayer(@Nullable ServerPlayer player) { + PacketSender.sendToPlayer(toVanilla(), player); + } + + /** + * Sends the given packet to all connected clients. + */ + public void sendToAllPlayers() { + PacketSender.sendToAllPlayers(toVanilla()); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

    + * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param pos The origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public void sendToAllAround(BlockPos pos, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toVanilla(), pos, range, dim); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

    + * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param x The X origin point to send around. + * @param y The Y origin point to send around. + * @param z The Z origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public void sendToAllAround(double x, double y, double z, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toVanilla(), x, y, z, range, dim); + } + + /** + * Send the given packet to all players within the given dimension. + * + * @param dim The dimension to send to. + */ + public void sendToDimension(ResourceKey dim) { + PacketSender.sendToDimension(toVanilla(), dim); + } + + /** + * Send the given packet to all players watching the chunk, that the given {@link BlockEntity} + * is within. + * + * @param tile The {@link BlockEntity} of the watched chunk to send to. + */ + public void sendToChunk(BlockEntity tile) { + PacketSender.sendToChunk(toVanilla(), tile); + } + + /** + * Send the given packet to all players watching the chunk specified by the + * given {@link BlockPos} in the specified dimension. + * + * @param level The level containing the chunk to send to. + * @param pos The {@link BlockPos} specifying the chunk to send to. + */ + public void sendToChunk(ServerLevel level, BlockPos pos) { + PacketSender.sendToChunk(toVanilla(), level, pos); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param level The level containing the chunk to send to. + * @param chunkX The chunk X coordinate to send to. + * @param chunkZ The chunk Z coordinate to send to. + */ + public void sendToChunk(ServerLevel level, int chunkX, int chunkZ) { + PacketSender.sendToChunk(toVanilla(), level, chunkX, chunkZ); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param level The level containing the chunk to send to. + * @param pos The {@link ChunkPos} to send to. + */ + public void sendToChunk(ServerLevel level, ChunkPos pos) { + PacketSender.sendToChunk(toVanilla(), level, pos); + } + + /** + * Send the given packet to all server operators. + */ + public void sendToOps() { + PacketSender.sendToOps(toVanilla()); + } + } + + /** + * A server-bound packet, write your data, then use one of the various send methods, + * or {@link #toVanilla()} to send it out a vanilla path. + */ + public static final class ToServer extends StreamPacket { + + ToServer(Type type, ByteBuf source, RegistryAccess registryAccess, ConnectionType connectionType) { + super(type, source, registryAccess, connectionType); + } + + /** + * Wrap this packet into a vanilla {@link Packet}. + * + * @return The vanilla packet. + */ + public Packet toVanilla() { + return PacketSender.toServerPacket(this); + } + + /** + * Send this packet to the server. + */ + public void sendToServer() { + PacketSender.sendToServer(toVanilla()); + } + } +} diff --git a/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java b/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java index 19bc779d..743c3e2c 100644 --- a/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java +++ b/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java @@ -16,16 +16,16 @@ public class SubHitBlockHitResult extends BlockHitResult implements Comparable instances = ThreadLocal.withInitial(BakedVertexSource::new); - - private final Quad unpacker = new Quad(CachedFormat.lookup(DefaultVertexFormat.BLOCK)); - - private int vertexIndex = 0; - private Vertex5[] vertices = new Vertex5[0]; - private Object[] attributes = new Object[0]; - private TextureAtlasSprite[] sprites = new TextureAtlasSprite[0]; - - @VisibleForTesting - BakedVertexSource() { - ensureAttr(AttributeKeyRegistry.numAttributes() - 1); - ensureSpace(24); //Ensure enough space for a full standard block model. - } - - public static BakedVertexSource instance() { - return instances.get(); - } - - @Override - public Vertex5[] getVertices() { - return vertices; - } - - @Override - public int getVertexCount() { - return vertexIndex; - } - - @Override - public T getAttribute(AttributeKey attr) { - ensureAttr(attr.attributeKeyIndex); - return unsafeCast(attributes[attr.attributeKeyIndex]); - } - - @Override - public boolean hasAttribute(AttributeKey attr) { - return attr == NormalAttribute.attributeKey || attr == ColourAttribute.attributeKey || attr == LightCoordAttribute.attributeKey; - } - - @Override - public void prepareVertex(CCRenderState ccrs) { - ccrs.sprite = sprites[ccrs.vertexIndex]; - } - - public void reset() { - reset(CachedFormat.lookup(DefaultVertexFormat.BLOCK)); - } - - public void reset(CachedFormat format) { - vertexIndex = 0; - unpacker.reset(format); - } - - // Use getVertexCount() - @Deprecated(forRemoval = true, since = "1.18.2") - public int availableVertices() { - return vertexIndex; - } - - private void onFull() { - ensureSpace(getVertexCount() + 4); - for (int i = 0; i < 4; i++) { - int v = vertexIndex++; - Quad.Vertex vertex = unpacker.vertices[i]; - Vertex5 vertex5 = vertices[v]; - vertex5.vec.set(vertex.vec()); - vertex5.uv.set(vertex.uv()); - - Vector3 normal = getAttr(NormalAttribute.attributeKey)[v]; - normal.set(vertex.normal()); - getAttr(LightCoordAttribute.attributeKey)[v].compute(vertex5.vec, normal); - - getAttr(ColourAttribute.attributeKey)[v] = Colour.packRGBA(vertex.color()); - - sprites[v] = unpacker.sprite; - } - unpacker.rewind(); - } - - private void ensureAttr(int aIdx) { - if (attributes.length <= aIdx) { - attributes = Arrays.copyOf(attributes, aIdx + 1); - } - } - - //Expands array storage. - @VisibleForTesting - void ensureSpace(int numVertices) { - //If we don't have enough, or are full, expand. - if (vertices.length < numVertices) { - int prevLen = vertices.length; - int fillStart = vertexIndex; - vertices = Arrays.copyOf(vertices, numVertices); - fill(vertices, fillStart, numVertices, Vertex5::new); - for (int aIdx = 0; aIdx < attributes.length; aIdx++) { - Object attr = attributes[aIdx]; - AttributeKey key = AttributeKeyRegistry.getAttributeKey(aIdx); - if (attr == null) { - attr = key.createDefault(numVertices); - } else { - attr = key.copy(unsafeCast(attr), numVertices); - } - attributes[aIdx] = attr; - //Fill non primitive vertex attributes with new things. - if (key == NormalAttribute.attributeKey) { - fill((Object[]) attr, fillStart, numVertices, Vector3::new); - } else if (key == LightCoordAttribute.attributeKey) { - fill((Object[]) attr, fillStart, numVertices, LC::new); - } - } - sprites = Arrays.copyOf(sprites, numVertices); - } - } - - private T getAttr(AttributeKey key) { - return unsafeCast(attributes[key.attributeKeyIndex]); - } - - @Override - public void put(Quad quad) { - unpacker.put(quad); - onFull(); - } - - @Override - public void put(int element, float... data) { - unpacker.put(element, data); - if (unpacker.full) { - onFull(); - } - } - - //@formatter:off - @Override public VertexFormat getVertexFormat() { return DefaultVertexFormat.BLOCK; } - @Override public void setQuadTint(int tint) { unpacker.setQuadTint(tint); } - @Override public void setQuadOrientation(Direction orientation) { unpacker.setQuadOrientation(orientation); } - @Override public void setApplyDiffuseLighting(boolean diffuse) { unpacker.setApplyDiffuseLighting(diffuse); } - @Override public void setTexture(TextureAtlasSprite texture) { unpacker.setTexture(texture); } - //@formatter:on - - private static void fill(Object[] arr, int start, int end, Supplier supplier) { - for (int i = start; i < end; i++) { - arr[i] = supplier.get(); - } - } -} diff --git a/src/main/java/codechicken/lib/render/CCModelLibrary.java b/src/main/java/codechicken/lib/render/CCModelLibrary.java index b3e5bc08..fd7bd768 100644 --- a/src/main/java/codechicken/lib/render/CCModelLibrary.java +++ b/src/main/java/codechicken/lib/render/CCModelLibrary.java @@ -3,12 +3,13 @@ import codechicken.lib.vec.Quat; import codechicken.lib.vec.Vector3; import codechicken.lib.vec.Vertex5; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.RenderStateShard; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.rendertype.RenderSetup; +import net.minecraft.client.renderer.rendertype.RenderType; +import net.minecraft.resources.Identifier; +import static codechicken.lib.CodeChickenLib.MOD_ID; import static codechicken.lib.math.MathHelper.phi; public class CCModelLibrary { @@ -81,21 +82,23 @@ private static void addIcosahedronTriangle(Vector3 vec1, double u1, double v1, V i++; } - public static RenderType getIcos4RenderType(ResourceLocation texture) { - return RenderType.create("icosahedron4", DefaultVertexFormat.BLOCK, VertexFormat.Mode.TRIANGLES, 256, makeIcosState(texture)); + public static RenderType getIcos4RenderType(Identifier texture) { + return RenderType.create( + MOD_ID + ":icosahedron4", + RenderSetup.builder(CCRenderPipelines.SOLID_TRIANGLES) + .withTexture("Sampler0", texture) + .useLightmap() + .createRenderSetup() + ); } - public static RenderType getIcos7RenderType(ResourceLocation texture) { - return RenderType.create("icosahedron7", DefaultVertexFormat.BLOCK, VertexFormat.Mode.QUADS, 256, makeIcosState(texture)); + public static RenderType getIcos7RenderType(Identifier texture) { + return RenderType.create( + MOD_ID + ":icosahedron7", + RenderSetup.builder(RenderPipelines.SOLID_BLOCK) + .withTexture("Sampler0", texture) + .useLightmap() + .createRenderSetup() + ); } - - public static RenderType.CompositeState makeIcosState(ResourceLocation texture) { - return RenderType.CompositeState.builder() - .setShaderState(RenderStateShard.RENDERTYPE_SOLID_SHADER) // TODO 1.20, this is probably wrong. - .setTextureState(new RenderStateShard.TextureStateShard(texture, false, false)) - .setTransparencyState(RenderStateShard.NO_TRANSPARENCY) - .setLightmapState(RenderStateShard.LIGHTMAP) - .createCompositeState(false); - } - } diff --git a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java index 3faeda69..d582a942 100644 --- a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java +++ b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java @@ -3,13 +3,18 @@ import codechicken.lib.raytracer.VoxelShapeBlockHitResult; import codechicken.lib.vec.Matrix4; import net.covers1624.quack.util.CrashLock; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.state.BlockOutlineRenderState; import net.minecraft.world.phys.BlockHitResult; import net.neoforged.bus.api.EventPriority; +import net.neoforged.neoforge.client.ClientHooks; import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.ExtractBlockOutlineRenderStateEvent; import net.neoforged.neoforge.client.event.RenderFrameEvent; -import net.neoforged.neoforge.client.event.RenderHighlightEvent; import net.neoforged.neoforge.common.NeoForge; +import java.util.List; + public class CCRenderEventHandler { private static final CrashLock LOCK = new CrashLock("Already Initialized"); @@ -32,14 +37,16 @@ private static void renderTick(RenderFrameEvent.Pre event) { renderFrame = event.getPartialTick().getGameTimeDeltaPartialTick(true); } - private static void onBlockHighlight(RenderHighlightEvent.Block event) { - //We have found a CuboidRayTraceResult, Lets render it properly.. - BlockHitResult hit = event.getTarget(); - if (hit instanceof VoxelShapeBlockHitResult voxelHit) { + private static void onBlockHighlight(ExtractBlockOutlineRenderStateEvent event) { + if (event.getHitResult() instanceof VoxelShapeBlockHitResult hit) { event.setCanceled(true); - Matrix4 mat = new Matrix4(event.getPoseStack()); - mat.translate(voxelHit.getBlockPos()); - RenderUtils.bufferShapeHitBox(mat, event.getMultiBufferSource(), event.getCamera(), voxelHit.shape); + event.getLevelRenderState().blockOutlineRenderState = new BlockOutlineRenderState( + event.getBlockPos(), + event.isInTranslucentPass(), + event.isHighContrast(), + hit.shape, + List.of() + ); } } } diff --git a/src/main/java/codechicken/lib/render/CCRenderPipelines.java b/src/main/java/codechicken/lib/render/CCRenderPipelines.java new file mode 100644 index 00000000..9e982093 --- /dev/null +++ b/src/main/java/codechicken/lib/render/CCRenderPipelines.java @@ -0,0 +1,32 @@ +package codechicken.lib.render; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.resources.Identifier; + +import static codechicken.lib.CodeChickenLib.MOD_ID; + +/** + * Created by covers1624 on 7/6/26. + */ +public class CCRenderPipelines { + + public static final RenderPipeline SOLID_TRIANGLES = RenderPipelines.SOLID_BLOCK.toBuilder() + .withVertexFormat(DefaultVertexFormat.BLOCK, VertexFormat.Mode.TRIANGLES) + .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/solid_triangles")) + .build(); + + public static final RenderPipeline POSITION_COLOR = RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS) + .withDepthWrite(true) // Overwritten from DEBUG_FILLED_SNIPPET as we very much want depth here. + .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/position_color")) + .build(); + + public static final RenderPipeline POSITION_COLOR_NO_DEPTH = RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS) + .withDepthWrite(false) + .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/position_color_no_depth")) + .build(); +} diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java index d0f40a6b..50dbbca3 100644 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ b/src/main/java/codechicken/lib/render/CCRenderState.java @@ -2,7 +2,7 @@ import codechicken.lib.colour.Colour; import codechicken.lib.colour.ColourRGBA; -import codechicken.lib.model.CachedFormat; +import codechicken.lib.render.buffer.BakedQuadVertexBuilder; import codechicken.lib.render.buffer.ISpriteAwareVertexConsumer; import codechicken.lib.render.buffer.TransformingVertexConsumer; import codechicken.lib.render.lighting.LC; @@ -20,8 +20,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.rendertype.RenderType; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; @@ -60,7 +60,6 @@ public class CCRenderState { public CCRenderPipeline pipeline; public @Nullable VertexConsumer r; public @Nullable VertexFormat fmt; - public @Nullable CachedFormat cFmt; //context /** @@ -106,6 +105,25 @@ public static CCRenderState instance() { return instances.get(); } + /** + * Bind this {@link CCRenderState} instance to a new {@link BakedQuadVertexBuilder}. + */ + public BakedQuadVertexBuilder bindBaking() { + var r = new BakedQuadVertexBuilder(); + bind(r, DefaultVertexFormat.BLOCK); + return r; + } + + /** + * Bind this {@link CCRenderState} instance to the given {@link BakedQuadVertexBuilder}. + * + * @param r The {@link BakedQuadVertexBuilder}. + */ + public BakedQuadVertexBuilder bind(BakedQuadVertexBuilder r) { + bind(r, DefaultVertexFormat.BLOCK); + return r; + } + /** * Bind this {@link CCRenderState} instance to the given {@link BufferBuilder}. * @@ -124,7 +142,16 @@ public void bind(BufferBuilder r) { public void bind(VertexConsumer consumer, VertexFormat format) { r = consumer; fmt = format; - cFmt = CachedFormat.lookup(format); + } + + /** + * Bind this {@link CCRenderState} to the given {@link VertexConsumer} and {@link RenderType}. + * + * @param consumer The {@link VertexConsumer} to bind to. + * @param renderType The {@link RenderType} of the {@link VertexConsumer}. + */ + public void bind(VertexConsumer consumer, RenderType renderType) { + bind(consumer, renderType.format()); } /** @@ -234,7 +261,6 @@ public void runPipeline() { public void writeVert() { assert r != null; assert fmt != null; - assert cFmt != null; if (sprite != null && r instanceof ISpriteAwareVertexConsumer cons) { cons.sprite(sprite); } @@ -258,7 +284,7 @@ public void writeVert() { } public void setBrightness(BlockAndTintGetter world, BlockPos pos) { - brightness = LevelRenderer.getLightColor(world, world.getBlockState(pos), pos); + brightness = LevelRenderer.getLightColor(world, pos); } public void setBrightness(Entity entity, float frameDelta) { diff --git a/src/main/java/codechicken/lib/render/CachedModel.java b/src/main/java/codechicken/lib/render/CachedModel.java new file mode 100644 index 00000000..8e9908c4 --- /dev/null +++ b/src/main/java/codechicken/lib/render/CachedModel.java @@ -0,0 +1,200 @@ +//package codechicken.lib.render; +// +//import com.mojang.blaze3d.buffers.GpuBuffer; +//import com.mojang.blaze3d.systems.RenderPass; +//import com.mojang.blaze3d.systems.RenderSystem; +//import com.mojang.blaze3d.vertex.*; +//import net.minecraft.client.renderer.rendertype.RenderType; +//import net.minecraft.util.Mth; +//import org.jetbrains.annotations.Nullable; +//import org.joml.Vector3f; +//import org.joml.Vector4f; +//import org.lwjgl.system.MemoryUtil; +// +//import java.util.OptionalDouble; +//import java.util.OptionalInt; +//import java.util.function.BiConsumer; +//import java.util.function.Consumer; +//import java.util.function.IntConsumer; +// +///** +// * Created by covers1624 on 11/3/25. +// */ +//public class CachedModel { +// +// private final String label; +// private final RenderType.CompositeRenderType renderType; +// private final BiConsumer factory; +// +// private final ByteBufferBuilder builder; +// +// private boolean dirty = true; +// private @Nullable GpuBuffer vertexBuffer; +// +// private @Nullable IndexBuffer indexBuffer; +// +// public CachedModel(String label, RenderType renderType, BiConsumer factory) { +// this.label = label; +// this.renderType = (RenderType.CompositeRenderType) renderType; +// this.factory = factory; +// +// builder = new ByteBufferBuilder(renderType.bufferSize()); +// } +// +// public void setDirty() { +// dirty = true; +// } +// +// public void render(Consumer cons) { +// renderType.setupRenderState(); +// if (dirty) { +// // Re-build the mesh data if we are marked dirty, we cache the underlying native byte buffer used, +// // we may wish to consider a cleanup heuristic, after 5 mins or smth. +// builder.discard(); +// BufferBuilder buffer = new BufferBuilder(builder, renderType.mode(), renderType.format()); +// factory.accept(renderType.format(), buffer); +// uploadMesh(buffer.buildOrThrow()); +// builder.discard(); +// dirty = false; +// } +// // These should be impossible, uploadMesh always sets both. +// assert vertexBuffer != null; +// assert indexBuffer != null; +// +// // Mirrors all the logic in RenderType.CompositeRenderType#render +// // However, uses our cached gpu buffers, and fires a callback to modify the RenderPass before draw. +// var target = renderType.state.outputState.getRenderTarget(); +// var colourTexture = RenderSystem.outputColorTextureOverride != null ? RenderSystem.outputColorTextureOverride : target.getColorTextureView(); +// var depthTexture = target.useDepth ? (RenderSystem.outputDepthTextureOverride != null ? RenderSystem.outputDepthTextureOverride : target.getDepthTextureView()) : null; +// +// var dynamicTransforms = RenderSystem.getDynamicUniforms() +// .writeTransform( +// RenderSystem.getModelViewMatrix(), +// new Vector4f(1.0F, 1.0F, 1.0F, 1.0F), +// new Vector3f(), +// RenderSystem.getTextureMatrix(), +// RenderSystem.getShaderLineWidth() +// ); +// +// try (var pass = RenderSystem.getDevice() +// .createCommandEncoder() +// .createRenderPass(() -> "CachedModel draw: " + label, colourTexture, OptionalInt.empty(), depthTexture, OptionalDouble.empty())) { +// pass.setPipeline(renderType.pipeline()); +// var scissorState = RenderSystem.getScissorStateForRenderTypeDraws(); +// if (scissorState.enabled()) { +// pass.enableScissor(scissorState.x(), scissorState.y(), scissorState.width(), scissorState.height()); +// } +// +// RenderSystem.bindDefaultUniforms(pass); +// pass.setUniform("DynamicTransforms", dynamicTransforms); +// cons.accept(pass); +// +// pass.setVertexBuffer(0, vertexBuffer); +// +// for (int i = 0; i < 12; i++) { +// var texture = RenderSystem.getShaderTexture(i); +// if (texture != null) { +// pass.bindSampler("Sampler" + i, texture); +// } +// } +// +// pass.setIndexBuffer(indexBuffer.buffer, indexBuffer.type); +// pass.drawIndexed(0, 0, indexBuffer.indexCount(), 1); +// } +// renderType.clearRenderState(); +// } +// +// private void uploadMesh(MeshData mesh) { +// try (mesh) { +// vertexBuffer = VertexFormat.uploadToBuffer( +// vertexBuffer, +// mesh.vertexBuffer(), +// GpuBuffer.USAGE_VERTEX | GpuBuffer.USAGE_COPY_DST, +// () -> "Vertex Buffer for CachedModel: " + label +// ); +// +// if (mesh.indexBuffer() == null) { +// indexBuffer = buildIndexBuffer( +// indexBuffer != null ? indexBuffer.buffer : null, +// mesh.drawState().mode(), +// mesh.drawState().indexCount() +// ); +// } else { +// indexBuffer = new IndexBuffer( +// VertexFormat.uploadToBuffer( +// indexBuffer != null ? indexBuffer.buffer : null, +// mesh.vertexBuffer(), +// GpuBuffer.USAGE_INDEX | GpuBuffer.USAGE_COPY_DST, +// () -> "Index Buffer for CachedModel: " + label +// ), +// mesh.drawState().indexType(), +// mesh.drawState().indexCount() +// ); +// } +// } +// } +// +// // Mostly mirrors RenderSystem.AutoStorageIndexBuffer, however, does not over-provision the buffer. +// private IndexBuffer buildIndexBuffer(@Nullable GpuBuffer indexBuffer, VertexFormat.Mode mode, int indexCount) { +// var gen = getGenForMode(mode); +// +// var type = VertexFormat.IndexType.least(indexCount); +// var buffer = MemoryUtil.memAlloc(Mth.roundToward(indexCount * type.bytes, 4)); +// IntConsumer inserter = switch (type) { +// case SHORT -> e -> buffer.putShort((short) e); +// case INT -> buffer::putInt; +// }; +// +// try { +// for (int i = 0; i < indexCount; i += gen.indexStride) { +// gen.func.buildIndex(inserter, i * gen.vertexStride / gen.indexStride); +// } +// +// buffer.flip(); +// +// return new IndexBuffer( +// VertexFormat.uploadToBuffer( +// indexBuffer, +// buffer, +// GpuBuffer.USAGE_INDEX | GpuBuffer.USAGE_COPY_DST, +// () -> "Index Buffer for CachedModel: " + label +// ), +// type, +// indexCount +// ); +// } finally { +// MemoryUtil.memFree(buffer); +// } +// } +// +// private static IndexGen getGenForMode(VertexFormat.Mode mode) { +// return switch (mode) { +// case QUADS -> new IndexGen(4, 6, (cons, i) -> { +// cons.accept(i); +// cons.accept(i + 1); +// cons.accept(i + 2); +// cons.accept(i + 2); +// cons.accept(i + 3); +// cons.accept(i); +// }); +// case LINES -> new IndexGen(4, 6, (cons, i) -> { +// cons.accept(i); +// cons.accept(i + 1); +// cons.accept(i + 2); +// cons.accept(i + 3); +// cons.accept(i + 2); +// cons.accept(i + 1); +// }); +// default -> new IndexGen(1, 1, IntConsumer::accept); +// }; +// } +// +// private record IndexGen(int vertexStride, int indexStride, GenFunc func) { +// } +// +// private interface GenFunc { +// void buildIndex(IntConsumer cons, int i); +// } +// +// private record IndexBuffer(GpuBuffer buffer, VertexFormat.IndexType type, int indexCount) { } +//} diff --git a/src/main/java/codechicken/lib/render/RenderUtils.java b/src/main/java/codechicken/lib/render/RenderUtils.java index 0217c4df..6b26ad8c 100644 --- a/src/main/java/codechicken/lib/render/RenderUtils.java +++ b/src/main/java/codechicken/lib/render/RenderUtils.java @@ -2,14 +2,14 @@ import codechicken.lib.render.buffer.TransformingVertexConsumer; import codechicken.lib.vec.*; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.rendertype.RenderType; +import net.minecraft.client.renderer.rendertype.RenderTypes; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.Material; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; @@ -32,17 +32,7 @@ public class RenderUtils { } } - public static RenderType getFluidRenderType() { - return RenderType.create("ccl:fluid_render", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() - .setShaderState(RenderType.POSITION_COLOR_TEX_LIGHTMAP_SHADER) - .setTextureState(RenderType.BLOCK_SHEET) - .setTransparencyState(RenderType.TRANSLUCENT_TRANSPARENCY) - .setLightmapState(RenderType.LIGHTMAP) - .createCompositeState(false) - ); - } - - public static void renderFluidCuboid(CCRenderState ccrs, Matrix4 mat, RenderType renderType, MultiBufferSource source, FluidStack stack, Cuboid6 bound, double capacity, double res) { + public static void renderFluidCuboid(CCRenderState ccrs, Matrix4 mat, FluidStack stack, Cuboid6 bound, double capacity, double res) { if (stack.isEmpty()) { return; } @@ -54,10 +44,9 @@ public static void renderFluidCuboid(CCRenderState ccrs, Matrix4 mat, RenderType bound.max.y = bound.min.y + (bound.max.y - bound.min.y) * capacity; } IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(type); - Material material = ClientHooks.getBlockMaterial(props.getStillTexture(stack)); - ccrs.bind(renderType, source); + TextureAtlasSprite sprite = Minecraft.getInstance().getAtlasManager().get(ClientHooks.getBlockMaterial(props.getStillTexture(stack))); ccrs.baseColour = props.getTintColor(stack) << 8 | alpha; - makeFluidModel(bound, material.sprite(), res).render(ccrs, mat); + makeFluidModel(bound, sprite, res).render(ccrs, mat); } public static CCModel makeFluidModel(Cuboid6 bound, TextureAtlasSprite tex, double res) { @@ -65,6 +54,7 @@ public static CCModel makeFluidModel(Cuboid6 bound, TextureAtlasSprite tex, doub List verts = new ArrayList<>(); makeFluidCuboid(verts, bound, tex, res); model.verts = verts.toArray(new Vertex5[0]); + model.computeNormals(); return model; } @@ -170,16 +160,19 @@ public static void bufferCuboidSolid(VertexConsumer builder, Cuboid6 c, float r, builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); } + @Deprecated public static void bufferHitbox(Matrix4 mat, MultiBufferSource getter, Camera renderInfo, Cuboid6 cuboid) { - Vec3 projectedView = renderInfo.getPosition(); + Vec3 projectedView = renderInfo.position(); bufferHitBox(mat.copy().translate(-projectedView.x, -projectedView.y, -projectedView.z), getter, cuboid); } + @Deprecated public static void bufferHitBox(Matrix4 mat, MultiBufferSource getter, Cuboid6 cuboid) { - VertexConsumer builder = new TransformingVertexConsumer(getter.getBuffer(RenderType.lines()), mat); + VertexConsumer builder = new TransformingVertexConsumer(getter.getBuffer(RenderTypes.lines()), mat); bufferCuboidOutline(builder, cuboid.copy().expand(0.0020000000949949026D), 0.0F, 0.0F, 0.0F, 0.4F); } + @Deprecated public static void bufferCuboidOutline(VertexConsumer builder, Cuboid6 c, float r, float g, float b, float a) { bufferLinePair(builder, c.min.x, c.min.y, c.min.z, c.max.x, c.min.y, c.min.z, r, g, b, a); bufferLinePair(builder, c.max.x, c.min.y, c.min.z, c.max.x, c.min.y, c.max.z, r, g, b, a); @@ -195,22 +188,26 @@ public static void bufferCuboidOutline(VertexConsumer builder, Cuboid6 c, float bufferLinePair(builder, c.min.x, c.min.y, c.max.z, c.min.x, c.max.y, c.max.z, r, g, b, a); } + @Deprecated public static void bufferShapeHitBox(Matrix4 mat, MultiBufferSource buffers, Camera renderInfo, VoxelShape shape) { - Vec3 projectedView = renderInfo.getPosition(); + Vec3 projectedView = renderInfo.position(); bufferShapeHitBox(mat.copy().translate(-projectedView.x, -projectedView.y, -projectedView.z), buffers, shape); } + @Deprecated public static void bufferShapeHitBox(Matrix4 mat, MultiBufferSource buffers, VoxelShape shape) { - VertexConsumer builder = new TransformingVertexConsumer(buffers.getBuffer(RenderType.lines()), mat); + VertexConsumer builder = new TransformingVertexConsumer(buffers.getBuffer(RenderTypes.lines()), mat); bufferShapeOutline(builder, shape, 0.0F, 0.0F, 0.0F, 0.4F); } + @Deprecated public static void bufferShapeOutline(VertexConsumer builder, VoxelShape shape, float r, float g, float b, float a) { shape.forAllEdges((x1, y1, z1, x2, y2, z2) -> { bufferLinePair(builder, x1, y1, z1, x2, y2, z2, r, g, b, a); }); } + @Deprecated private static void bufferLinePair(VertexConsumer builder, double x1, double y1, double z1, double x2, double y2, double z2, float r, float g, float b, float a) { Vector3 v1 = vectors[0].set(x1, y1, z1).subtract(x2, y2, z2); double d = v1.mag(); diff --git a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java b/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java deleted file mode 100644 index b83bcb57..00000000 --- a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java +++ /dev/null @@ -1,152 +0,0 @@ -package codechicken.lib.render.block; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.block.BlockRenderDispatcher; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.material.Fluid; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import net.neoforged.fml.ModList; -import org.embeddedt.embeddium.api.BlockRendererRegistry; -import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Predicate; - -/** - * Registry for {@link ICCBlockRenderer} instances. - *

    - * Created by covers1624 on 8/09/2016. - * - * @see ICCBlockRenderer - */ -@Deprecated(forRemoval = true) // No replacement. -@ScheduledForRemoval (inVersion = "mc 1.21.2+") -public class BlockRenderingRegistry { - - private static boolean initialized = false; - - private static final Map blockRenderers = new HashMap<>(); - private static final Map fluidRenderers = new HashMap<>(); - private static final List globalRenderers = new ArrayList<>(); - - @OnlyIn (Dist.CLIENT) - public static void init() { - if (!initialized) { - Minecraft mc = Minecraft.getInstance(); - BlockRenderDispatcher parentDispatcher = mc.getBlockRenderer(); - mc.blockRenderer = new CCBlockRendererDispatcher(parentDispatcher, mc.getBlockColors()); - initialized = true; - } - - if (ModList.get().isLoaded("embeddium")) { - EmbeddiumSupport.init(); - } - } - - /** - * Register an {@link ICCBlockRenderer} for the given block. - *

    - * Unlike {@link #registerGlobalRenderer}, registering your {@link ICCBlockRenderer} via this method - * is guaranteed to only be tested against the block provided. - * - * @param block The block to register to. - * @param renderer The {@link ICCBlockRenderer}. - * @throws IllegalArgumentException If the same Block is registered twice. - */ - @Deprecated // No replacement. Use a mixin. - public static synchronized void registerRenderer(Block block, ICCBlockRenderer renderer) { - ICCBlockRenderer prev = blockRenderers.get(block); - if (prev != null) { - throw new IllegalArgumentException("Renderer already registered for block. " + BuiltInRegistries.BLOCK.getKey(block)); - } - blockRenderers.put(block, renderer); - } - - /** - * Register an {@link ICCBlockRenderer} for the given fluid. - *

    - * Unlike {@link #registerGlobalRenderer}, registering your {@link ICCBlockRenderer} via this method - * is guaranteed to only be tested against the fluid provided. - * - * @param fluid The fluid to register to. - * @param renderer The {@link ICCBlockRenderer}. - * @throws IllegalArgumentException If the same Fluid is registered twice. - */ - @Deprecated // No replacement. Use a mixin. - public static synchronized void registerRenderer(Fluid fluid, ICCBlockRenderer renderer) { - ICCBlockRenderer prev = fluidRenderers.get(fluid); - if (prev != null) { - throw new IllegalArgumentException("Renderer already registered for fluid. " + BuiltInRegistries.FLUID.getKey(fluid)); - } - fluidRenderers.put(fluid, renderer); - } - - /** - * Register a global {@link ICCBlockRenderer}, capable of overriding the - * rendering of any block in world. - * - * @param renderer The {@link ICCBlockRenderer}. - */ - @Deprecated // No replacement. Use a mixin. - public static synchronized void registerGlobalRenderer(ICCBlockRenderer renderer) { - globalRenderers.add(renderer); - } - - @Nullable - static ICCBlockRenderer findFor(Block block, Predicate pred) { - for (ICCBlockRenderer renderer : globalRenderers) { - if (pred.test(renderer)) { - return renderer; - } - } - - ICCBlockRenderer found = blockRenderers.get(block); - if (found != null && pred.test(found)) return found; - - return null; - } - - @Nullable - static ICCBlockRenderer findFor(Fluid fluid, Predicate pred) { - for (ICCBlockRenderer renderer : globalRenderers) { - if (pred.test(renderer)) { - return renderer; - } - } - - ICCBlockRenderer found = fluidRenderers.get(fluid); - if (found != null && pred.test(found)) return found; - - return null; - } - - private static class EmbeddiumSupport { - - private static final Map ADAPTERS = new ConcurrentHashMap<>(); - private static final ThreadLocal POSE_STACK_CACHE = ThreadLocal.withInitial(PoseStack::new); - - private static BlockRendererRegistry.Renderer adapt(ICCBlockRenderer renderer) { - return ADAPTERS.computeIfAbsent(renderer, e -> (ctx, random, consumer) -> { - e.renderBlock(ctx.state(), ctx.pos(), ctx.world(), POSE_STACK_CACHE.get(), consumer, random, ctx.modelData(), ctx.renderLayer()); - return BlockRendererRegistry.RenderResult.OVERRIDE; - }); - } - - public static void init() { - BlockRendererRegistry.instance().registerRenderPopulator((resultList, ctx) -> { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(ctx.state().getBlock(), e -> e.canHandleBlock(ctx.world(), ctx.pos(), ctx.state(), ctx.renderLayer())); - if (renderer != null) { - resultList.add(adapt(renderer)); - } - }); - } - } -} diff --git a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java deleted file mode 100644 index 051ffe82..00000000 --- a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java +++ /dev/null @@ -1,147 +0,0 @@ -package codechicken.lib.render.block; - -import codechicken.lib.internal.ClientInit; -import codechicken.lib.internal.ExceptionMessageEventHandler; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.CrashReport; -import net.minecraft.CrashReportCategory; -import net.minecraft.ReportedException; -import net.minecraft.client.Minecraft; -import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.BlockRenderDispatcher; -import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.FluidState; -import net.neoforged.neoforge.client.model.data.ModelData; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval; - -import java.util.concurrent.TimeUnit; - -/** - * Created by covers1624 on 8/09/2016. - */ -@Deprecated -@ScheduledForRemoval (inVersion = "mc 1.21.2+") -public class CCBlockRendererDispatcher extends BlockRenderDispatcher { - - private static final Logger logger = LogManager.getLogger(); - - public final BlockRenderDispatcher parentDispatcher; - private static long lastTime; - - public CCBlockRendererDispatcher(BlockRenderDispatcher parent, BlockColors blockColours) { - super(parent.getBlockModelShaper(), parent.blockEntityRenderer, blockColours); - parentDispatcher = parent; - this.modelRenderer = parent.modelRenderer; - this.liquidBlockRenderer = parent.liquidBlockRenderer; - } - - //In world. - @Override - public void renderBatched(BlockState state, BlockPos pos, BlockAndTintGetter level, PoseStack stack, VertexConsumer builder, boolean checkSides, RandomSource rand, ModelData modelData, RenderType renderType) { - try { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(state.getBlock(), e -> e.canHandleBlock(level, pos, state, renderType)); - if (renderer != null) { - renderer.renderBlock(state, pos, level, stack, builder, rand, modelData, renderType); - return; - } - } catch (Throwable t) { - if (ClientInit.catchBlockRenderExceptions) { - handleCaughtException(t, state, pos, level); - return; - } - CrashReport crashreport = CrashReport.forThrowable(t, "Tessellating CCL block in world"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Block being tessellated"); - CrashReportCategory.populateBlockDetails(crashreportcategory, level, pos, state); - throw new ReportedException(crashreport); - } - try { - parentDispatcher.renderBatched(state, pos, level, stack, builder, checkSides, rand, modelData, renderType); - } catch (Throwable t) { - if (ClientInit.catchBlockRenderExceptions) { - handleCaughtException(t, state, pos, level); - return; - } - throw t; - } - } - - //Block Damage - @Override - public void renderBreakingTexture(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack matrixStackIn, VertexConsumer vertexBuilderIn, ModelData data) { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(state.getBlock(), e -> e.canHandleBlock(world, pos, state, null)); - if (renderer != null) { - renderer.renderBreaking(state, pos, world, matrixStackIn, vertexBuilderIn, data); - } else { - parentDispatcher.renderBreakingTexture(state, pos, world, matrixStackIn, vertexBuilderIn, data); - } - } - - //Fluids - @Override - public void renderLiquid(BlockPos pos, BlockAndTintGetter world, VertexConsumer builder, BlockState blockState, FluidState fluidState) { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(fluidState.getType(), e -> e.canHandleFluid(world, pos, blockState, fluidState)); - if (renderer != null) { - renderer.renderFluid(pos, world, builder, blockState, fluidState); - return; - } - parentDispatcher.renderLiquid(pos, world, builder, blockState, fluidState); - } - - //From an entity - @Override - public void renderSingleBlock(BlockState blockStateIn, PoseStack matrixStackIn, MultiBufferSource bufferTypeIn, int combinedLightIn, int combinedOverlayIn, ModelData modelData, RenderType renderType) { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(blockStateIn.getBlock(), e -> e.canHandleEntity(blockStateIn)); - if (renderer != null) { - renderer.renderEntity(blockStateIn, matrixStackIn, bufferTypeIn, combinedLightIn, combinedOverlayIn, modelData, renderType); - } else { - parentDispatcher.renderSingleBlock(blockStateIn, matrixStackIn, bufferTypeIn, combinedLightIn, combinedOverlayIn, modelData, renderType); - } - } - - private static void handleCaughtException(Throwable t, BlockState inState, BlockPos pos, BlockAndTintGetter world) { - Block inBlock = inState.getBlock(); - BlockEntity tile = world.getBlockEntity(pos); - - StringBuilder builder = new StringBuilder("\n CCL has caught an exception whilst rendering a block\n"); - builder.append(" BlockPos: ").append(String.format("x:%s, y:%s, z:%s", pos.getX(), pos.getY(), pos.getZ())).append("\n"); - builder.append(" Block Class: ").append(inBlock.getClass()).append("\n"); - builder.append(" Registry Name: ").append(BuiltInRegistries.BLOCK.getKey(inBlock)).append("\n"); - builder.append(" State: ").append(inState).append("\n"); - builder.append(" Tile at position\n"); - builder.append(" Tile Class: ").append(tile != null ? tile.getClass() : null).append("\n"); - builder.append(" Tile Id: ").append(tile != null ? BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(tile.getType()) : null).append("\n"); - builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata(tile.getLevel().registryAccess()) : null).append("\n"); - builder.append("This functionality can be disabled in the CCL config file.\n"); - if (ClientInit.messagePlayerOnRenderExceptionCaught) { - builder.append("You can also turn off player messages in the CCL config file.\n"); - } - String logMessage = builder.toString(); - String key = ExceptionUtils.getStackTrace(t) + logMessage; - if (ExceptionMessageEventHandler.exceptionMessageCache.add(key)) { - logger.error(logMessage, t); - } - Player player = Minecraft.getInstance().player; - if (ClientInit.messagePlayerOnRenderExceptionCaught && player != null) { - long time = System.nanoTime(); - if (TimeUnit.NANOSECONDS.toSeconds(time - lastTime) > 5) { - lastTime = time; - player.sendSystemMessage(Component.literal("CCL Caught an exception rendering a block. See the log for info.")); - } - } - } - -} diff --git a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java b/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java deleted file mode 100644 index 1ed00fcf..00000000 --- a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java +++ /dev/null @@ -1,151 +0,0 @@ -package codechicken.lib.render.block; - -import codechicken.lib.render.CCRenderState; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.FluidState; -import net.neoforged.neoforge.client.model.data.ModelData; -import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval; -import org.jetbrains.annotations.Nullable; - -/** - * Capable of rendering Blocks and Fluids directly to the chunk buffer. - *

    - * Created by covers1624 on 8/09/2016. - * - * @see BlockRenderingRegistry - * @deprecated Unfortunately, this has become a maintenance and compatability burden. Mods like Sodium - * are in every single modpack, and we can't realistically tell people not to use it. It's possible - * a Neo api may pop up that allows features similar to this API. But I'm not going to hold my breath. - * If someone still requires the functionality that this system provides, they should implement mixins - * themselves, or Sodium/Embeddium compatability. - */ -@Deprecated (forRemoval = true) -@ScheduledForRemoval (inVersion = "mc 1.21.2+") -public interface ICCBlockRenderer { - - //region Block - - /** - * Called to evaluate weather this ICCBlockRenderer will be called for the specified BlockState. - * - * @param world The world. - * @param pos The pos. - * @param blockState The BlockState. - * @param renderType The {@link RenderType}, {@code null} for breaking. - * @return If you wish to render the BlockState. - */ - @Deprecated - boolean canHandleBlock(BlockAndTintGetter world, BlockPos pos, BlockState blockState, @Nullable RenderType renderType); - - /** - * Called to render your block in world. - * You MUST use the provided {@link VertexConsumer}. - * THE BUFFER IS ALREADY DRAWING! - * YOU MAY BE FIRED ON THE CHUNK BATCHING THREAD! - * - * @param state Your state. - * @param pos Position. - * @param world World. - * @param mStack The {@link PoseStack}. - * @param builder The {@link VertexConsumer} to add quads to. - * @param random Position seeded Random for this block position. - * @param data Any ModelData. - * @param renderType The {@link RenderType}, {@code null} for breaking. - */ - @Deprecated - void renderBlock(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack mStack, VertexConsumer builder, RandomSource random, ModelData data, @Nullable RenderType renderType); - - /** - * Called when vanilla is rendering breaking texture over your block. - * Usually just render out your normal quads. - * - * @param state Your state. - * @param pos Position. - * @param world World. - * @param mStack The {@link PoseStack}. - * @param builder The {@link VertexConsumer} to add quads to. - * @param data Any ModelData. - */ - @Deprecated - default void renderBreaking(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack mStack, VertexConsumer builder, ModelData data) { - CCRenderState ccrs = CCRenderState.instance(); - ccrs.overlay = OverlayTexture.NO_OVERLAY; - ccrs.brightness = LevelRenderer.getLightColor(world, state, pos); - mStack.pushPose(); - renderBlock(state, pos, world, mStack, builder, RandomSource.create(), data, null); - mStack.popPose(); - } - //endregion - - //region Rendering from an entity, Minecarts, enderman, etc. - - /** - * Called to evaluate weather this ICCBlockRenderer will be called to handle - * {@link #renderEntity} for the given BlockState. - * - * @param state The state. - * @return If you wish to render this block. - */ - @Deprecated // No replacement. Use a mixin. - default boolean canHandleEntity(BlockState state) { - return false; - } - - /** - * Called for misc entities holding or have blocks as part of their model. - * IronGolems, Enderman, Mooshroom, Minecarts, TNT. - * - * @param state The BlockState to render. - * @param nStack The {@link PoseStack}. - * @param builder The {@link MultiBufferSource} - * @param packedLight The {@link LightTexture} packed coords. - * @param packedOverlay The {@link OverlayTexture} packed coords. - * @param data Any ModelData. - * @param renderType The {@link RenderType} may be {@code null}. - */ - @Deprecated // No replacement. Use a mixin. - default void renderEntity(BlockState state, PoseStack nStack, MultiBufferSource builder, int packedLight, int packedOverlay, ModelData data, @Nullable RenderType renderType) { } - //endregion - - //region Fluids - - /** - * Called to evaluate weather this ICCBlockRenderer will be called for the specified IFluidState. - * - * @param world The world. - * @param pos The pos. - * @param blockState The {@link BlockState} - * @param fluidState The {@link FluidState}. - * @return If you wish to render the {@link FluidState}. - */ - @Deprecated // No replacement. Use a mixin. - default boolean canHandleFluid(BlockAndTintGetter world, BlockPos pos, BlockState blockState, FluidState fluidState) { - return false; - } - - /** - * Called to render your fluid in world. - * You MUST use the provided {@link VertexConsumer}. - * THE BUFFER IS ALREADY DRAWING! - * YOU MAY BE FIRED ON THE CHUNK BATCHING THREAD! - * - * @param pos Position. - * @param world World. - * @param builder The {@link VertexConsumer}. - * @param blockState The {@link BlockState} - * @param fluidState The {@link FluidState} - */ - @Deprecated // No replacement. Use a mixin. - default void renderFluid(BlockPos pos, BlockAndTintGetter world, VertexConsumer builder, BlockState blockState, FluidState fluidState) { } - //endregion -} diff --git a/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java index eb72096b..e07a6b64 100644 --- a/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java @@ -22,4 +22,9 @@ public AlphaOverrideVertexConsumer(VertexConsumer delegate, int alpha) { public VertexConsumer setColor(int r, int g, int b, int a) { return super.setColor(r, g, b, alpha); } + + @Override + public VertexConsumer setColor(int color) { + return super.setColor((color & 0xFFFFFF) | alpha & 0xFF); + } } diff --git a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java index e9118901..c2785cdc 100644 --- a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java +++ b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java @@ -1,13 +1,11 @@ package codechicken.lib.render.buffer; -import codechicken.lib.model.CachedFormat; import codechicken.lib.model.Quad; -import codechicken.lib.util.VectorUtils; -import codechicken.lib.vec.Vector3; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.util.ARGB; import java.util.ArrayList; import java.util.List; @@ -23,46 +21,17 @@ public class BakedQuadVertexBuilder implements VertexConsumer, ISpriteAwareVerte private final VertexFormat.Mode mode; private final Quad current = new Quad(); - private CachedFormat format; private int vertex = -1; public BakedQuadVertexBuilder() { this(VertexFormat.Mode.QUADS); } - public BakedQuadVertexBuilder(VertexFormat format) { - this(format, VertexFormat.Mode.QUADS); - } - - public BakedQuadVertexBuilder(CachedFormat format) { - this(format, VertexFormat.Mode.QUADS); - } - public BakedQuadVertexBuilder(VertexFormat.Mode mode) { - this(CachedFormat.BLOCK, mode); - } - - public BakedQuadVertexBuilder(VertexFormat format, VertexFormat.Mode mode) { - this(CachedFormat.lookup(format), mode); - } - - public BakedQuadVertexBuilder(CachedFormat format, VertexFormat.Mode mode) { if (mode != VertexFormat.Mode.QUADS && mode != VertexFormat.Mode.TRIANGLES) { throw new IllegalArgumentException("Only QUADS or TRIANGLES supported. Got: " + mode); } this.mode = mode; - setFormat(format); - } - - // Provided for interop with other mods that may provide different quad formats. - public void setFormat(VertexFormat format) { - setFormat(CachedFormat.lookup(format)); - } - - // Provided for interop with other mods that may provide different quad formats. - public void setFormat(CachedFormat format) { - this.format = format; - current.reset(format); } public void reset() { @@ -72,65 +41,55 @@ public void reset() { @Override public void sprite(TextureAtlasSprite sprite) { - current.setTexture(sprite); + current.sprite = sprite; } @Override public VertexConsumer addVertex(float x, float y, float z) { - if (!format.hasPosition) return this; - endPrevVertex(); - current.vertices[vertex].vec()[0] = x; - current.vertices[vertex].vec()[1] = y; - current.vertices[vertex].vec()[2] = z; + current.vertices[vertex].vec.set(x, y, z); return this; } @Override - public VertexConsumer setColor(int red, int green, int blue, int alpha) { - if (!format.hasColor) return this; + public VertexConsumer setColor(int color) { + current.vertices[vertex].color = color; + return this; + } - current.vertices[vertex].color()[0] = red / 255F; - current.vertices[vertex].color()[1] = green / 255F; - current.vertices[vertex].color()[2] = blue / 255F; - current.vertices[vertex].color()[3] = alpha / 255F; + @Override + public VertexConsumer setColor(int red, int green, int blue, int alpha) { + setColor(ARGB.color(red, green, blue, alpha)); return this; } @Override public VertexConsumer setUv(float u, float v) { - if (!format.hasUV) return this; + current.vertices[vertex].uv.set(u, v); + return this; + } - current.vertices[vertex].uv()[0] = u; - current.vertices[vertex].uv()[1] = v; + @Override + public VertexConsumer setNormal(float x, float y, float z) { + current.vertices[vertex].normal.set(x, y, z); return this; } @Override public VertexConsumer setUv1(int u, int v) { - if (!format.hasOverlay) return this; - - current.vertices[vertex].overlay()[0] = u / (float) 0xF0; - current.vertices[vertex].overlay()[1] = v / (float) 0xF0; + // Baked quads dont support overlay. return this; } @Override public VertexConsumer setUv2(int u, int v) { - if (!format.hasLightMap) return this; - - current.vertices[vertex].lightmap()[0] = u / (float) 0xF0; - current.vertices[vertex].lightmap()[1] = v / (float) 0xF0; + // Baked quads dont support arbitrary lightmap. return this; } @Override - public VertexConsumer setNormal(float x, float y, float z) { - if (!format.hasNormal) return this; - - current.vertices[vertex].normal()[0] = x; - current.vertices[vertex].normal()[1] = y; - current.vertices[vertex].normal()[2] = z; + public VertexConsumer setLineWidth(float lineWidth) { + // Baked quads dont support line width. return this; } @@ -138,17 +97,14 @@ private void endPrevVertex() { vertex++; if (vertex == mode.primitiveLength) { if (mode == VertexFormat.Mode.TRIANGLES) { - //Quadulate. - for (int e = 0; e < current.format().elementCount; e++) { - System.arraycopy(current.vertices[2].raw[e], 0, current.vertices[3].raw[e], 0, 4); - } + // Quadulate. + current.vertices[3].copyFrom(current.vertices[2]); } if (current.sprite == null) { throw new IllegalStateException("Sprite not set."); } - current.setQuadOrientation(VectorUtils.findSideE(Vector3.fromArray(current.vertices[0].normal()))); + current.calculateOrientation(false); quadList.add(current.bake()); - current.reset(format); vertex = 0; } } diff --git a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java deleted file mode 100644 index 889441b3..00000000 --- a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java +++ /dev/null @@ -1,38 +0,0 @@ -package codechicken.lib.render.buffer; - -import com.mojang.blaze3d.vertex.MeshData; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.covers1624.quack.util.SneakyUtils; -import net.minecraft.client.renderer.RenderType; - -/** - * Created by covers1624 on 25/5/20. - */ -public class DelegateRenderType extends RenderType { - - protected RenderType parent; - - public DelegateRenderType(RenderType parent) { - this(parent, parent.format()); - } - - public DelegateRenderType(RenderType parent, VertexFormat format) { - super(parent.name, format, parent.mode(), parent.bufferSize(), parent.affectsCrumbling(), parent.sortOnUpload, SneakyUtils.none(), SneakyUtils.none()); - this.parent = parent; - } - - @Override - public void draw(MeshData meshData) { - parent.draw(meshData); - } - - @Override - public void setupRenderState() { - parent.setupRenderState(); - } - - @Override - public void clearRenderState() { - parent.clearRenderState(); - } -} diff --git a/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java index 6207311b..a56766fb 100644 --- a/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java @@ -35,6 +35,12 @@ public VertexConsumer setColor(int r, int g, int b, int a) { return this; } + @Override + public VertexConsumer setColor(int color) { + delegate.setColor(color); + return this; + } + @Override public VertexConsumer setUv(float u, float v) { delegate.setUv(u, v); @@ -58,4 +64,10 @@ public VertexConsumer setNormal(float x, float y, float z) { delegate.setNormal(x, y, z); return this; } + + @Override + public VertexConsumer setLineWidth(float lineWidth) { + delegate.setLineWidth(lineWidth); + return this; + } } diff --git a/src/main/java/codechicken/lib/render/buffer/ExtentsConsumer.java b/src/main/java/codechicken/lib/render/buffer/ExtentsConsumer.java new file mode 100644 index 00000000..1c08c080 --- /dev/null +++ b/src/main/java/codechicken/lib/render/buffer/ExtentsConsumer.java @@ -0,0 +1,65 @@ +package codechicken.lib.render.buffer; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +import java.util.function.Consumer; + +/** + * Created by covers1624 on 11/2/25. + */ +public class ExtentsConsumer implements ISpriteAwareVertexConsumer { + + private final Consumer cons; + + public ExtentsConsumer(Consumer cons) { + this.cons = cons; + } + + @Override + public VertexConsumer addVertex(float x, float y, float z) { + cons.accept(new Vector3f(x, y, z)); + return this; + } + + @Override + public VertexConsumer setColor(int red, int green, int blue, int alpha) { + return this; + } + + @Override + public VertexConsumer setColor(int color) { + return this; + } + + @Override + public VertexConsumer setUv(float u, float v) { + return this; + } + + @Override + public VertexConsumer setUv1(int u, int v) { + return this; + } + + @Override + public VertexConsumer setUv2(int u, int v) { + return this; + } + + @Override + public VertexConsumer setNormal(float normalX, float normalY, float normalZ) { + return this; + } + + @Override + public VertexConsumer setLineWidth(float lineWidth) { + return this; + } + + @Override + public void sprite(TextureAtlasSprite sprite) { + } +} diff --git a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java deleted file mode 100644 index 34e6d7d7..00000000 --- a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java +++ /dev/null @@ -1,179 +0,0 @@ -package codechicken.lib.render.buffer; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderStateShard; -import net.minecraft.client.renderer.RenderType; - -import java.util.LinkedList; -import java.util.List; -import java.util.function.BiConsumer; - -import static java.util.Objects.requireNonNull; -import static net.covers1624.quack.util.SneakyUtils.none; - -/** - * A RenderType that is backed by a VertexBufferObject used for Cached rendering. - *

    - * Created by covers1624 on 25/5/20. - */ -public class VBORenderType extends DelegateRenderType implements AutoCloseable { - - private final BiConsumer factory; - private final VertexBuffer vertexBuffer = new VertexBuffer(VertexBuffer.Usage.DYNAMIC); - private final ByteBufferBuilder builder; - private boolean dirty = true; - - /** - * Create a new VBORenderType, delegates render state setup - * to the provided parent, also uses the parents VertexFormat. - * - * @param parent The parent, for state setup and buffer VertexFormat. - * @param factory The Factory used to fill the BufferBuilder with data. - */ - public VBORenderType(RenderType parent, BiConsumer factory) { - super(parent, parent.format()); - this.factory = factory; - builder = new ByteBufferBuilder(bufferSize()); - } - - /** - * Marks this {@link VBORenderType} as needing to be re-built. - */ - public void setDirty() { - dirty = true; - } - - /** - * An extra {@link Runnable} to be applied before draw calls. - * - * @param action The action. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withCallback(Runnable action) { - return new WithCallbacks().withAction(action); - } - - /** - * An extra {@link RenderStateShard} to be applied. - * - * @param shard The {@link RenderStateShard}. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withState(RenderStateShard shard) { - return new WithCallbacks().withState(shard); - } - - /** - * Called to draw a VBORenderType. - * - * @param buffers The buffers instance. - */ - public void draw(MultiBufferSource buffers) { - draw(buffers, this); - } - - private static void draw(MultiBufferSource buffers, RenderType type) { - var cons = buffers.getBuffer(type); - // Add some garbage so a mesh gets generated. - for (int i = 0; i < type.mode().primitiveLength; i++) { - cons.addVertex(0F, 0F, 0F, 0, 0F, 0F, 0, 0, 0F, 0F, 0F); - } - } - - private void render() { - rebuild(); - vertexBuffer.bind(); - vertexBuffer.drawWithShader(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), requireNonNull(RenderSystem.getShader())); - } - - private void rebuild() { - if (!dirty) return; - builder.discard(); - BufferBuilder buffer = new BufferBuilder(builder, mode(), format()); - factory.accept(format(), buffer); - vertexBuffer.bind(); - vertexBuffer.upload(buffer.build()); - builder.clear(); - dirty = false; - } - - @Override - public void draw(MeshData meshData) { - try (meshData) { - setupRenderState(); - render(); - clearRenderState(); - } - } - - @Override - public void close() throws Exception { - vertexBuffer.close(); - } - - public class WithCallbacks extends DelegateRenderType { - - private final List shards = new LinkedList<>(); - - public WithCallbacks() { - super(VBORenderType.this); - } - - /** - * An extra {@link Runnable} to be applied before draw calls. - * - * @param action The action. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withAction(Runnable action) { - return withState(new RenderStateShard("none", none(), none()) { - @Override - public void setupRenderState() { - action.run(); - } - }); - } - - /** - * An extra {@link RenderStateShard} to be applied. - * - * @param shard The {@link RenderStateShard}. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withState(RenderStateShard shard) { - shards.add(shard); - return this; - } - - @Override - public void setupRenderState() { - super.setupRenderState(); - for (RenderStateShard state : shards) { - state.setupRenderState(); - } - } - - @Override - public void draw(MeshData meshData) { - try (meshData) { - setupRenderState(); - render(); - clearRenderState(); - } - } - - @Override - public void clearRenderState() { - for (RenderStateShard state : shards) { - state.clearRenderState(); - } - super.clearRenderState(); - } - - public void draw(MultiBufferSource buffers) { - VBORenderType.draw(buffers, this); - } - } -} diff --git a/src/main/java/codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension.java b/src/main/java/codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension.java new file mode 100644 index 00000000..5d8ac283 --- /dev/null +++ b/src/main/java/codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension.java @@ -0,0 +1,109 @@ +package codechicken.lib.render.extension; + +import codechicken.lib.render.CCRenderState; +import codechicken.lib.vec.Matrix4; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.OrderedSubmitNodeCollector; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.rendertype.RenderType; + +/** + * Created by covers1624 on 11/2/25. + */ +public interface CCOrderedSubmitNodeCollectorExtension { + + private OrderedSubmitNodeCollector self() { + return (OrderedSubmitNodeCollector) this; + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} however using a {@link Matrix4}. + *

    + * The matrix is copied for your invocation and provided to your callback. + * + * @param mat The matrix. + * @param renderType The render type. + * @param renderer Your renderer callback. + */ + default void cc$submitCustomGeometry(Matrix4 mat, RenderType renderType, Mat4CustomGeometryRenderer renderer) { + var matCopy = mat.copy(); + self().submitCustomGeometry(Internal.EMPTY, renderType, (p, consumer) -> renderer.render(matCopy, renderType, consumer)); + } + + /** + * Similar to {@link SubmitNodeCollector.CustomGeometryRenderer} except + * carries a {@link Matrix4} instead of a {@link PoseStack.Pose}. + */ + interface Mat4CustomGeometryRenderer { + + void render(Matrix4 mat, RenderType renderType, VertexConsumer cons); + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} except, additionally + * provides you the {@link RenderType} you requested as a callback parameter. + * + * @param pStack The pose stack. + * @param renderType The render type. + * @param renderer Your renderer callback. + */ + default void cc$submitCustomGeometry(PoseStack pStack, RenderType renderType, CustomGeometryRendererExtended renderer) { + self().submitCustomGeometry(pStack, renderType, (pose, consumer) -> renderer.render(pose, renderType, consumer)); + } + + /** + * Similar to {@link SubmitNodeCollector.CustomGeometryRenderer} except + * additionally carries the {@link RenderType} for convenience. + */ + interface CustomGeometryRendererExtended { + + void render(PoseStack.Pose pose, RenderType renderType, VertexConsumer cons); + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} however, provides + * you a {@link CCRenderState} instance already reset and bound. + * + * @param mat The matrix to capture. + * @param renderType The render type. + * @param renderer Your render callback. + */ + default void cc$submitCCRS(Matrix4 mat, RenderType renderType, CustomGeometryRendererCCRS renderer) { + var matCopy = mat.copy(); + self().submitCustomGeometry(Internal.EMPTY, renderType, (p, consumer) -> { + var ccrs = CCRenderState.instance(); + ccrs.reset(); + ccrs.bind(consumer, renderType.format()); + renderer.render(matCopy, ccrs); + }); + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} however, provides + * you a {@link CCRenderState} instance already reset and bound. + * + * @param pose The pose to capture. + * @param renderType The render type. + * @param renderer Your render callback. + */ + default void cc$submitCCRS(PoseStack pose, RenderType renderType, CustomGeometryRendererCCRS renderer) { + var matCopy = new Matrix4(pose); + self().submitCustomGeometry(Internal.EMPTY, renderType, (p, consumer) -> { + var ccrs = CCRenderState.instance(); + ccrs.reset(); + ccrs.bind(consumer, renderType.format()); + renderer.render(matCopy, ccrs); + }); + } + + interface CustomGeometryRendererCCRS { + + void render(Matrix4 mat, CCRenderState ccrs); + } + + class Internal { + + private static final PoseStack EMPTY = new PoseStack(); + } +} diff --git a/src/main/java/codechicken/lib/internal/network/package-info.java b/src/main/java/codechicken/lib/render/extension/package-info.java similarity index 60% rename from src/main/java/codechicken/lib/internal/network/package-info.java rename to src/main/java/codechicken/lib/render/extension/package-info.java index 788d4aae..558c32d0 100644 --- a/src/main/java/codechicken/lib/internal/network/package-info.java +++ b/src/main/java/codechicken/lib/render/extension/package-info.java @@ -1,4 +1,4 @@ @NonNullApi -package codechicken.lib.internal.network; +package codechicken.lib.render.extension; import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/item/IItemRenderer.java b/src/main/java/codechicken/lib/render/item/IItemRenderer.java deleted file mode 100644 index 112011a2..00000000 --- a/src/main/java/codechicken/lib/render/item/IItemRenderer.java +++ /dev/null @@ -1,43 +0,0 @@ -package codechicken.lib.render.item; - -import codechicken.lib.model.PerspectiveModel; -import codechicken.lib.texture.TextureUtils; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; - -import java.util.Collections; -import java.util.List; - -public interface IItemRenderer extends PerspectiveModel { - - /** - * Called to render your item with complete control. Bypasses all vanilla rendering of your model. - * - * @param stack The {@link ItemStack} being rendered. - * @param ctx The {@link ItemDisplayContext} of where we are rendering. - * @param mStack The {@link PoseStack} to get / add transformations to. - * @param source The {@link MultiBufferSource} to retrieve buffers from. - * @param packedLight The {@link LightTexture} packed coords. - * @param packedOverlay The {@link OverlayTexture} packed coords. - */ - void renderItem(ItemStack stack, ItemDisplayContext ctx, PoseStack mStack, MultiBufferSource source, int packedLight, int packedOverlay); - - //Useless methods for IItemRenderer. - //@formatter:off - @Override default List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { return Collections.emptyList(); } - @Override default boolean isCustomRenderer() { return true; } - @Override default TextureAtlasSprite getParticleIcon() { return TextureUtils.getMissingSprite(); } - @Override default ItemOverrides getOverrides() { return ItemOverrides.EMPTY; } - //@formatter:on -} diff --git a/src/main/java/codechicken/lib/render/item/map/IMapRenderer.java b/src/main/java/codechicken/lib/render/item/map/IMapRenderer.java deleted file mode 100644 index 79706dec..00000000 --- a/src/main/java/codechicken/lib/render/item/map/IMapRenderer.java +++ /dev/null @@ -1,30 +0,0 @@ -package codechicken.lib.render.item.map; - -import net.minecraft.world.item.ItemStack; - -/** - * Used to handle rendering FirstPerson items the same as a map. - *

    - * Created by covers1624 on 15/02/2017. - */ -public interface IMapRenderer { - - /** - * If the IMapRenderer should handle rendering the data from this map. - * - * @param stack The ItemStack to render map data from. - * @param inFrame If the ItemStack is inside an ItemFrame. - * @return Should this IMapRenderer handle with this context. - */ - boolean shouldHandle(ItemStack stack, boolean inFrame); - - /** - * If this is called you are expected to do something. - * This is ONLY called if shouldHandle returns true. - * - * @param stack The ItemStack to render the map data from. - * @param inFrame If the ItemStack is inside an ItemFrame. - */ - void renderMap(ItemStack stack, boolean inFrame); - -} diff --git a/src/main/java/codechicken/lib/render/item/map/MapRenderRegistry.java b/src/main/java/codechicken/lib/render/item/map/MapRenderRegistry.java deleted file mode 100644 index 95df7a33..00000000 --- a/src/main/java/codechicken/lib/render/item/map/MapRenderRegistry.java +++ /dev/null @@ -1,103 +0,0 @@ -package codechicken.lib.render.item.map; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import java.util.IdentityHashMap; - -/** - * Created by covers1624 on 15/02/2017. - */ -public class MapRenderRegistry { - - private static IdentityHashMap mapRenderers = new IdentityHashMap<>(); - - public static boolean shouldHandle(ItemStack stack, boolean inFrame) { - IMapRenderer mapRenderer = mapRenderers.get(stack.getItem()); - if (mapRenderer != null) { - return mapRenderer.shouldHandle(stack, inFrame); - } - return false; - } - - public static void handleRender(ItemStack stack, boolean inFrame) { - IMapRenderer mapRenderer = mapRenderers.get(stack.getItem()); - if (mapRenderer != null) { - mapRenderer.renderMap(stack, inFrame); - } - } - - public static void registerMapRenderer(Item item, IMapRenderer mapRenderer) { - mapRenderers.put(item, mapRenderer); - } - - // @SubscribeEvent - // public void onItemFrameRender(RenderItemInFrameEvent event) { - // if (shouldHandle(event.getItem(), true)) { - // event.setCanceled(true); - // handleRender(event.getItem(), true); - // } - // } - // - // @SubscribeEvent - // public void renderFirstPersonHand(RenderSpecificHandEvent event) { - // ItemStack stack = event.getItemStack(); - // if (!shouldHandle(stack, false)) { - // return; - // } - // event.setCanceled(true); - // Minecraft minecraft = Minecraft.getInstance(); - // FirstPersonRenderer firstPersonRenderer = minecraft.getFirstPersonRenderer(); - // ClientPlayerEntity player = minecraft.player; - // Hand hand = event.getHand(); - // float partialTicks = event.getPartialTicks(); - // float interpPitch = event.getInterpolatedPitch(); - // float swingProgress = event.getSwingProgress(); - // float equipProgress = event.getEquipProgress(); - // - // //Begin reimplementation of vanilla -_- - // boolean flag = hand == Hand.MAIN_HAND; - // HandSide handSide = flag ? player.getPrimaryHand() : player.getPrimaryHand().opposite(); - // - // GlStateManager.pushMatrix(); - // if (flag && firstPersonRenderer.itemStackOffHand.isEmpty()) { - // float f = MathHelper.sqrt(swingProgress); - // float f1 = -0.2F * MathHelper.sin(swingProgress * (float) Math.PI); - // float f2 = -0.4F * MathHelper.sin(f * (float) Math.PI); - // GlStateManager.translatef(0.0F, -f1 / 2.0F, f2); - // float f3 = firstPersonRenderer.getMapAngleFromPitch(interpPitch); - // GlStateManager.translatef(0.0F, 0.04F + equipProgress * -1.2F + f3 * -0.5F, -0.72F); - // GlStateManager.rotatef(f3 * -85.0F, 1.0F, 0.0F, 0.0F); - // firstPersonRenderer.renderArms(); - // float f4 = MathHelper.sin(f * (float) Math.PI); - // GlStateManager.rotatef(f4 * 20.0F, 1.0F, 0.0F, 0.0F); - // GlStateManager.scalef(2.0F, 2.0F, 2.0F); - // handleRender(stack, false); - // } else { - // float f = handSide == HandSide.RIGHT ? 1.0F : -1.0F; - // GlStateManager.translatef(f * 0.125F, -0.125F, 0.0F); - // - // if (!player.isInvisible()) { - // GlStateManager.pushMatrix(); - // GlStateManager.rotatef(f * 10.0F, 0.0F, 0.0F, 1.0F); - // firstPersonRenderer.renderArmFirstPerson(equipProgress, swingProgress, handSide); - // GlStateManager.popMatrix(); - // } - // - // GlStateManager.pushMatrix(); - // GlStateManager.translatef(f * 0.51F, -0.08F + equipProgress * -1.2F, -0.75F); - // float f1 = MathHelper.sqrt(swingProgress); - // float f2 = MathHelper.sin(f1 * (float) Math.PI); - // float f3 = -0.5F * f2; - // float f4 = 0.4F * MathHelper.sin(f1 * ((float) Math.PI * 2F)); - // float f5 = -0.3F * MathHelper.sin(swingProgress * (float) Math.PI); - // GlStateManager.translatef(f * f3, f4 - 0.3F * f2, f5); - // GlStateManager.rotatef(f2 * -45.0F, 1.0F, 0.0F, 0.0F); - // GlStateManager.rotatef(f * f2 * -30.0F, 0.0F, 1.0F, 0.0F); - // handleRender(stack, false); - // GlStateManager.popMatrix(); - // } - // GlStateManager.popMatrix(); - // } - -} diff --git a/src/main/java/codechicken/lib/render/model/MatLib.java b/src/main/java/codechicken/lib/render/model/MatLib.java index 5f11baba..65de8e6d 100644 --- a/src/main/java/codechicken/lib/render/model/MatLib.java +++ b/src/main/java/codechicken/lib/render/model/MatLib.java @@ -1,7 +1,7 @@ package codechicken.lib.render.model; import codechicken.lib.util.ResourceUtils; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.ResourceProvider; import org.jetbrains.annotations.Nullable; @@ -17,7 +17,7 @@ public class MatLib { public final Map materials = new HashMap<>(); - public static MatLib parse(ResourceProvider resourceProvider, ResourceLocation loc) { + public static MatLib parse(ResourceProvider resourceProvider, Identifier loc) { MatLib matLib = new MatLib(); ModelMaterial curr = null; for (String line : ResourceUtils.loadResource(resourceProvider, loc)) { diff --git a/src/main/java/codechicken/lib/render/model/OBJParser.java b/src/main/java/codechicken/lib/render/model/OBJParser.java index 13c57790..bf302860 100644 --- a/src/main/java/codechicken/lib/render/model/OBJParser.java +++ b/src/main/java/codechicken/lib/render/model/OBJParser.java @@ -7,7 +7,7 @@ import codechicken.lib.vec.Vector3; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.ResourceProvider; import org.jetbrains.annotations.Nullable; @@ -18,7 +18,7 @@ */ public class OBJParser { - private final ResourceLocation location; + private final Identifier location; @Nullable private ResourceProvider provider; private VertexFormat.Mode vertexMode = VertexFormat.Mode.TRIANGLES; @@ -29,9 +29,9 @@ public class OBJParser { /** * Create a new instance of an OBJParser for a nice builder-like structure. * - * @param location The {@link ResourceLocation} of the OBJ. + * @param location The {@link Identifier} of the OBJ. */ - public OBJParser(ResourceLocation location) { + public OBJParser(Identifier location) { this.location = location; } @@ -116,13 +116,13 @@ public Map parse() { * Parse an OBJ model into a named map of {@link CCModel}s. * * @param provider The {@link ResourceProvider} to locate assets. - * @param loc The {@link ResourceLocation} of the OBJ model. + * @param loc The {@link Identifier} of the OBJ model. * @param vertexMode The {@link VertexFormat.Mode} to parse the model into. * @param coordSystem The coordinate system transformation to apply during parsing. * @param ignoreMtl If MTL files should be ignored. * @return The parsed models. */ - public static Map parse(ResourceProvider provider, ResourceLocation loc, VertexFormat.Mode vertexMode, @Nullable Transformation coordSystem, boolean ignoreMtl) { + public static Map parse(ResourceProvider provider, Identifier loc, VertexFormat.Mode vertexMode, @Nullable Transformation coordSystem, boolean ignoreMtl) { if (vertexMode != VertexFormat.Mode.QUADS && vertexMode != VertexFormat.Mode.TRIANGLES) throw new IllegalStateException("Only Quads and Triangles are supported."); Map builtModels = new HashMap<>(); @@ -296,9 +296,9 @@ private static double[] parseDoubles(String s, String token) { return values; } - private static ResourceLocation maybeRelative(ResourceLocation other, String resource) { + private static Identifier maybeRelative(Identifier other, String resource) { if (resource.contains(":")) { - return ResourceLocation.parse(resource); + return Identifier.parse(resource); } String path = other.getPath(); int lastSlash = path.lastIndexOf("/"); @@ -307,6 +307,6 @@ private static ResourceLocation maybeRelative(ResourceLocation other, String res } else { path = ""; } - return ResourceLocation.fromNamespaceAndPath(other.getNamespace(), path + "/" + resource); + return Identifier.fromNamespaceAndPath(other.getNamespace(), path + "/" + resource); } } diff --git a/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java b/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java index 1ebc2272..95d13f39 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java +++ b/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java @@ -1,18 +1,16 @@ package codechicken.lib.render.particle; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.particle.ParticleRenderType; -import net.minecraft.client.particle.TextureSheetParticle; +import net.minecraft.client.particle.SingleQuadParticle; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -public class CustomBreakingParticle extends TextureSheetParticle { +public class CustomBreakingParticle extends SingleQuadParticle { private final float uo; private final float vo; public CustomBreakingParticle(ClientLevel world, double x, double y, double z, double dx, double dy, double dz, TextureAtlasSprite icon) { - super(world, x, y, z, dx, dy, dz); - setSprite(icon); + super(world, x, y, z, dx, dy, dz, icon); gravity = 1; rCol = gCol = bCol = 0.6F; quadSize /= 2.0F; @@ -28,8 +26,9 @@ public static CustomBreakingParticle newLandingParticle(ClientLevel world, doubl return particle; } - public ParticleRenderType getRenderType() { - return ParticleRenderType.TERRAIN_SHEET; + @Override + protected Layer getLayer() { + return Layer.TERRAIN; } protected float getU0() { diff --git a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java index 1cb9eba5..1ae1dd3b 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java +++ b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java @@ -1,168 +1,22 @@ package codechicken.lib.render.particle; -import codechicken.lib.internal.network.CCLNetwork; -import codechicken.lib.packet.PacketCustom; -import codechicken.lib.raytracer.VoxelShapeBlockHitResult; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.ParticleEngine; -import net.minecraft.client.renderer.block.BlockModelShaper; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.HitResult; -import net.minecraft.world.phys.Vec3; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import net.neoforged.neoforge.client.model.data.ModelData; -import java.util.ArrayList; import java.util.List; -import java.util.Random; -import java.util.Set; - -import static codechicken.lib.internal.network.CCLNetwork.C_ADD_LANDING_EFFECTS; -import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 21/11/2016. */ public class CustomParticleHandler { - /** - * Call from {@link Block#addLandingEffects} - * Provided the model bound is an instance of IModelParticleProvider, you will have landing particles just handled for you. - * - * @param world The world. - * @param pos The position of the block. - * @param entity The entity. - * @param numParticles The number of particles to spawn. - * @return Always true for this, basically just return the result of this method inside {@link Block#addLandingEffects} - */ - public static boolean handleLandingEffects(ServerLevel world, BlockPos pos, LivingEntity entity, int numParticles) { - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_ADD_LANDING_EFFECTS, entity.level().registryAccess()); - packet.writePos(pos); - packet.writeVector(Vector3.fromEntity(entity)); - packet.writeVarInt(numParticles); - packet.sendToPlayer((ServerPlayer) entity); - return true; - } - - @OnlyIn (Dist.CLIENT) - public static boolean handleRunningEffects(Level world, BlockPos pos, BlockState state, Entity entity) { - //Spoof a raytrace from the feet. - BlockHitResult traceResult = new BlockHitResult(entity.position().add(0, 1, 0), Direction.UP, pos, false); - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); - ParticleEngine particleManager = Minecraft.getInstance().particleEngine; - List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); - TextureAtlasSprite rolledSprite = sprites.get(world.random.nextInt(sprites.size())); - double x = entity.getX() + (world.random.nextFloat() - 0.5D) * entity.getBbWidth(); - double y = entity.getBoundingBox().minY + 0.1D; - double z = entity.getZ() + (world.random.nextFloat() - 0.5D) * entity.getBbWidth(); - particleManager.add(new CustomBreakingParticle((ClientLevel) world, x, y, z, -entity.getDeltaMovement().x * 4.0D, 1.5D, -entity.getDeltaMovement().z * 4.0D, rolledSprite)); - return true; - } - - return false; - } - - /** - * Call from {@link Block#addLandingEffects} - * Provided the model bound is an instance of IModelParticleProvider, you will have landing particles just handled for you. - * Use the default PerspectiveModel implementations in CCL, Hit effects will be polled from your model based on your bounding box hit. - * - * @param state The state. - * @param world The world. - * @param traceResult The trace result. - * @param manager The ParticleManager. - * @return True if particles were added, basically just return the result of this method inside {@link Block#addLandingEffects} - */ - @OnlyIn (Dist.CLIENT) - public static boolean handleHitEffects(BlockState state, Level world, HitResult traceResult, ParticleEngine manager) { - if (traceResult instanceof BlockHitResult hit) { - BlockPos pos = hit.getBlockPos(); - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); - Cuboid6 bounds = new Cuboid6(); - if (hit instanceof VoxelShapeBlockHitResult) { - bounds.set(((VoxelShapeBlockHitResult) hit).shape.bounds()); - } else { - bounds.set(state.getShape(world, pos).bounds()); - } - bounds = bounds.copy().add(pos); - Set hitSprites = ((IModelParticleProvider) model).getHitEffects(hit, state, world, pos, modelData); - List sprites = new ArrayList<>(hitSprites); - addBlockHitEffects(world, bounds, hit.getDirection(), sprites.get(world.random.nextInt(sprites.size())), manager); - return true; - } - } - return false; - } - - /** - * {@link IClientBlockExtensions#addHitEffects} - * Provided the model bound is an instance of IModelParticleProvider, you will have landing particles just handled for you. - * Use the default PerspectiveModel implementations inside CCL, Destroy effects will just be handled for you. - * - * @param world The world. - * @param pos The position of the block. - * @param manager The ParticleManager. - * @return True if particles were added, basically just return the result of this method inside {@link IClientBlockExtensions#addHitEffects} - */ - @OnlyIn (Dist.CLIENT) - public static boolean handleDestroyEffects(Level world, BlockPos pos, BlockState state, ParticleEngine manager) { - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); - Cuboid6 bounds = new Cuboid6(state.getShape(world, pos).bounds()); - addBlockDestroyEffects(world, bounds.add(pos), new ArrayList<>(((IModelParticleProvider) model).getDestroyEffects(state, world, pos, modelData)), manager); - return true; - } - return false; - } - - @OnlyIn (Dist.CLIENT) - public static void addLandingEffects(Level world, BlockPos pos, BlockState state, Vector3 entityPos, int numParticles) { - //Spoof a raytrace from the feet. - BlockHitResult traceResult = new BlockHitResult(new Vec3(entityPos.x, pos.getY() + 1, entityPos.z), Direction.UP, pos, false); - ParticleEngine manager = Minecraft.getInstance().particleEngine; - Random randy = new Random(); - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = requireNonNull(world.getModelDataManager()).getAt(pos); - List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); - - double speed = 0.15000000596046448D; - if (numParticles != 0) { - for (int i = 0; i < numParticles; i++) { - double mX = randy.nextGaussian() * speed; - double mY = randy.nextGaussian() * speed; - double mZ = randy.nextGaussian() * speed; - manager.add(CustomBreakingParticle.newLandingParticle((ClientLevel) world, entityPos.x, entityPos.y, entityPos.z, mX, mY, mZ, sprites.get(randy.nextInt(sprites.size())))); - } - } - } - } - - @OnlyIn (Dist.CLIENT) public static void addBlockHitEffects(Level world, Cuboid6 bounds, Direction side, TextureAtlasSprite icon, ParticleEngine particleManager) { float border = 0.1F; Vector3 diff = bounds.max.copy().subtract(bounds.min).add(-2 * border); @@ -193,7 +47,6 @@ public static void addBlockHitEffects(Level world, Cuboid6 bounds, Direction sid particleManager.add(new CustomBreakingParticle((ClientLevel) world, pos.x, pos.y, pos.z, 0, 0, 0, icon).setPower(0.2F).scale(0.6F)); } - @OnlyIn (Dist.CLIENT) public static void addBlockDestroyEffects(Level world, Cuboid6 bounds, List icons, ParticleEngine particleManager) { Vector3 diff = bounds.max.copy().subtract(bounds.min); Vector3 center = bounds.min.copy().add(bounds.max).multiply(0.5); @@ -210,4 +63,29 @@ public static void addBlockDestroyEffects(Level world, Cuboid6 bounds, List - * Created by covers1624 on 31/10/19. - */ -public interface ICustomParticleBlock extends IBlockExtension { - - @Override - default boolean addLandingEffects(BlockState state1, ServerLevel worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) { - CustomParticleHandler.handleLandingEffects(worldserver, pos, entity, numberOfParticles); - return true; - } - - @Override - default boolean addRunningEffects(BlockState state, Level world, BlockPos pos, Entity entity) { - return world.isClientSide && CustomParticleHandler.handleRunningEffects(world, pos, state, entity); - } - - // TODO IBlockRenderProperties -// @Override -// @OnlyIn (Dist.CLIENT) -// default boolean addHitEffects(BlockState state, World worldObj, RayTraceResult target, ParticleManager manager) { -// return CustomParticleHandler.handleHitEffects(state, worldObj, target, manager); -// } -// -// @Override -// @OnlyIn (Dist.CLIENT) -// default boolean addDestroyEffects(BlockState state, World world, BlockPos pos, ParticleManager manager) { -// return CustomParticleHandler.handleDestroyEffects(world, pos, state, manager); -// } -} diff --git a/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java b/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java deleted file mode 100644 index 482629ca..00000000 --- a/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -package codechicken.lib.render.particle; - -import codechicken.lib.texture.TextureUtils; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.neoforged.neoforge.client.model.data.ModelData; - -import java.util.Set; - -/** - * Created by covers1624 on 12/07/2017. - */ -public interface IModelParticleProvider extends BakedModel { - - @Override - default TextureAtlasSprite getParticleIcon() { - return TextureUtils.getMissingSprite(); - } - - /** - * Used to retrieve the particles to randomly choose from for hit particles. - * - * @param traceResult The trace result. - * @param state The state, getActualState and getExtendedState has been called. - * @param world The world. - * @param pos The pos. - * @return A Set of Textures to use. - */ - Set getHitEffects(BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData); - - /** - * Used to retrieve the destroy particles for the block. - * - * @param state The state, getActualState and getExtendedState has been called. - * @param world The world. - * @param pos The pos. - * @return A Set of Textures to use. - */ - Set getDestroyEffects(BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data); - -} diff --git a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java index 87af24d3..d0b79999 100644 --- a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java +++ b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java @@ -1,6 +1,7 @@ package codechicken.lib.render.pipeline; import codechicken.lib.render.CCRenderState; +import com.mojang.blaze3d.vertex.VertexFormatElement; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -50,11 +51,10 @@ public void rebuild() { unbuild(); - assert renderState.cFmt != null; - if (renderState.cFmt.hasNormal) { + if (renderState.fmt.contains(VertexFormatElement.NORMAL)) { addAttribute(renderState.normalAttrib); } - if (renderState.cFmt.hasColor) { + if (renderState.fmt.contains(VertexFormatElement.COLOR)) { addAttribute(renderState.colourAttrib); } if (renderState.computeLighting && !renderState.hackyReallyDontComputeLighting) { diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java index 23e337a8..dbaf6b9b 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java @@ -3,6 +3,7 @@ import codechicken.lib.colour.ColourRGBA; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.VertexAttribute; +import com.mojang.blaze3d.vertex.VertexFormatElement; import org.jetbrains.annotations.Nullable; /** @@ -20,10 +21,10 @@ public LightingAttribute() { @Override public boolean load(CCRenderState ccrs) { - assert ccrs.cFmt != null; + assert ccrs.fmt != null; assert ccrs.model != null; - if (!ccrs.computeLighting || !ccrs.cFmt.hasColor || !ccrs.model.hasAttribute(attributeKey)) { + if (!ccrs.computeLighting || !ccrs.fmt.contains(VertexFormatElement.COLOR) || !ccrs.model.hasAttribute(attributeKey)) { return false; } diff --git a/src/main/java/codechicken/lib/render/shader/AbstractShaderObject.java b/src/main/java/codechicken/lib/render/shader/AbstractShaderObject.java deleted file mode 100644 index 7f9d3dee..00000000 --- a/src/main/java/codechicken/lib/render/shader/AbstractShaderObject.java +++ /dev/null @@ -1,54 +0,0 @@ -package codechicken.lib.render.shader; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; - -import java.util.Collection; - -/** - * Created by covers1624 on 24/5/20. - */ -public abstract class AbstractShaderObject extends NamedShaderObject { - - protected int shaderId = -1; - protected boolean dirty; - - protected AbstractShaderObject(String name, ShaderType type, Collection uniforms) { - super(name, type, uniforms); - } - - @Override - public boolean isDirty() { - return dirty; - } - - @Override - public void alloc() { - if (dirty || shaderId == -1) { - if (shaderId == -1) { - shaderId = GL20.glCreateShader(getShaderType().getGLCode()); - if (shaderId == 0) { - throw new RuntimeException("Allocation of ShaderObject failed."); - } - } - GL20.glShaderSource(shaderId, getSource()); - GL20.glCompileShader(shaderId); - if (GL20.glGetShaderi(shaderId, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { - throw new RuntimeException("ShaderProgram linkage failure. \n" + GL20.glGetShaderInfoLog(shaderId)); - } - dirty = false; - } - } - - @Override - public int getShaderID() { - return shaderId; - } - - @Override - public void onLink(int programId) { - - } - - protected abstract String getSource(); -} diff --git a/src/main/java/codechicken/lib/render/shader/AssetShaderObject.java b/src/main/java/codechicken/lib/render/shader/AssetShaderObject.java deleted file mode 100644 index ca524460..00000000 --- a/src/main/java/codechicken/lib/render/shader/AssetShaderObject.java +++ /dev/null @@ -1,44 +0,0 @@ -package codechicken.lib.render.shader; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.Objects; - -/** - * Created by covers1624 on 24/5/20. - */ -public class AssetShaderObject extends AbstractShaderObject implements ResourceManagerReloadListener { - - private static final Logger LOGGER = LogManager.getLogger(); - - private final ResourceLocation asset; - @Nullable - private String source; - - public AssetShaderObject(String name, ShaderType type, Collection uniforms, ResourceLocation asset) { - super(name, type, uniforms); - this.asset = Objects.requireNonNull(asset); - } - - @Override - protected String getSource() { - if (source == null) { - source = new GlslProcessor(asset).process().processedSource(); - } - - return source; - } - - @Override - public void onResourceManagerReload(ResourceManager resourceManager) { - source = null; - dirty = true; - } - -} diff --git a/src/main/java/codechicken/lib/render/shader/BinaryShaderObject.java b/src/main/java/codechicken/lib/render/shader/BinaryShaderObject.java deleted file mode 100644 index 390866ea..00000000 --- a/src/main/java/codechicken/lib/render/shader/BinaryShaderObject.java +++ /dev/null @@ -1,111 +0,0 @@ -package codechicken.lib.render.shader; - -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL46; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Collection; -import java.util.function.Consumer; - -/** - * Allows using pre-compiled shader binaries with {@link ShaderProgram}. - *

    - * Created by KitsuneAlex on 18/11/21. - */ -public class BinaryShaderObject extends NamedShaderObject implements ResourceManagerReloadListener { - - private static final Logger LOGGER = LogManager.getLogger(); - - private final ResourceLocation asset; - private final BinaryType binaryType; - private final String entryPoint; - private final ShaderConstantCache constantCache = new ShaderConstantCache(); - private final Consumer specializationCallback; - private boolean dirty = false; - private int shaderId = -1; - - public BinaryShaderObject(String name, ResourceLocation asset, ShaderType type, BinaryType binaryType, String entryPoint, Collection uniforms, Consumer specializationCallback) { - super(name, type, uniforms); - this.asset = asset; - this.binaryType = binaryType; - this.entryPoint = entryPoint; - this.specializationCallback = specializationCallback; - } - - @Override - public boolean isDirty() { - return dirty; - } - - @Override - public void alloc() { - if (dirty || shaderId == -1) { - if (shaderId == -1) { - shaderId = GL20.glCreateShader(getShaderType().getGLCode()); - if (shaderId == 0) { - throw new IllegalStateException("Allocation of ShaderObject failed."); - } - } - - byte[] source = getRawSource(); - ByteBuffer sourceBuffer = BufferUtils.createByteBuffer(source.length).order(ByteOrder.nativeOrder()); - sourceBuffer.put(source); - sourceBuffer.flip(); - GL46.glShaderBinary(new int[] { shaderId }, binaryType.getGLCode(), sourceBuffer); - - specializationCallback.accept(constantCache); - GL46.glSpecializeShader(shaderId, entryPoint, constantCache.getIndices(), constantCache.getValues()); - - if (GL20.glGetShaderi(shaderId, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { - throw new RuntimeException("ShaderProgram linkage failure. \n" + GL20.glGetShaderInfoLog(shaderId)); - } - - dirty = false; - } - } - - @Override - public int getShaderID() { - return shaderId; - } - - @Override - public void onLink(int programId) { - } - - @Override - public void onResourceManagerReload(ResourceManager resourceManager) { - dirty = true; - } - - private byte[] getRawSource() { - try { - Resource resource = Minecraft.getInstance().getResourceManager().getResourceOrThrow(asset); - try (InputStream istream = resource.open()) { - ByteArrayOutputStream ostream = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int read; - while ((read = istream.read(buffer)) != -1) { - ostream.write(buffer, 0, read); - } - return ostream.toByteArray(); - } - } catch (Throwable t) { - LOGGER.error("Failed to read shader asset.", t); - return new byte[0]; - } - } - -} diff --git a/src/main/java/codechicken/lib/render/shader/BinaryType.java b/src/main/java/codechicken/lib/render/shader/BinaryType.java deleted file mode 100644 index 86ccb071..00000000 --- a/src/main/java/codechicken/lib/render/shader/BinaryType.java +++ /dev/null @@ -1,22 +0,0 @@ -package codechicken.lib.render.shader; - -import org.lwjgl.opengl.GL46; - -/** - * All currently supported shader binary types. - *

    - * Created by KitsuneAlex on 19/11/21. - */ -public enum BinaryType { - SPIR_V(GL46.GL_SHADER_BINARY_FORMAT_SPIR_V); - - private final int glCode; - - BinaryType(int glCode) { - this.glCode = glCode; - } - - public int getGLCode() { - return glCode; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java b/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java deleted file mode 100644 index bbcbb7e8..00000000 --- a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java +++ /dev/null @@ -1,201 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.render.shader.GlslProcessor.ProcessedShader; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.shaders.Program; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.Util; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.ChainedJsonException; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.minecraft.util.GsonHelper; -import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; - -import java.io.IOException; -import java.util.*; - -/** - * A Slightly extended ShaderInstance supporting: - * - Better Uniform caching. - * - All OpenGL Uniform types. - * - Global Uniform callbacks. - * - Better import/includes in shaders. - *

    - * Created by covers1624 on 8/4/22. - */ -public class CCShaderInstance extends ShaderInstance { - - private final List applyCallbacks = new LinkedList<>(); - - protected CCShaderInstance(ResourceProvider resourceProvider, ResourceLocation loc, VertexFormat format) throws IOException { - super(resourceProvider, loc, format); - } - - public static CCShaderInstance create(ResourceProvider resourceProvider, ResourceLocation loc, VertexFormat format) { - try { - return new CCShaderInstance(resourceProvider, loc, format); - } catch (IOException ex) { - throw new RuntimeException("Failed to initialize shader.", ex); - } - } - - /** - * Add a callback for when this {@link CCShaderInstance} is applied. - *

    - * Use this for global uniforms, or whatever else. - * - * @param callback The callback. - */ - public void onApply(Runnable callback) { - applyCallbacks.add(callback); - } - - @Override - public void apply() { - for (Runnable callback : applyCallbacks) { - callback.run(); - } - super.apply(); - } - - @Nullable - @Override - public CCUniform getUniform(String name) { - return (CCUniform) super.getUniform(name); - } - - @Override - protected void parseUniformNode(JsonElement json) throws ChainedJsonException { - JsonObject obj = GsonHelper.convertToJsonObject(json, "uniform"); - String name = GsonHelper.getAsString(obj, "name"); - String typeStr = GsonHelper.getAsString(obj, "type"); - UniformType type = UniformType.parse(typeStr); - if (type == null) { - throw new ChainedJsonException("Invalid type '%s'. See UniformType enum. All vanilla types supported.".formatted(typeStr)); - } - - int count = GsonHelper.getAsInt(obj, "count"); - // Hack for vanilla compat. Vanilla specifies 'float, count 4' for vec4, we need ot to be a vec4 - switch (type) { - case FLOAT -> { - switch(count) { - case 2 -> type = UniformType.VEC2; - case 3 -> type = UniformType.VEC3; - case 4 -> type = UniformType.VEC4; - } - } - case INT -> { - switch(count) { - case 2 -> type = UniformType.I_VEC2; - case 3 -> type = UniformType.I_VEC3; - case 4 -> type = UniformType.I_VEC4; - } - } - case U_INT -> { - switch(count) { - case 2 -> type = UniformType.U_VEC2; - case 3 -> type = UniformType.U_VEC3; - case 4 -> type = UniformType.U_VEC4; - } - } - } - CCUniform uniform = CCUniform.makeUniform(name, type, count, this); - - JsonArray jsonValues = GsonHelper.getAsJsonArray(obj, "values"); - if (jsonValues.size() != count && jsonValues.size() > 1) { - throw new ChainedJsonException("Invalid amount of values specified (expected " + count + ", found " + jsonValues.size() + ")"); - } - switch (type.getCarrier()) { - case INT, U_INT -> uniform.glUniformI(parseInts(count, jsonValues)); - case FLOAT, MATRIX -> uniform.glUniformF(false, parseFloats(count, jsonValues)); - case DOUBLE, D_MATRIX -> uniform.glUniformD(false, parseDoubles(count, jsonValues)); - } - uniforms.add(uniform); - } - - public Program compileProgram(ResourceProvider resourceProvider, Program.Type programType, ResourceLocation loc) throws IOException { - ResourceLocation adjustedLoc = ResourceLocation.fromNamespaceAndPath(loc.getNamespace(), "shaders/core/" + loc.getPath() + programType.getExtension()); - String cacheString = "ccl__" + adjustedLoc; - Program program = programType.getPrograms().get(cacheString); - if (program != null) return program; - - ProcessedShader processedShader = new GlslProcessor(resourceProvider, adjustedLoc).process(); - - int id = GL20.glCreateShader(programType.getGlType()); - GlStateManager.glShaderSource(id, List.of(processedShader.processedSource())); - GL20.glCompileShader(id); - if (GL20.glGetShaderi(id, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { - String s1 = GL20.glGetShaderInfoLog(id); - throw new IOException("Couldn't compile " + programType.getName() + " program (" + processedShader.sourceName() + ", " + adjustedLoc + ") : " + s1); - } - program = new Program(programType, id, cacheString); - programType.getPrograms().put(cacheString, program); - return program; - } - - private static float[] parseFloats(int count, JsonArray jsonValues) throws ChainedJsonException { - int i = 0; - float[] values = new float[Math.max(count, 16)]; - for (JsonElement jsonValue : jsonValues) { - try { - values[i++] = GsonHelper.convertToFloat(jsonValue, "value"); - } catch (Exception ex) { - ChainedJsonException chainedjsonexception = ChainedJsonException.forException(ex); - chainedjsonexception.prependJsonKey("values[" + i + "]"); - throw chainedjsonexception; - } - } - - // If only one value is specified, copy to all in array. - if (count > 1 && jsonValues.size() == 1) { - Arrays.fill(values, 1, values.length, values[0]); - } - return Arrays.copyOfRange(values, 0, count); - } - - private static int[] parseInts(int count, JsonArray jsonValues) throws ChainedJsonException { - int i = 0; - int[] values = new int[Math.max(count, 16)]; - for (JsonElement jsonValue : jsonValues) { - try { - values[i++] = GsonHelper.convertToInt(jsonValue, "value"); - } catch (Exception ex) { - ChainedJsonException chainedjsonexception = ChainedJsonException.forException(ex); - chainedjsonexception.prependJsonKey("values[" + i + "]"); - throw chainedjsonexception; - } - } - - // If only one value is specified, copy to all in array. - if (count > 1 && jsonValues.size() == 1) { - Arrays.fill(values, 1, values.length, values[0]); - } - return Arrays.copyOfRange(values, 0, count); - } - - private static double[] parseDoubles(int count, JsonArray jsonValues) throws ChainedJsonException { - int i = 0; - double[] values = new double[Math.max(count, 16)]; - for (JsonElement jsonValue : jsonValues) { - try { - values[i++] = GsonHelper.convertToDouble(jsonValue, "value"); - } catch (Exception ex) { - ChainedJsonException chainedjsonexception = ChainedJsonException.forException(ex); - chainedjsonexception.prependJsonKey("values[" + i + "]"); - throw chainedjsonexception; - } - } - - // If only one value is specified, copy to all in array. - if (count > 1 && jsonValues.size() == 1) { - Arrays.fill(values, 1, values.length, values[0]); - } - return Arrays.copyOfRange(values, 0, count); - } -} diff --git a/src/main/java/codechicken/lib/render/shader/CCUniform.java b/src/main/java/codechicken/lib/render/shader/CCUniform.java deleted file mode 100644 index 7ae99a96..00000000 --- a/src/main/java/codechicken/lib/render/shader/CCUniform.java +++ /dev/null @@ -1,287 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.render.shader.UniformType.Carrier; -import com.mojang.blaze3d.shaders.Shader; -import com.mojang.blaze3d.shaders.Uniform; -import org.apache.commons.lang3.NotImplementedException; -import org.jetbrains.annotations.Nullable; -import org.joml.Matrix3f; -import org.joml.Matrix4f; -import org.joml.Vector3f; -import org.joml.Vector4f; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL21; -import org.lwjgl.opengl.GL30; -import org.lwjgl.opengl.GL40; -import org.lwjgl.system.MemoryUtil; - -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.util.Arrays; - -/** - * Created by covers1624 on 8/4/22. - */ -public abstract class CCUniform extends Uniform implements ICCUniform { - - protected final UniformType type; - - @SuppressWarnings ("ConstantConditions") - protected CCUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type.getVanillaType(), count, parent); - this.type = type; - if (intValues != null) { - MemoryUtil.memFree(intValues); - intValues = null; - } - if (floatValues != null) { - MemoryUtil.memFree(floatValues); - floatValues = null; - } - } - - static CCUniform makeUniform(String name, UniformType type, int count, @Nullable Shader parent) { - if (count % type.getSize() != 0) throw new IllegalArgumentException("Expected count to be a multiple of the uniform type size: " + type.getSize()); - return switch (type.getCarrier()) { - case INT, U_INT -> new IntUniform(name, type, count, parent); - case FLOAT, MATRIX -> new FloatUniform(name, type, count, parent); - case DOUBLE, D_MATRIX -> new DoubleUniform(name, type, count, parent); - }; - } - - @Override - public IntBuffer getIntBuffer() { - throw new NotImplementedException("TODO"); - } - - @Override - public FloatBuffer getFloatBuffer() { - throw new NotImplementedException("TODO"); - } - - private static abstract class UniformEntry extends CCUniform { - - @Nullable - protected T cache; - protected boolean transpose; - - public UniformEntry(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - } - - // @formatter:off - @Override public void set(float f0) { glUniformF(false, f0); } - @Override public void set(float f0, float f1) { glUniformF(false, f0, f1); } - @Override public void set(int i, float f) { throw new UnsupportedOperationException("Unable to set specific index."); } - @Override public void set(float f0, float f1, float f2) { glUniformF(false, f0, f1, f2); } - @Override public void set(Vector3f vec) { glUniformF(false, vec.x(), vec.y(), vec.z()); } - @Override public void set(float f0, float f1, float f2, float f3) { glUniformF(false, f0, f1, f2, f3); } - @Override public void set(Vector4f vec) { glUniformF(false, vec.x(), vec.y(), vec.z(), vec.w()); } - @Override public void set(int i0) { glUniformI(i0); } - @Override public void set(int i0, int i1) { glUniformI(i0, i1); } - @Override public void set(int i0, int i1, int i2) { glUniformI(i0, i1, i2); } - @Override public void set(int i0, int i1, int i2, int i3) { glUniformI(i0, i1, i2, i3); } - @Override public void set(float[] p_85632_) { glUniformF(false, p_85632_); } - @Override public void setMat2x2(float m00, float m01, float m10, float m11) { glUniformF(true, m00, m01, m10, m11); } - @Override public void setMat2x3(float m00, float m01, float m02, float m10, float m11, float m12) { glUniformF(true, m00, m01, m02, m10, m11, m12); } - @Override public void setMat2x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13) { glUniformF(true, m00, m01, m02, m03, m10, m11, m12, m13); } - @Override public void setMat3x2(float m00, float m01, float m10, float m11, float m20, float m21) { glUniformF(true, m00, m01, m10, m11, m20, m21); } - @Override public void setMat3x3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { glUniformF(true, m00, m01, m02, m10, m11, m12, m20, m21, m22); } - @Override public void setMat3x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23) { glUniformF(true, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23); } - @Override public void setMat4x2(float m00, float m01, float m10, float m11, float m20, float m21, float m30, float m31) { glUniformF(true, m00, m01, m10, m11, m20, m21, m30, m31); } - @Override public void setMat4x3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m23, float m30, float m31, float m32) { glUniformF(true, m00, m01, m02, m10, m11, m12, m20, m21, m23, m30, m31, m32); } - @Override public void setMat4x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { glUniformF(true, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); } - @Override public void set(Matrix4f mat) { glUniformMatrix4f(mat); } - @Override public void set(Matrix3f mat) { glUniformMatrix3f(mat); } - // @formatter:on - - @Override - public void setSafe(float f0, float f1, float f2, float f3) { - assert type.getCarrier() == Carrier.FLOAT; - switch (type.getSize()) { - case 1 -> glUniform1f(f0); - case 2 -> glUniform2f(f0, f1); - case 3 -> glUniform3f(f0, f1, f2); - case 4 -> glUniform4f(f0, f1, f2, f3); - } - throw new IllegalStateException("Unexpected type size: " + type); - } - - @Override - public void setSafe(int i0, int i1, int i2, int i3) { - assert type.getCarrier() == Carrier.INT || type.getCarrier() == Carrier.U_INT; - switch (type.getSize()) { - case 1 -> glUniform1i(i0); - case 2 -> glUniform2i(i0, i1); - case 3 -> glUniform3i(i0, i1, i2); - case 4 -> glUniform4i(i0, i1, i2, i3); - } - throw new IllegalStateException("Unexpected type size: " + type); - } - - @Override - public void glUniformI(int... values) { - if (type.getCarrier() != Carrier.INT && type.getCarrier() != Carrier.U_INT) { - throw new IllegalArgumentException("Uniform '%s' isn't registered with the carrier of INT or U_INT, Got type '%s' with carrier '%s'.".formatted(getName(), type, type.getCarrier())); - } - set((T) values, false); - } - - @Override - public void glUniformF(boolean transpose, float... values) { - if (type.getCarrier() != Carrier.FLOAT && type.getCarrier() != Carrier.MATRIX) { - throw new IllegalArgumentException("Uniform '%s' isn't registered with the carrier of FLOAT or MATRIX, Got type '%s' with carrier '%s'.".formatted(getName(), type, type.getCarrier())); - } - set((T) values, transpose); - } - - @Override - public void glUniformD(boolean transpose, double... values) { - if (type.getCarrier() != Carrier.DOUBLE && type.getCarrier() != Carrier.D_MATRIX) { - throw new IllegalArgumentException("Uniform '%s' isn't registered with the carrier of DOUBLE or D_MATRIX, Got type '%s' with carrier '%s'.".formatted(getName(), type, type.getCarrier())); - } - set((T) values, transpose); - } - - public void set(T values, boolean transpose) { - assert !transpose || type.getCarrier() == Carrier.MATRIX || type.getCarrier() == Carrier.D_MATRIX; - - if (len(values) != getCount()) { - throw new IllegalArgumentException("Invalid size for uniform '%s', Expected: '%s', Got: '%s'.".formatted(getName(), getCount(), len(values))); - } - - if (!equals(cache, values) || this.transpose != transpose) { - cache = values; - this.transpose = transpose; - dirty = true; - } - } - - @Override - public void upload() { - if (!dirty) return; - - flush(); - dirty = false; - } - - public abstract void flush(); - - public abstract T make(int len); - - public abstract int len(T arr); - - public abstract boolean equals(@Nullable T a, T b); - } - - private static class IntUniform extends UniformEntry { - - public IntUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - assert type.getCarrier() == Carrier.INT || type.getCarrier() == Carrier.U_INT; - } - - @Override - public void flush() { - assert cache != null; - - switch (type) { - case INT -> GL20.glUniform1iv(getLocation(), cache); - case U_INT -> GL30.glUniform1uiv(getLocation(), cache); - case I_VEC2, B_VEC2 -> GL20.glUniform2iv(getLocation(), cache); - case U_VEC2 -> GL30.glUniform2uiv(getLocation(), cache); - case I_VEC3, B_VEC3 -> GL20.glUniform3iv(getLocation(), cache); - case U_VEC3 -> GL30.glUniform3uiv(getLocation(), cache); - case I_VEC4, B_VEC4 -> GL20.glUniform4iv(getLocation(), cache); - case U_VEC4 -> GL30.glUniform4uiv(getLocation(), cache); - default -> throw new IllegalStateException("Unhandled uniform type for IntUniform: " + type); - } - } - - //@formatter:off - @Override public int[] make(int len) { return new int[len]; } - @Override public int len(int[] cache) { return cache.length; } - @Override public boolean equals(int @Nullable [] a, int[] b) { return Arrays.equals(a, b); } - //@formatter:on - } - - private static class FloatUniform extends UniformEntry { - - public FloatUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - assert type.getCarrier() == Carrier.FLOAT || type.getCarrier() == Carrier.MATRIX; - } - - @Override - public void flush() { - assert cache != null; - - switch (type) { - case FLOAT -> GL20.glUniform1fv(getLocation(), cache); - case VEC2 -> GL20.glUniform2fv(getLocation(), cache); - case VEC3 -> GL20.glUniform3fv(getLocation(), cache); - case VEC4 -> GL20.glUniform4fv(getLocation(), cache); - - case MAT2 -> GL20.glUniformMatrix2fv (getLocation(), transpose, cache); - case MAT2x3 -> GL21.glUniformMatrix2x3fv(getLocation(), transpose, cache); - case MAT2x4 -> GL21.glUniformMatrix2x4fv(getLocation(), transpose, cache); - - case MAT3 -> GL20.glUniformMatrix3fv (getLocation(), transpose, cache); - case MAT3x2 -> GL21.glUniformMatrix3x2fv(getLocation(), transpose, cache); - case MAT3x4 -> GL21.glUniformMatrix3x4fv(getLocation(), transpose, cache); - - case MAT4 -> GL20.glUniformMatrix4fv (getLocation(), transpose, cache); - case MAT4x2 -> GL21.glUniformMatrix4x2fv(getLocation(), transpose, cache); - case MAT4x3 -> GL21.glUniformMatrix4x3fv(getLocation(), transpose, cache); - - default -> throw new IllegalStateException("Unhandled uniform type for FloatUniform: " + type); - } - } - - //@formatter:off - @Override public float[] make(int len) { return new float[len]; } - @Override public int len(float[] cache) { return cache.length; } - @Override public boolean equals(float @Nullable [] a, float[] b) { return Arrays.equals(a, b); } - //@formatter:on - } - - private static class DoubleUniform extends UniformEntry { - - public DoubleUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - assert type.getCarrier() == Carrier.DOUBLE || type.getCarrier() == Carrier.D_MATRIX; - } - - @Override - public void flush() { - assert cache != null; - - switch (type) { - case DOUBLE -> GL40.glUniform1dv(getLocation(), cache); - case D_VEC2 -> GL40.glUniform2dv(getLocation(), cache); - case D_VEC3 -> GL40.glUniform3dv(getLocation(), cache); - case D_VEC4 -> GL40.glUniform4dv(getLocation(), cache); - - case D_MAT2 -> GL40.glUniformMatrix2dv (getLocation(), transpose, cache); - case D_MAT2x3 -> GL40.glUniformMatrix2x3dv(getLocation(), transpose, cache); - case D_MAT2x4 -> GL40.glUniformMatrix2x4dv(getLocation(), transpose, cache); - - case D_MAT3 -> GL40.glUniformMatrix3dv (getLocation(), transpose, cache); - case D_MAT3x2 -> GL40.glUniformMatrix3x2dv(getLocation(), transpose, cache); - case D_MAT3x4 -> GL40.glUniformMatrix3x4dv(getLocation(), transpose, cache); - - case D_MAT4 -> GL40.glUniformMatrix4dv (getLocation(), transpose, cache); - case D_MAT4x2 -> GL40.glUniformMatrix4x2dv(getLocation(), transpose, cache); - case D_MAT4x3 -> GL40.glUniformMatrix4x3dv(getLocation(), transpose, cache); - - default -> throw new IllegalStateException("Unhandled uniform type for DoubleUniform: " + type); - } - } - - //@formatter:off - @Override public double[] make(int len) { return new double[len]; } - @Override public int len(double[] cache) { return cache.length; } - @Override public boolean equals(double @Nullable [] a, double[] b) { return Arrays.equals(a, b); } - //@formatter:on - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ConstantCache.java b/src/main/java/codechicken/lib/render/shader/ConstantCache.java deleted file mode 100644 index c78a104d..00000000 --- a/src/main/java/codechicken/lib/render/shader/ConstantCache.java +++ /dev/null @@ -1,17 +0,0 @@ -package codechicken.lib.render.shader; - -/** - * Provides methods to mutate specilization constants - * before the shader is specialized. - *

    - * Created by KitsuneAlex on 19/11/21. - */ -public interface ConstantCache { - - void constant1i(int id, int value); - - void constant1f(int id, float value); - - void constant1b(int id, boolean value); - -} diff --git a/src/main/java/codechicken/lib/render/shader/GlslProcessor.java b/src/main/java/codechicken/lib/render/shader/GlslProcessor.java deleted file mode 100644 index b3d30c20..00000000 --- a/src/main/java/codechicken/lib/render/shader/GlslProcessor.java +++ /dev/null @@ -1,197 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.graph.GraphBuilder; -import com.google.common.graph.MutableGraph; -import com.mojang.blaze3d.preprocessor.GlslPreprocessor; -import it.unimi.dsi.fastutil.ints.IntOpenHashSet; -import it.unimi.dsi.fastutil.ints.IntSet; -import net.covers1624.quack.io.IOUtils; -import net.covers1624.quack.sort.TopologicalSort; -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceProvider; -import org.apache.commons.io.FilenameUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.Nullable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Similar to Mojang's own {@link GlslPreprocessor}. - * However, more suited to a modded environment. - *

    - * Created by covers1624 on 22/3/22. - */ -@SuppressWarnings ("ALL") -public class GlslProcessor { - - private static Logger LOGGER = LogManager.getLogger(); - - private static final boolean DEBUG = Boolean.getBoolean("ccl.glsl_processor.debug"); - - private static final Pattern VERSION_PATTERN = Pattern.compile("^#version (.*)$"); - // Matches #moj_import with <> or "" - private static final Pattern IMPORT_PATTERN = Pattern.compile("^#moj_import (?>(?><(.*)>)|(?>\"(.*)\"))$"); - - private final ResourceProvider resourceProvider; - private final ResourceLocation shader; - - private final Map processorLookup = new HashMap<>(); - private final LinkedList newProcessors = new LinkedList<>(); - - public GlslProcessor(ResourceLocation shader) { - this(Minecraft.getInstance().getResourceManager(), shader); - } - - public GlslProcessor(ResourceProvider resourceProvider, ResourceLocation shader) { - this.resourceProvider = resourceProvider; - this.shader = shader; - newProcessors.add(processorLookup.computeIfAbsent(shader, ProcessorEntry::new)); - } - - public ProcessedShader process() { - ProcessorEntry mainEntry = newProcessors.peek(); - String mainVersion = Objects.requireNonNull(mainEntry.version, "Main Shader '" + shader + "' in chain requires #version."); - - if (mainEntry.includes.isEmpty()) { - return new ProcessedShader( - shader, - mainEntry.sourceName, - List.of(shader), - String.join("\n", mainEntry.lines) - ); - } - - MutableGraph graph = GraphBuilder.directed().build(); - while (!newProcessors.isEmpty()) { - ProcessorEntry entry = newProcessors.pop(); - if (entry.version != null && !entry.version.equals(mainVersion)) { - LOGGER.warn("Shader chain {} -> {} version discrepency. Main Shader: {}, Included Shader: {}. This shader may not compile.", shader, entry.shader, mainVersion, entry.version); - } - for (ResourceLocation include : entry.includes) { - graph.putEdge(include, entry.shader); - if (!processorLookup.containsKey(include)) { - newProcessors.add(processorLookup.computeIfAbsent(include, ProcessorEntry::new)); - } - } - } - - List order = TopologicalSort.topologicalSort(graph, null); - List outputLines = new LinkedList<>(); - outputLines.add("#version " + mainVersion); - for (ResourceLocation resourceLocation : order) { - outputLines.add(""); - outputLines.add("/*" + resourceLocation + "*/"); - ProcessorEntry entry = processorLookup.get(resourceLocation); - for (int i = 0; i < entry.lines.size(); i++) { - String line = entry.lines.get(i); - if (entry.linesToComment.contains(i)) { - outputLines.add("/*" + line + "*/"); - } else { - outputLines.add(line); - } - } - } - - if (DEBUG) { - Path out = Paths.get("glsl") - .resolve("assets") - .resolve(shader.getNamespace()) - .resolve(shader.getPath()); - try { - Files.write(IOUtils.makeParents(out), outputLines, StandardCharsets.UTF_8); - } catch (IOException ex) { - LOGGER.error("Failed to write debug glsl output to {}", out); - } - } - - return new ProcessedShader( - shader, - mainEntry.sourceName, - List.copyOf(order), - String.join("\n", outputLines) - ); - } - - public static record ProcessedShader( - ResourceLocation shader, - String sourceName, - List order, - String processedSource) { - } - - private class ProcessorEntry { - - private final ResourceLocation shader; - private final String sourceName; - private final List lines; - private final List includes; - @Nullable - private final String version; - private final IntSet linesToComment; - - private ProcessorEntry(ResourceLocation shader) { - this.shader = shader; - try { - Resource resource = resourceProvider.getResourceOrThrow(shader); - sourceName = resource.sourcePackId(); - try (BufferedReader reader = resource.openAsReader()) { - lines = reader.lines().toList(); - } - } catch (IOException ex) { - throw new RuntimeException("Unable to read asset '" + shader + "'.", ex); - } - linesToComment = new IntOpenHashSet(); - includes = extractIncludes(lines, linesToComment); - version = extractVersion(lines, linesToComment); - } - - private static List extractIncludes(List lines, IntSet linesToComment) { - List imports = new LinkedList<>(); - for (int i = 0; i < lines.size(); i++) { - String line = lines.get(i); - Matcher matcher = IMPORT_PATTERN.matcher(line); - if (matcher.find()) { - linesToComment.add(i); - String match = matcher.group(1); - boolean includeFolder = match != null; - if (!includeFolder) { - match = matcher.group(2); - } - ResourceLocation loc = ResourceLocation.parse(match); - if (includeFolder) { - loc = ResourceLocation.fromNamespaceAndPath(loc.getNamespace(), FilenameUtils.normalize("shaders/include/" + loc.getPath(), true)); - } - imports.add(loc); - } - } - - return List.copyOf(imports); - } - - @Nullable - private static String extractVersion(List lines, IntSet linesToComment) { - for (int i = 0; i < lines.size(); i++) { - String line = lines.get(i); - Matcher matcher = VERSION_PATTERN.matcher(line); - if (matcher.find()) { - linesToComment.add(i); - return matcher.group(1); - } - } - return null; - } - } - -} diff --git a/src/main/java/codechicken/lib/render/shader/ICCUniform.java b/src/main/java/codechicken/lib/render/shader/ICCUniform.java deleted file mode 100644 index 42d5df52..00000000 --- a/src/main/java/codechicken/lib/render/shader/ICCUniform.java +++ /dev/null @@ -1,247 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.vec.Matrix4; -import org.joml.Matrix3f; -import org.joml.Matrix4f; - -/** - * Created by covers1624 on 8/4/22. - */ -public interface ICCUniform { - - // region Int - default void glUniform1i(int i0) { glUniformI(i0); } - - default void glUniform2i(int i0, int i1) { glUniformI(i0, i1); } - - default void glUniform3i(int i0, int i1, int i2) { glUniformI(i0, i1, i2); } - - default void glUniform4i(int i0, int i1, int i2, int i3) { glUniformI(i0, i1, i2, i3); } - // endregion - - // region Unsigned Int - default void glUniform1ui(int i0) { glUniformI(i0); } - - default void glUniform2ui(int i0, int i1) { glUniformI(i0, i1); } - - default void glUniform3ui(int i0, int i1, int i2) { glUniformI(i0, i1, i2); } - - default void glUniform4ui(int i0, int i1, int i2, int i3) { glUniformI(i0, i1, i2, i3); } - // endregion - - // region Float - default void glUniform1f(float f0) { glUniformF(false, f0); } - - default void glUniform2f(float f0, float f1) { glUniformF(false, f0, f1); } - - default void glUniform3f(float f0, float f1, float f2) { glUniformF(false, f0, f1, f2); } - - default void glUniform4f(float f0, float f1, float f2, float f3) { glUniformF(false, f0, f1, f2, f3); } - // endregion - - // region Double - default void glUniform1d(float d0) { glUniformD(false, d0); } - - default void glUniform2d(float d0, float d1) { glUniformD(false, d0, d1); } - - default void glUniform3d(float d0, float d1, float d2) { glUniformD(false, d0, d1, d2); } - - default void glUniform4d(float d0, float d1, float d2, float d3) { glUniformD(false, d0, d1, d2, d3); } - // endregion - - // region Boolean - default void glUniform1b(boolean b0) { glUniformI(b0 ? 1 : 0); } - - default void glUniform2b(boolean b0, boolean b1) { glUniformI(b0 ? 1 : 0, b1 ? 1 : 0); } - - default void glUniform3b(boolean b0, boolean b1, boolean b2) { glUniformI(b0 ? 1 : 0, b1 ? 1 : 0, b2 ? 1 : 0); } - - default void glUniform4b(boolean b0, boolean b1, boolean b2, boolean b3) { glUniformI(b0 ? 1 : 0, b1 ? 1 : 0, b2 ? 1 : 0, b3 ? 1 : 0); } - // endregion - - // region 2x Float Matrix - default void glUniformMatrix2f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix2f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix2x3f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix2x3f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix2x4f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix2x4f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - // endregion - - // region 3x Float Matrix - default void glUniformMatrix3f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix3f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix3f(Matrix3f matrix) { glUniformF(false, toArrayF(matrix)); } - - default void glUniformMatrix3f(boolean transpose, Matrix3f matrix) { glUniformF(transpose, toArrayF(matrix)); } - - default void glUniformMatrix3x2f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix3x2f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix3x4f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix3x4f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - // endregion - - // region 4x Float Matrix - default void glUniformMatrix4f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix4f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix4f(Matrix4 matrix) { glUniformF(false, matrix.toArrayF()); } - - default void glUniformMatrix4f(boolean transpose, Matrix4 matrix) { glUniformF(transpose, matrix.toArrayF()); } - - default void glUniformMatrix4f(Matrix4f matrix) { glUniformF(false, toArrayF(matrix)); } - - default void glUniformMatrix4f(boolean transpose, Matrix4f matrix) { glUniformF(transpose, toArrayF(matrix)); } - - default void glUniformMatrix4x2f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix4x2f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix4x3f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix4x3f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - // endregion - - // region 2x Double matrix - default void glUniformMatrix2d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix2d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix2x3d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix2x3d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix2x4d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix2x4d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - // endregion - - // region 3x Double Matrix - default void glUniformMatrix3d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix3d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix3d(Matrix3f matrix) { glUniformD(false, toArrayD(matrix)); } - - default void glUniformMatrix3d(boolean transpose, Matrix3f matrix) { glUniformD(transpose, toArrayD(matrix)); } - - default void glUniformMatrix3x2d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix3x2d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix3x4d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix3x4d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - // endregion - - // region 4x Double Matrix - default void glUniformMatrix4d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix4d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix4d(Matrix4 matrix) { glUniformD(false, matrix.toArrayD()); } - - default void glUniformMatrix4d(boolean transpose, Matrix4 matrix) { glUniformD(transpose, matrix.toArrayD()); } - - default void glUniformMatrix4d(Matrix4f matrix) { glUniformD(false, toArrayD(matrix)); } - - default void glUniformMatrix4d(boolean transpose, Matrix4f matrix) { glUniformD(transpose, toArrayD(matrix)); } - - default void glUniformMatrix4x2d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix4x2d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix4x3d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix4x3d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - // endregion - - // region Raw - void glUniformI(int... values); - - void glUniformF(boolean transpose, float... values); - - void glUniformD(boolean transpose, double... values); - // endregion - - private static float[] toArrayF(Matrix3f matrix) { - return new float[] { - matrix.m00, - matrix.m01, - matrix.m02, - matrix.m10, - matrix.m11, - matrix.m12, - matrix.m20, - matrix.m21, - matrix.m22, - }; - } - - private static float[] toArrayF(Matrix4f matrix) { - return new float[] { - matrix.m00(), - matrix.m01(), - matrix.m02(), - matrix.m03(), - matrix.m10(), - matrix.m11(), - matrix.m12(), - matrix.m13(), - matrix.m20(), - matrix.m21(), - matrix.m22(), - matrix.m23(), - matrix.m30(), - matrix.m31(), - matrix.m32(), - matrix.m33(), - }; - } - - private static double[] toArrayD(Matrix3f matrix) { - return new double[] { - matrix.m00, - matrix.m01, - matrix.m02, - matrix.m10, - matrix.m11, - matrix.m12, - matrix.m20, - matrix.m21, - matrix.m22, - }; - } - - private static double[] toArrayD(Matrix4f matrix) { - return new double[] { - matrix.m00(), - matrix.m01(), - matrix.m02(), - matrix.m03(), - matrix.m10(), - matrix.m11(), - matrix.m12(), - matrix.m13(), - matrix.m20(), - matrix.m21(), - matrix.m22(), - matrix.m23(), - matrix.m30(), - matrix.m31(), - matrix.m32(), - matrix.m33(), - }; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/NamedShaderObject.java b/src/main/java/codechicken/lib/render/shader/NamedShaderObject.java deleted file mode 100644 index bc409573..00000000 --- a/src/main/java/codechicken/lib/render/shader/NamedShaderObject.java +++ /dev/null @@ -1,37 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.collect.ImmutableList; - -import java.util.Collection; -import java.util.Objects; - -/** - * Created by covers1624 on 9/3/22. - */ -public abstract class NamedShaderObject implements ShaderObject { - - private final String name; - private final ShaderType type; - private final ImmutableList uniforms; - - protected NamedShaderObject(String name, ShaderType type, Collection uniforms) { - this.name = Objects.requireNonNull(name); - this.type = Objects.requireNonNull(type); - this.uniforms = ImmutableList.copyOf(uniforms); - } - - @Override - public String getName() { - return name; - } - - @Override - public ShaderType getShaderType() { - return type; - } - - @Override - public ImmutableList getUniforms() { - return uniforms; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderConstantCache.java b/src/main/java/codechicken/lib/render/shader/ShaderConstantCache.java deleted file mode 100644 index 122b4741..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderConstantCache.java +++ /dev/null @@ -1,49 +0,0 @@ -package codechicken.lib.render.shader; - -import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; - -/** - * Created by KitsuneAlex on 19/11/21. - */ -public class ShaderConstantCache implements ConstantCache { - - private final Int2IntArrayMap values = new Int2IntArrayMap(); - - @Override - public void constant1i(int id, int value) { - if (id < 0) throw new IllegalArgumentException("Constant location ID must be >= 0"); - - int oldValue = values.get(id); - if (oldValue == value) return; - - values.put(id, value); - } - - @Override - public void constant1f(int id, float value) { - if (id < 0) throw new IllegalArgumentException("Constant location ID must be >= 0"); - - float oldValue = Float.intBitsToFloat(values.get(id)); - if (oldValue == value) return; - - values.put(id, Float.floatToIntBits(value)); - } - - @Override - public void constant1b(int id, boolean value) { - if (id < 0) throw new IllegalArgumentException("Constant location ID must be >= 0"); - - boolean oldValue = values.get(id) == 1; - if (oldValue == value) return; - - values.put(id, value ? 1 : 0); - } - - public int[] getIndices() { - return values.keySet().toIntArray(); - } - - public int[] getValues() { - return values.values().toIntArray(); - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderObject.java b/src/main/java/codechicken/lib/render/shader/ShaderObject.java deleted file mode 100644 index 0291ee53..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderObject.java +++ /dev/null @@ -1,104 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.collect.ImmutableList; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL32; -import org.lwjgl.opengl.GL40; -import org.lwjgl.opengl.GL43; - -/** - * Created by covers1624 on 24/5/20. - */ -public interface ShaderObject { - - /** - * A simple identifier for this {@link ShaderObject}, - * used for logging. - * - * @return The name. - */ - String getName(); - - /** - * Gets the {@link ShaderType} for this shader. - * - * @return The {@link ShaderType}. - */ - ShaderType getShaderType(); - - /** - * Gets all {@link UniformPair}s this shader exposes. - * It is expected that a {@link ShaderObject} will not - * dynamically change the uniforms it exposes over its - * lifetime. Doing so is not enforced, but will break - * the Uniform pipeline. - * - * @return The {@link UniformPair}s. - */ - ImmutableList getUniforms(); - - /** - * Checks if this shader is dirty and requires re-compiling. - * - * @return If this shader is dirty. - */ - boolean isDirty(); - - /** - * Allocates and compiles this {@link ShaderObject}. - * Does nothing if the shader is already compiled. - */ - void alloc(); - - /** - * Gets the GL id for this {@link ShaderObject}. - * - * @return The id, -1 of not allocated. - */ - int getShaderID(); - - /** - * Called when this {@link ShaderObject} is linked to a {@link ShaderProgram}. - * - * @param programId The GL id of the program. - */ - void onLink(int programId); - - /** - * Represents a Shader Type. - */ - interface ShaderType { - - /** - * The GL code used in {@link GL20#glCreateShader}. - * - * @return The code. - */ - int getGLCode(); - } - - /** - * Standard ShaderTypes. - */ - enum StandardShaderType implements ShaderType { - //@formatter:off - VERTEX (GL20.GL_VERTEX_SHADER ), - FRAGMENT (GL20.GL_FRAGMENT_SHADER ), - GEOMETRY (GL32.GL_GEOMETRY_SHADER ), - TESS_CONTROL(GL40.GL_TESS_CONTROL_SHADER ), - TESS_EVAL (GL40.GL_TESS_EVALUATION_SHADER), - COMPUTE (GL43.GL_COMPUTE_SHADER ); - //@formatter:on - - private final int glCode; - - StandardShaderType(int glCode) { - this.glCode = glCode; - } - - @Override - public int getGLCode() { - return glCode; - } - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderProgram.java b/src/main/java/codechicken/lib/render/shader/ShaderProgram.java deleted file mode 100644 index 96e278f4..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderProgram.java +++ /dev/null @@ -1,156 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.collect.ImmutableList; -import net.covers1624.quack.collection.FastStream; -import net.covers1624.quack.collection.StreamableIterable; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.server.packs.resources.ReloadableResourceManager; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * A ShaderProgram. - *

    - * As of 1.18.2, you will probably want to use {@link CCShaderInstance} instead as an extension - * to Vanilla's {@link ShaderInstance}. - *

    - * You probably want {@link ShaderProgramBuilder} to construct a ShaderProgram. - * it should be noted, that a ShaderProgram is a {@link ResourceManagerReloadListener}, - * its recommended that you ensure this is registered to {@link ReloadableResourceManager} - * to ensure {@link ShaderObject}s are re loaded properly when Resources are reloaded. - *

    - * Created by covers1624 on 24/5/20. - */ -public class ShaderProgram implements ResourceManagerReloadListener { - - private final List shaders; - private final Map uniforms; - @Nullable - private final Runnable applyCallback; - private int programId = -1; - private boolean bound; - - ShaderProgram(Collection shaders, Collection uniforms, @Nullable Runnable applyCallback) { - this.shaders = ImmutableList.copyOf(shaders); - this.uniforms = FastStream.of(uniforms) - .toImmutableMap(UniformPair::name, e -> CCUniform.makeUniform(e.name(), e.type(), e.type().getSize(), null)); - this.applyCallback = applyCallback; - } - - /** - * Gets all {@link ShaderObject}s that make up this {@link ShaderProgram}. - * - * @return The {@link ShaderObject}s. - */ - public List getShaders() { - return shaders; - } - - /** - * Get all {@link UniformPair}s exposed by this shader. - * - * @return The uniforms. - */ - public Map getUniforms() { - return uniforms; - } - - /** - * Get a {@link CCUniform} from this {@link ShaderProgram}. - * - * @param name The name of the Uniform. - * @return the {@link CCUniform}. - */ - @Nullable - public CCUniform getUniform(String name) { - return uniforms.get(name); - } - - /** - * Gets the GL {@link ShaderProgram} id for this shader. - * Might not be initialized until {@link #use()} is called once. - * - * @return The id, -1 if not initialized. - */ - public int getProgramId() { - return programId; - } - - /** - * Binds this shader for use, Lazily allocates, links - * and compiles all {@link ShaderObject}s. - */ - public void use() { - if (bound) { - throw new IllegalStateException("Already bound."); - } - compile(); - GL20.glUseProgram(programId); - if (applyCallback != null) { - applyCallback.run(); - } - bound = true; - } - - /** - * Forces the ShaderProgram to compile and link. - *

    - * This will happen automatically when calling {@link #use()}, however, - * it may be required to call this ahead of time in some cases. - *

    - * Be sure to only call this when you have GL context. - */ - public void compile() { - if (programId != -1 && shaders.stream().noneMatch(ShaderObject::isDirty)) return; - - for (ShaderObject shaderObject : shaders) { - shaderObject.alloc(); - } - - if (programId == -1) { - programId = GL20.glCreateProgram(); - if (programId == 0) { - throw new IllegalStateException("Allocation of ShaderProgram has failed."); - } - shaders.forEach(shader -> GL20.glAttachShader(programId, shader.getShaderID())); - } - GL20.glLinkProgram(programId); - if (GL20.glGetProgrami(programId, GL20.GL_LINK_STATUS) == GL11.GL_FALSE) { - throw new RuntimeException("ShaderProgram linkage failure. \n" + GL20.glGetProgramInfoLog(programId)); - } - for (ShaderObject shader : shaders) { - shader.onLink(programId); - } - for (CCUniform value : uniforms.values()) { - value.setLocation(GL20.glGetUniformLocation(programId, value.getName())); - } - } - - /** - * Releases this shader. - */ - public void release() { - if (!bound) { - throw new IllegalStateException("Not bound"); - } - bound = false; - GL20.glUseProgram(0); - } - - @Override - public void onResourceManagerReload(ResourceManager resourceManager) { - for (ShaderObject shader : shaders) { - if (shader instanceof ResourceManagerReloadListener) { - ((ResourceManagerReloadListener) shader).onResourceManagerReload(resourceManager); - } - } - compile(); - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderProgramBuilder.java b/src/main/java/codechicken/lib/render/shader/ShaderProgramBuilder.java deleted file mode 100644 index a07593ea..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderProgramBuilder.java +++ /dev/null @@ -1,186 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.render.shader.ShaderObject.ShaderType; -import net.covers1624.quack.util.SneakyUtils; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.function.Consumer; - -import static net.covers1624.quack.util.SneakyUtils.nullCons; - -/** - * Created by covers1624 on 24/5/20. - */ -public class ShaderProgramBuilder { - - private final Map shaders = new HashMap<>(); - private final Map allUniforms = new HashMap<>(); - @Nullable - private Runnable applyCallback; - - private ShaderProgramBuilder() { - } - - public static ShaderProgramBuilder builder() { - return new ShaderProgramBuilder(); - } - - public ShaderProgramBuilder addBinaryShader(String name, Consumer func) { - BinaryShaderObjectBuilder builder = new BinaryShaderObjectBuilder(name); - func.accept(builder); - return addShader(builder.build()); - } - - public ShaderProgramBuilder addShader(String name, Consumer func) { - ShaderObjectBuilder builder = new ShaderObjectBuilder(name); - func.accept(builder); - return addShader(builder.build()); - } - - public ShaderProgramBuilder addShader(ShaderObject shader) { - if (shaders.containsKey(shader.getName())) { - throw new IllegalArgumentException("Duplicate shader with name: " + shader.getName()); - } - shaders.put(shader.getName(), shader); - return this; - } - - public ShaderProgramBuilder whenUsed(Runnable callback) { - if (applyCallback == null) { - applyCallback = callback; - } else { - applyCallback = SneakyUtils.concat(applyCallback, callback); - } - return this; - } - - public ShaderProgram build() { - return new ShaderProgram(shaders.values(), allUniforms.values(), applyCallback); - } - - /** - * Created by covers1624 on 24/5/20. - * Edited by KitsuneAlex on 18/11/21. - */ - public class ShaderObjectBuilder { - - protected final String name; - protected final Map uniforms = new HashMap<>(); - @Nullable - protected ShaderType type; - @Nullable - protected String simpleSource; - @Nullable - protected ResourceLocation assetSource; - - private ShaderObjectBuilder(String name) { - this.name = Objects.requireNonNull(name); - } - - public ShaderObjectBuilder type(ShaderType type) { - if (this.type != null) throw new IllegalArgumentException("Type already set."); - - this.type = Objects.requireNonNull(type); - return this; - } - - public ShaderObjectBuilder source(String source) { - if (simpleSource != null || assetSource != null) throw new IllegalArgumentException("Source already set."); - - simpleSource = Objects.requireNonNull(source); - return this; - } - - public ShaderObjectBuilder source(ResourceLocation asset) { - if (assetSource != null || simpleSource != null) throw new IllegalArgumentException("Source already set."); - - assetSource = Objects.requireNonNull(asset); - return this; - } - - public ShaderObjectBuilder uniform(String name, UniformType type) { - UniformPair uniform = allUniforms.get(name); - if (uniform != null && uniform.type() != type) throw new IllegalArgumentException("Uniform with name '" + name + "' already exists with a different type: " + uniform.type()); - - if (uniform == null) { - uniform = new UniformPair(name, type); - allUniforms.put(name, uniform); - } - uniforms.put(name, uniform); - return this; - } - - protected ShaderObject build() { - if (type == null) throw new IllegalStateException("Type not set."); - if (simpleSource == null && assetSource == null) throw new IllegalStateException("SimpleSource or AssetSource not set."); - if (simpleSource != null) return new SimpleShaderObject(name, type, uniforms.values(), simpleSource); - - return new AssetShaderObject(name, type, uniforms.values(), assetSource); - } - } - - /** - * Created by KitsuneAlex on 18/11/21. - */ - public class BinaryShaderObjectBuilder extends ShaderObjectBuilder { - - @Nullable - private BinaryType binaryType; - @Nullable - private String entryPoint; - private Consumer specializationCallback = nullCons(); - - private BinaryShaderObjectBuilder(String name) { - super(name); - } - - @Override - public BinaryShaderObjectBuilder source(String source) { - throw new IllegalStateException("Binary shaders don't have string source."); - } - - @Override - public BinaryShaderObjectBuilder source(ResourceLocation asset) { - return (BinaryShaderObjectBuilder) super.source(asset); - } - - @Override - public BinaryShaderObjectBuilder uniform(String name, UniformType type) { - return (BinaryShaderObjectBuilder) super.uniform(name, type); - } - - public BinaryShaderObjectBuilder binaryType(BinaryType binaryType) { - if (this.binaryType != null) throw new IllegalStateException("Binary type already set."); - - this.binaryType = binaryType; - return this; - } - - public BinaryShaderObjectBuilder entryPoint(String entryPoint) { - if (this.entryPoint != null) throw new IllegalStateException("Entry point already set."); - - this.entryPoint = entryPoint; - return this; - } - - public BinaryShaderObjectBuilder whenSpecialized(Consumer specializationCallback) { - this.specializationCallback = specializationCallback; - return this; - } - - @Override - protected ShaderObject build() { - if (type == null) throw new IllegalStateException("Type not set."); - if (assetSource == null) throw new IllegalStateException("AssetSource not set."); - if (binaryType == null) throw new IllegalStateException("Binary type not set"); - if (entryPoint == null || entryPoint.isEmpty()) throw new IllegalStateException("Entry point not set."); - - return new BinaryShaderObject(name, assetSource, type, binaryType, entryPoint, allUniforms.values(), specializationCallback); - } - - } -} diff --git a/src/main/java/codechicken/lib/render/shader/SimpleShaderObject.java b/src/main/java/codechicken/lib/render/shader/SimpleShaderObject.java deleted file mode 100644 index fe2cef0e..00000000 --- a/src/main/java/codechicken/lib/render/shader/SimpleShaderObject.java +++ /dev/null @@ -1,21 +0,0 @@ -package codechicken.lib.render.shader; - -import java.util.Collection; - -/** - * Created by covers1624 on 24/5/20. - */ -public class SimpleShaderObject extends AbstractShaderObject { - - private final String source; - - protected SimpleShaderObject(String name, ShaderType type, Collection uniforms, String source) { - super(name, type, uniforms); - this.source = source; - } - - @Override - protected String getSource() { - return source; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/UniformPair.java b/src/main/java/codechicken/lib/render/shader/UniformPair.java deleted file mode 100644 index 8b1c1e5f..00000000 --- a/src/main/java/codechicken/lib/render/shader/UniformPair.java +++ /dev/null @@ -1,7 +0,0 @@ -package codechicken.lib.render.shader; - -/** - * Created by covers1624 on 24/5/20. - */ -public record UniformPair(String name, UniformType type) { -} diff --git a/src/main/java/codechicken/lib/render/shader/UniformType.java b/src/main/java/codechicken/lib/render/shader/UniformType.java deleted file mode 100644 index ef5bf0bb..00000000 --- a/src/main/java/codechicken/lib/render/shader/UniformType.java +++ /dev/null @@ -1,124 +0,0 @@ -package codechicken.lib.render.shader; - -import com.mojang.blaze3d.shaders.Uniform; -import org.jetbrains.annotations.Nullable; - -import java.util.Locale; - -/** - * Created by covers1624 on 24/5/20. - */ -public enum UniformType { - //@formatter:off - INT (Carrier.INT, 1), - U_INT (Carrier.U_INT, 1), - FLOAT (Carrier.FLOAT, 1), - - VEC2 (Carrier.FLOAT, 2), - I_VEC2 (Carrier.INT, 2), - U_VEC2 (Carrier.U_INT, 2), - B_VEC2 (Carrier.INT, 2), - - VEC3 (Carrier.FLOAT, 3), - I_VEC3 (Carrier.INT, 3), - U_VEC3 (Carrier.U_INT, 3), - B_VEC3 (Carrier.INT, 3), - - VEC4 (Carrier.FLOAT, 4), - I_VEC4 (Carrier.INT, 4), - U_VEC4 (Carrier.U_INT, 4), - B_VEC4 (Carrier.INT, 4), - - MAT2 (Carrier.MATRIX, 2 * 2), - MAT2x3 (Carrier.MATRIX, 2 * 3), - MAT2x4 (Carrier.MATRIX, 2 * 4), - - MAT3 (Carrier.MATRIX, 3 * 3), - MAT3x2 (Carrier.MATRIX, 3 * 2), - MAT3x4 (Carrier.MATRIX, 3 * 4), - - MAT4 (Carrier.MATRIX, 4 * 4), - MAT4x2 (Carrier.MATRIX, 4 * 2), - MAT4x3 (Carrier.MATRIX, 4 * 3), - - DOUBLE (Carrier.DOUBLE, 1), - D_VEC2 (Carrier.DOUBLE, 2), - D_VEC3 (Carrier.DOUBLE, 3), - D_VEC4 (Carrier.DOUBLE, 4), - - D_MAT2 (Carrier.D_MATRIX, 2 * 2), - D_MAT2x3(Carrier.D_MATRIX, 2 * 3), - D_MAT2x4(Carrier.D_MATRIX, 2 * 4), - - D_MAT3 (Carrier.D_MATRIX, 3 * 3), - D_MAT3x2(Carrier.D_MATRIX, 3 * 2), - D_MAT3x4(Carrier.D_MATRIX, 3 * 4), - - D_MAT4 (Carrier.D_MATRIX, 4 * 4), - D_MAT4x2(Carrier.D_MATRIX, 4 * 2), - D_MAT4x3(Carrier.D_MATRIX, 4 * 3); - //@formatter:on - - public static final UniformType[] VALUES = values(); - - private final Carrier carrier; - private final int size; - - UniformType(Carrier carrier, int size) { - this.carrier = carrier; - this.size = size; - } - - public Carrier getCarrier() { - return carrier; - } - - public int getSize() { - return size; - } - - public int getVanillaType() { - return switch (this) { - case INT, U_INT -> Uniform.UT_INT1; - case FLOAT -> Uniform.UT_FLOAT1; - case VEC2 -> Uniform.UT_FLOAT2; - case I_VEC2, U_VEC2, B_VEC2 -> Uniform.UT_INT2; - case VEC3 -> Uniform.UT_FLOAT3; - case I_VEC3, U_VEC3, B_VEC3 -> Uniform.UT_INT3; - case VEC4 -> Uniform.UT_FLOAT4; - case I_VEC4, U_VEC4, B_VEC4 -> Uniform.UT_INT4; - case MAT2 -> Uniform.UT_MAT2; - case MAT3 -> Uniform.UT_MAT3; - case MAT4 -> Uniform.UT_MAT4; - default -> -1; - }; - } - - @Nullable - public static UniformType parse(String s) { - s = s.toLowerCase(Locale.ROOT); - - // Handle vanilla Matrix names - switch (s) { - case "matrix2x2" -> { return MAT2; } - case "matrix3x3" -> { return MAT3; } - case "matrix4x4" -> { return MAT4; } - } - for (UniformType value : VALUES) { - String n = value.name().toLowerCase(Locale.ROOT); - if (n.equals(s)) { - return value; - } - } - return null; - } - - public enum Carrier { - INT, - U_INT, - FLOAT, - DOUBLE, - MATRIX, - D_MATRIX - } -} diff --git a/src/main/java/codechicken/lib/render/shader/package-info.java b/src/main/java/codechicken/lib/render/shader/package-info.java deleted file mode 100644 index 4dec7fc8..00000000 --- a/src/main/java/codechicken/lib/render/shader/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@NonNullApi -package codechicken.lib.render.shader; - -import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/texture/TextureUtils.java b/src/main/java/codechicken/lib/texture/TextureUtils.java index 079abcb7..ea99a5e0 100644 --- a/src/main/java/codechicken/lib/texture/TextureUtils.java +++ b/src/main/java/codechicken/lib/texture/TextureUtils.java @@ -3,19 +3,10 @@ import codechicken.lib.colour.Colour; import codechicken.lib.colour.ColourARGB; import codechicken.lib.util.ResourceUtils; -import com.mojang.blaze3d.platform.GlStateManager; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.resources.Identifier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; @@ -29,7 +20,7 @@ public class TextureUtils { /** * @return an array of ARGB pixel data */ - public static int[] loadTextureData(ResourceLocation resource) { + public static int[] loadTextureData(Identifier resource) { BufferedImage img = loadBufferedImage(resource); if (img == null) { return new int[0]; @@ -41,7 +32,7 @@ public static int[] loadTextureData(ResourceLocation resource) { return data; } - public static Colour[] loadTextureColours(ResourceLocation resource) { + public static Colour[] loadTextureColours(Identifier resource) { int[] idata = loadTextureData(resource); Colour[] data = new Colour[idata.length]; for (int i = 0; i < data.length; i++) { @@ -50,7 +41,7 @@ public static Colour[] loadTextureColours(ResourceLocation resource) { return data; } - public static @Nullable BufferedImage loadBufferedImage(ResourceLocation textureFile) { + public static @Nullable BufferedImage loadBufferedImage(Identifier textureFile) { try { return loadBufferedImage(ResourceUtils.getResourceAsStream(textureFile)); } catch (Exception ex) { @@ -75,40 +66,4 @@ public static void copySubImg(int[] fromTex, int fromWidth, int fromX, int fromY } } } - - public static TextureManager getTextureManager() { - return Minecraft.getInstance().getTextureManager(); - } - - public static TextureAtlas getTextureMap() { - return Minecraft.getInstance().getModelManager().getAtlas(InventoryMenu.BLOCK_ATLAS); - } - - public static TextureAtlasSprite getMissingSprite() { - return getTextureMap().getSprite(MissingTextureAtlasSprite.getLocation()); - } - - public static TextureAtlasSprite getTexture(String location) { - return getTextureMap().getSprite(ResourceLocation.parse(location)); - } - - public static TextureAtlasSprite getTexture(ResourceLocation location) { - return getTextureMap().getSprite(location); - } - - public static TextureAtlasSprite getBlockTexture(String string) { - return getBlockTexture(ResourceLocation.parse(string)); - } - - public static TextureAtlasSprite getBlockTexture(ResourceLocation location) { - return getTexture(ResourceLocation.fromNamespaceAndPath(location.getNamespace(), "block/" + location.getPath())); - } - - public static TextureAtlasSprite getItemTexture(String string) { - return getItemTexture(ResourceLocation.parse(string)); - } - - public static TextureAtlasSprite getItemTexture(ResourceLocation location) { - return getTexture(ResourceLocation.fromNamespaceAndPath(location.getNamespace(), "items/" + location.getPath())); - } } diff --git a/src/main/java/codechicken/lib/util/CCLTags.java b/src/main/java/codechicken/lib/util/CCLTags.java index 9381ec32..191c36dd 100644 --- a/src/main/java/codechicken/lib/util/CCLTags.java +++ b/src/main/java/codechicken/lib/util/CCLTags.java @@ -1,6 +1,6 @@ package codechicken.lib.util; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; @@ -33,7 +33,7 @@ public static class Blocks { public static TagKey WOOLS_BLACK = common("wools/black"); private static TagKey common(String path) { - return BlockTags.create(ResourceLocation.fromNamespaceAndPath("c", path)); + return BlockTags.create(Identifier.fromNamespaceAndPath("c", path)); } } @@ -58,7 +58,7 @@ public static class Items { public static TagKey WOOLS_BLACK = common("wools/black"); private static TagKey common(String path) { - return ItemTags.create(ResourceLocation.fromNamespaceAndPath("c", path)); + return ItemTags.create(Identifier.fromNamespaceAndPath("c", path)); } } } diff --git a/src/main/java/codechicken/lib/util/ItemUtils.java b/src/main/java/codechicken/lib/util/ItemUtils.java index 325f6d16..e0911fc2 100644 --- a/src/main/java/codechicken/lib/util/ItemUtils.java +++ b/src/main/java/codechicken/lib/util/ItemUtils.java @@ -3,7 +3,6 @@ import codechicken.lib.vec.Vector3; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.LivingEntity; @@ -127,7 +126,7 @@ public static ItemStack copyStack(ItemStack stack, int quantity) { public static void ejectItem(Level world, BlockPos pos, ItemStack stack, Direction dir) { pos.relative(dir); ItemEntity entity = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, stack); - entity.setDeltaMovement(Vec3.atLowerCornerOf(dir.getNormal()).scale(0.3)); + entity.setDeltaMovement(Vec3.atLowerCornerOf(dir.getUnitVec3i()).scale(0.3)); entity.setPickUpDelay(10); world.addFreshEntity(entity); } diff --git a/src/main/java/codechicken/lib/util/ResourceUtils.java b/src/main/java/codechicken/lib/util/ResourceUtils.java index 60e27ac9..646fce53 100644 --- a/src/main/java/codechicken/lib/util/ResourceUtils.java +++ b/src/main/java/codechicken/lib/util/ResourceUtils.java @@ -1,11 +1,8 @@ package codechicken.lib.util; import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ReloadableResourceManager; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import net.minecraft.server.packs.resources.ResourceProvider; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.*; import java.io.BufferedReader; import java.io.IOException; @@ -24,7 +21,7 @@ public class ResourceUtils { * @return The InputStream. * @throws IOException If the file is not found or some other IO error occurred. */ - public static InputStream getResourceAsStream(ResourceLocation resource) throws IOException { + public static InputStream getResourceAsStream(Identifier resource) throws IOException { return getResource(resource).open(); } @@ -33,8 +30,8 @@ public static InputStream getResourceAsStream(ResourceLocation resource) throws * * @return The resource manager. */ - public static ReloadableResourceManager getResourceManager() { - return (ReloadableResourceManager) Minecraft.getInstance().getResourceManager(); + public static ResourceManager getResourceManager() { + return Minecraft.getInstance().getResourceManager(); } /** @@ -44,28 +41,19 @@ public static ReloadableResourceManager getResourceManager() { * @return The gotten resource. * @throws IOException If the resource doesn't exist, or some other IO error occurred. */ - public static Resource getResource(ResourceLocation location) throws IOException { + public static Resource getResource(Identifier location) throws IOException { return getResourceManager().getResourceOrThrow(location); } /** - * Registers a IResourceManagerReloadListener to MC's resource manager. - * - * @param reloadListener The listener. - */ - public static void registerReloadListener(ResourceManagerReloadListener reloadListener) { - getResourceManager().registerReloadListener(reloadListener); - } - - /** - * Loads the given {@link ResourceLocation} with the given {@link ResourceProvider} into + * Loads the given {@link Identifier} with the given {@link ResourceProvider} into * a list of UTF-8 Strings. * * @param resourceProvider The {@link ResourceProvider}. - * @param loc The {@link ResourceLocation}. + * @param loc The {@link Identifier}. * @return The UTF-8 lines of the resource. */ - public static List loadResource(ResourceProvider resourceProvider, ResourceLocation loc) { + public static List loadResource(ResourceProvider resourceProvider, Identifier loc) { try { Resource resource = resourceProvider.getResourceOrThrow(loc); try (BufferedReader reader = resource.openAsReader()) { @@ -75,5 +63,4 @@ public static List loadResource(ResourceProvider resourceProvider, Resou throw new RuntimeException("Failed to load MTL file: " + loc, ex); } } - } diff --git a/src/main/java/codechicken/lib/util/TransformUtils.java b/src/main/java/codechicken/lib/util/TransformUtils.java deleted file mode 100644 index abab10f3..00000000 --- a/src/main/java/codechicken/lib/util/TransformUtils.java +++ /dev/null @@ -1,170 +0,0 @@ -package codechicken.lib.util; - -import codechicken.lib.math.MathHelper; -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.vec.Vector3; -import com.google.common.collect.ImmutableMap; -import com.mojang.math.Transformation; -import net.minecraft.client.renderer.block.model.ItemTransform; -import net.minecraft.client.renderer.block.model.ItemTransforms; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.world.item.ItemDisplayContext; -import org.joml.Quaternionf; -import org.joml.Vector3f; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by covers1624 on 5/16/2016. - * This is mostly just extracted from the ForgeBlockStateV1 in 1.10. - * Credits to Fry. - *

    - * If you have an idea for another transform just make a pull request. - */ -public class TransformUtils { - - private static final Transformation flipX = new Transformation(null, null, new Vector3f(-1, 1, 1), null); - - public static final PerspectiveModelState IDENTITY = PerspectiveModelState.IDENTITY; - public static final PerspectiveModelState DEFAULT_BLOCK; - public static final PerspectiveModelState DEFAULT_ITEM; - public static final PerspectiveModelState DEFAULT_TOOL; - public static final PerspectiveModelState DEFAULT_BOW; - public static final PerspectiveModelState DEFAULT_HANDHELD_ROD; - - static { - Map map; - Transformation thirdPerson; - Transformation firstPerson; - - //@formatter:off - map = new HashMap<>(); - thirdPerson = create(0F,2.5F, 0F,75F, 45F, 0F,0.375F ); - map.put(ItemDisplayContext.GUI, create(0F, 0F, 0F,30F,225F, 0F,0.625F)); - map.put(ItemDisplayContext.GROUND, create(0F, 3F, 0F, 0F, 0F, 0F, 0.25F)); - map.put(ItemDisplayContext.FIXED, create(0F, 0F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, thirdPerson); - map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); - map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(0F, 0F, 0F, 0F, 45F, 0F, 0.4F)); - map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(0F, 0F, 0F, 0F, 225F, 0F, 0.4F)); - DEFAULT_BLOCK = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - thirdPerson = create( 0F, 3F, 1F, 0F, 0F, 0F, 0.55F); - firstPerson = create(1.13F,3.2F,1.13F, 0F,-90F,25F, 0.68F); - map.put(ItemDisplayContext.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(ItemDisplayContext.HEAD, create( 0F, 13F, 7F, 0F,180F, 0F, 1F)); - map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, thirdPerson); - map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); - map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, firstPerson); - map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, flipLeft(firstPerson)); - DEFAULT_ITEM = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - map.put(ItemDisplayContext.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(ItemDisplayContext.FIXED, create( 0F, 0F, 0F, 0F,180F, 0F, 1F)); - map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, create( 0F, 4F, 0.5F, 0F,-90F, 55,0.85F)); - map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, create( 0F, 4F, 0.5F, 0F, 90F,-55,0.85F)); - map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F,-90F, 25,0.68F)); - map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25,0.68F)); - DEFAULT_TOOL = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - map.put(ItemDisplayContext.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(ItemDisplayContext.FIXED, create( 0F, 0F, 0F, 0F, 180F, 0F, 1F)); - map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, create( -1F, -2F, 2.5F,-80F, 260F,-40F, 0.9F)); - map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, create( -1F, -2F, 2.5F,-80F,-280F, 40F, 0.9F)); - map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F, -90F, 25F,0.68F)); - map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25F,0.68F)); - DEFAULT_BOW = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - map.put(ItemDisplayContext.GROUND, create(0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(ItemDisplayContext.THIRD_PERSON_RIGHT_HAND, create(0F, 4F,2.5F, 0F, 90F, 55F,0.85F)); - map.put(ItemDisplayContext.THIRD_PERSON_LEFT_HAND, create(0F, 4F,2.5F, 0F,-90F,-55F,0.85F)); - map.put(ItemDisplayContext.FIRST_PERSON_RIGHT_HAND, create(0F,1.6F,0.8F, 0F, 90F, 25F,0.68F)); - map.put(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, create(0F,1.6F,0.8F, 0F,-90F,-25F,0.68F)); - DEFAULT_HANDHELD_ROD = new PerspectiveModelState(ImmutableMap.copyOf(map)); - //@formatter:on - } - - /** - * Creates a new TRSRTransformation. - * - * @param tx The x transform. - * @param ty The y transform. - * @param tz The z transform. - * @param rx The x Axis rotation. - * @param ry The y Axis rotation. - * @param rz The z Axis rotation. - * @param s The scale. - * @return The new TRSRTransformation. - */ - public static Transformation create(float tx, float ty, float tz, float rx, float ry, float rz, float s) { - return create(new Vector3f(tx / 16, ty / 16, tz / 16), new Vector3f(rx, ry, rz), new Vector3f(s, s, s)); - } - - /** - * Creates a new TRSRTransformation. - * - * @param transform The transform. - * @param rotation The rotation. - * @param scale The scale. - * @return The new TRSRTransformation. - */ - public static Transformation create(Vector3 transform, Vector3 rotation, Vector3 scale) { - return create(transform.vector3f(), rotation.vector3f(), scale.vector3f()); - } - - /** - * Creates a new TRSRTransformation. - * - * @param transform The transform. - * @param rotation The rotation. - * @param scale The scale. - * @return The new TRSRTransformation. - */ - public static Transformation create(Vector3f transform, Vector3f rotation, Vector3f scale) { - return new Transformation( - transform, - new Quaternionf().rotationXYZ((float) (rotation.x() * MathHelper.torad), (float) (rotation.y() * MathHelper.torad), (float) (rotation.z() * MathHelper.torad)), - scale, - null - ); - } - - public static Transformation create(ItemTransform transform) { - if (ItemTransform.NO_TRANSFORM.equals(transform)) return Transformation.identity(); - - return create(transform.translation, transform.rotation, transform.scale); - } - - /** - * Flips the transform for the left hand. - * - * @param transform The right-hand transform. - * @return The new left-hand transform. - */ - public static Transformation flipLeft(Transformation transform) { - return flipX.compose(transform).compose(flipX); - } - - /** - * Decompose a vanilla {@link ItemTransforms} into a {@link PerspectiveModelState}. - * - * @param itemTransforms the {@link ItemTransforms} to decompose. - * @return The {@link PerspectiveModelState} - */ - public static ModelState stateFromItemTransforms(ItemTransforms itemTransforms) { - if (itemTransforms == ItemTransforms.NO_TRANSFORMS) return IDENTITY; - - ImmutableMap.Builder map = ImmutableMap.builder(); - - for (ItemDisplayContext value : ItemDisplayContext.values()) { - map.put(value, create(itemTransforms.getTransform(value))); - } - - return new PerspectiveModelState(map.build()); - } -} diff --git a/src/main/java/codechicken/lib/util/VertexUtils.java b/src/main/java/codechicken/lib/util/VertexUtils.java deleted file mode 100644 index fd9d05db..00000000 --- a/src/main/java/codechicken/lib/util/VertexUtils.java +++ /dev/null @@ -1,142 +0,0 @@ -package codechicken.lib.util; - -import codechicken.lib.model.IVertexConsumer; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; -import net.minecraft.client.renderer.block.model.BakedQuad; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Created by covers1624 on 9/7/22. - */ -public class VertexUtils { - - private static final ConcurrentMap, int[]> formatMaps = new ConcurrentHashMap<>(); - - private static final int[] DEFAULT_MAPPING = generateMapping(DefaultVertexFormat.BLOCK, DefaultVertexFormat.BLOCK); - - public static int[] mapFormats(VertexFormat from, VertexFormat to) { - if (from.equals(DefaultVertexFormat.BLOCK) && to.equals(DefaultVertexFormat.BLOCK)) return DEFAULT_MAPPING; - - return formatMaps.computeIfAbsent(Pair.of(from, to), pair -> generateMapping(pair.getLeft(), pair.getRight())); - } - - public static void putQuad(IVertexConsumer consumer, BakedQuad quad) { - consumer.setTexture(quad.getSprite()); - consumer.setQuadOrientation(quad.getDirection()); - if (quad.isTinted()) { - consumer.setQuadTint(quad.getTintIndex()); - } - consumer.setApplyDiffuseLighting(quad.isShade()); - float[] data = new float[4]; - VertexFormat formatFrom = consumer.getVertexFormat(); - VertexFormat formatTo = DefaultVertexFormat.BLOCK; - int countFrom = formatFrom.getElements().size(); - int countTo = formatTo.getElements().size(); - int[] eMap = mapFormats(formatFrom, formatTo); - for (int v = 0; v < 4; v++) { - for (int e = 0; e < countFrom; e++) { - if (eMap[e] != countTo) { - unpack(quad.getVertices(), data, formatTo, v, eMap[e]); - consumer.put(e, data); - } else { - consumer.put(e); - } - } - } - } - - public static void unpack(int[] from, float[] to, VertexFormat formatFrom, int v, int e) { - int length = Math.min(4, to.length); - VertexFormatElement element = formatFrom.getElements().get(e); - int vertexStart = v * formatFrom.getVertexSize() + formatFrom.getOffset(element); - int count = element.count(); - VertexFormatElement.Type type = element.type(); - VertexFormatElement.Usage usage = element.usage(); - int size = type.size(); - int mask = (256 << (8 * (size - 1))) - 1; - for (int i = 0; i < length; i++) { - if (i < count) { - int pos = vertexStart + size * i; - int index = pos >> 2; - int offset = pos & 3; - int bits = from[index]; - bits = bits >>> (offset * 8); - if ((pos + size - 1) / 4 != index) { - bits |= from[index + 1] << ((4 - offset) * 8); - } - bits &= mask; - if (type == VertexFormatElement.Type.FLOAT) { - to[i] = Float.intBitsToFloat(bits); - } else if (type == VertexFormatElement.Type.UBYTE || type == VertexFormatElement.Type.USHORT) { - to[i] = (float) bits / mask; - } else if (type == VertexFormatElement.Type.UINT) { - to[i] = (float) ((double) (bits & 0xFFFFFFFFL) / 0xFFFFFFFFL); - } else if (type == VertexFormatElement.Type.BYTE) { - to[i] = ((float) (byte) bits) / (mask >> 1); - } else if (type == VertexFormatElement.Type.SHORT) { - to[i] = ((float) (short) bits) / (mask >> 1); - } else if (type == VertexFormatElement.Type.INT) { - to[i] = (float) ((double) (bits & 0xFFFFFFFFL) / (0xFFFFFFFFL >> 1)); - } - } else { - to[i] = (i == 3 && usage == VertexFormatElement.Usage.POSITION) ? 1 : 0; - } - } - } - - public static void pack(float[] from, int[] to, VertexFormat formatTo, int v, int e) { - VertexFormatElement element = formatTo.getElements().get(e); - int vertexStart = v * formatTo.getVertexSize() + formatTo.getOffset(element); - int count = element.count(); - VertexFormatElement.Type type = element.type(); - int size = type.size(); - int mask = (256 << (8 * (size - 1))) - 1; - for (int i = 0; i < 4; i++) { - if (i < count) { - int pos = vertexStart + size * i; - int index = pos >> 2; - int offset = pos & 3; - int bits = 0; - float f = i < from.length ? from[i] : 0; - if (type == VertexFormatElement.Type.FLOAT) { - bits = Float.floatToRawIntBits(f); - } else if ( - type == VertexFormatElement.Type.UBYTE || - type == VertexFormatElement.Type.USHORT || - type == VertexFormatElement.Type.UINT - ) { - bits = Math.round(f * mask); - } else { - bits = Math.round(f * (mask >> 1)); - } - to[index] &= ~(mask << (offset * 8)); - to[index] |= (((bits & mask) << (offset * 8))); - // TODO handle overflow into to[index + 1] - } - } - } - - private static int[] generateMapping(VertexFormat from, VertexFormat to) { - int fromCount = from.getElements().size(); - int toCount = to.getElements().size(); - int[] eMap = new int[fromCount]; - - for (int e = 0; e < fromCount; e++) { - VertexFormatElement expected = from.getElements().get(e); - int e2; - for (e2 = 0; e2 < toCount; e2++) { - VertexFormatElement current = to.getElements().get(e2); - if (expected.usage() == current.usage() && expected.index() == current.index()) { - break; - } - } - eMap[e] = e2; - } - return eMap; - } -} diff --git a/src/main/java/codechicken/lib/vec/Cuboid6.java b/src/main/java/codechicken/lib/vec/Cuboid6.java index 2c048b13..8a866d70 100644 --- a/src/main/java/codechicken/lib/vec/Cuboid6.java +++ b/src/main/java/codechicken/lib/vec/Cuboid6.java @@ -2,10 +2,14 @@ import codechicken.lib.raytracer.VoxelShapeCache; import codechicken.lib.util.Copyable; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; @@ -16,7 +20,19 @@ public class Cuboid6 implements Copyable { - public static Cuboid6 full = new Cuboid6(0, 0, 0, 1, 1, 1); + public static final Cuboid6 full = new Cuboid6(0, 0, 0, 1, 1, 1); + + public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + Vector3.CODEC.fieldOf("min").forGetter(e -> e.min), + Vector3.CODEC.fieldOf("max").forGetter(e -> e.max) + ).apply(b, Cuboid6::new) + ); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + Vector3.STREAM_CODEC, e -> e.min, + Vector3.STREAM_CODEC, e -> e.max, + Cuboid6::new + ); public Vector3 min; public Vector3 max; @@ -41,7 +57,7 @@ public Cuboid6(AABB aabb) { } public Cuboid6(CompoundTag tag) { - this(Vector3.fromNBT(tag.getCompound("min")), Vector3.fromNBT(tag.getCompound("max"))); + this(Vector3.fromNBT(tag.getCompoundOrEmpty("min")), Vector3.fromNBT(tag.getCompoundOrEmpty("max"))); } public Cuboid6(Cuboid6 cuboid) { @@ -154,8 +170,8 @@ public Cuboid6 expand(Vector3 vec) { public Cuboid6 expandSide(Direction side, int amount) { switch (side.getAxisDirection()) { - case NEGATIVE -> min.add(Vector3.fromVec3i(side.getNormal()).multiply(amount)); - case POSITIVE -> max.add(Vector3.fromVec3i(side.getNormal()).multiply(amount)); + case NEGATIVE -> min.add(Vector3.fromVec3i(side.getUnitVec3i()).multiply(amount)); + case POSITIVE -> max.add(Vector3.fromVec3i(side.getUnitVec3i()).multiply(amount)); } return this; } diff --git a/src/main/java/codechicken/lib/vec/Matrix4.java b/src/main/java/codechicken/lib/vec/Matrix4.java index 914312ef..42d4443c 100644 --- a/src/main/java/codechicken/lib/vec/Matrix4.java +++ b/src/main/java/codechicken/lib/vec/Matrix4.java @@ -66,6 +66,10 @@ public Matrix4(PoseStack stack) { set(stack); } + public Matrix4(PoseStack.Pose pose) { + set(pose); + } + public Matrix4 setIdentity() { m00 = m11 = m22 = m33 = 1; m01 = m02 = m03 = m10 = m12 = m13 = m20 = m21 = m23 = m30 = m31 = m32 = 0; @@ -416,6 +420,10 @@ public Matrix4 set(PoseStack stack) { return set(stack.last().pose()); } + public Matrix4 set(PoseStack.Pose pose) { + return set(pose.pose()); + } + public Matrix4 set(Matrix4f mat) { m00 = mat.m00(); m01 = mat.m10(); diff --git a/src/main/java/codechicken/lib/vec/Vector3.java b/src/main/java/codechicken/lib/vec/Vector3.java index 11c4a4bc..8495c460 100644 --- a/src/main/java/codechicken/lib/vec/Vector3.java +++ b/src/main/java/codechicken/lib/vec/Vector3.java @@ -16,6 +16,7 @@ import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; +import org.joml.Vector3fc; import org.joml.Vector4f; import java.math.BigDecimal; @@ -128,7 +129,7 @@ public static Vector3 fromArray(float[] fa) { } public static Vector3 fromNBT(CompoundTag tag) { - return new Vector3(tag.getDouble("x"), tag.getDouble("y"), tag.getDouble("z")); + return new Vector3(tag.getDoubleOr("x", 0), tag.getDoubleOr("y", 0), tag.getDoubleOr("z", 0)); } public Vec3 vec3() { @@ -181,6 +182,10 @@ public Vector3 set(Vec3i vec) { return set(vec.getX(), vec.getY(), vec.getZ()); } + public Vector3 set(Vector3fc vec) { + return set(vec.x(), vec.y(), vec.z()); + } + public Vector3 set(double[] da) { return set(da[0], da[1], da[2]); } diff --git a/src/main/java/codechicken/lib/vec/uv/IconTransformation.java b/src/main/java/codechicken/lib/vec/uv/IconTransformation.java index ebc77a8a..d3f10149 100644 --- a/src/main/java/codechicken/lib/vec/uv/IconTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/IconTransformation.java @@ -49,8 +49,8 @@ public Inverse(Inverse other) { @Override public void apply(UV uv) { - uv.u = icon.getUOffset((float) uv.u) / 16; - uv.v = icon.getVOffset((float) uv.v) / 16; + uv.u = getUOffset(icon, (float) uv.u); + uv.v = getVOffset(icon, (float) uv.v); } @Override @@ -62,5 +62,13 @@ public UVTransformation inverse() { public IconTransformation copy() { return new Inverse(this); } + + public static float getUOffset(TextureAtlasSprite sprite, float u) { + return (u - sprite.getU0()) / (sprite.getU1() - sprite.getU0()); + } + + public static float getVOffset(TextureAtlasSprite sprite, float v) { + return (v - sprite.getV0()) / (sprite.getV1() - sprite.getV0()); + } } } diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 51b57a39..c1deec27 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -1,6 +1,6 @@ # CodeChickenLib Access Transformer public net.minecraft.core.Direction BY_3D_DATA -public net.minecraft.world.phys.BlockHitResult (ZLnet/minecraft/world/phys/Vec3;Lnet/minecraft/core/Direction;Lnet/minecraft/core/BlockPos;Z)V +public net.minecraft.world.phys.BlockHitResult (ZLnet/minecraft/world/phys/Vec3;Lnet/minecraft/core/Direction;Lnet/minecraft/core/BlockPos;ZZ)V public net.minecraft.server.MinecraftServer storageSource public com.mojang.math.Matrix3f * # All fields. @@ -17,50 +17,21 @@ public net.minecraft.world.inventory.MenuType constructor public net.minecraft.client.renderer.RenderStateShard * # Everything. public net.minecraft.client.renderer.RenderType *() # All Methods public net.minecraft.client.renderer.RenderType * # All Fields. -public-f net.minecraft.client.renderer.block.BlockRenderDispatcher modelRenderer -public net.minecraft.client.renderer.block.BlockRenderDispatcher blockEntityRenderer -public-f net.minecraft.client.renderer.block.BlockRenderDispatcher liquidBlockRenderer -public-f net.minecraft.client.Minecraft blockRenderer +public net.minecraft.client.renderer.RenderType$CompositeRenderType +public net.minecraft.client.renderer.RenderType$CompositeRenderType * +public net.minecraft.client.renderer.RenderType$CompositeRenderType *() +public net.minecraft.client.renderer.RenderType$CompositeState +public net.minecraft.client.renderer.RenderType$CompositeState * +public net.minecraft.client.renderer.RenderType$CompositeState *() public net.minecraft.world.item.ArmorMaterials HEALTH_FUNCTION_FOR_TYPE +public com.mojang.blaze3d.vertex.VertexFormat uploadToBuffer(Lcom/mojang/blaze3d/buffers/GpuBuffer;Ljava/nio/ByteBuffer;ILjava/util/function/Supplier;)Lcom/mojang/blaze3d/buffers/GpuBuffer; + public-f net.minecraft.world.level.block.Block stateDefinition public-f net.minecraft.world.level.block.Block defaultBlockState()Lnet/minecraft/world/level/block/state/BlockState; public-f net.minecraft.data.loot.LootTableProvider subProviders -public net.minecraft.data.tags.IntrinsicHolderTagsProvider tag(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/IntrinsicHolderTagsProvider$IntrinsicTagAppender; - -protected net.minecraft.client.renderer.ShaderInstance uniforms -protected net.minecraft.client.renderer.ShaderInstance parseUniformNode(Lcom/google/gson/JsonElement;)V -protected-f com.mojang.blaze3d.shaders.Uniform intValues -protected-f com.mojang.blaze3d.shaders.Uniform floatValues -protected com.mojang.blaze3d.shaders.Uniform dirty -public-f com.mojang.blaze3d.shaders.Uniform set(F)V -public-f com.mojang.blaze3d.shaders.Uniform set(FF)V -public-f com.mojang.blaze3d.shaders.Uniform set(IF)V -public-f com.mojang.blaze3d.shaders.Uniform set(FFF)V -public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Vector3f;)V -public-f com.mojang.blaze3d.shaders.Uniform set(FFFF)V -public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Vector4f;)V -public-f com.mojang.blaze3d.shaders.Uniform setSafe(FFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setSafe(IIII)V -public-f com.mojang.blaze3d.shaders.Uniform set(I)V -public-f com.mojang.blaze3d.shaders.Uniform set(II)V -public-f com.mojang.blaze3d.shaders.Uniform set(III)V -public-f com.mojang.blaze3d.shaders.Uniform set(IIII)V -public-f com.mojang.blaze3d.shaders.Uniform set([F)V -public-f com.mojang.blaze3d.shaders.Uniform setMat2x2(FFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat2x3(FFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat2x4(FFFFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat3x2(FFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat3x3(FFFFFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat3x4(FFFFFFFFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat4x2(FFFFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat4x3(FFFFFFFFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform setMat4x4(FFFFFFFFFFFFFFFF)V -public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Matrix4f;)V -public-f com.mojang.blaze3d.shaders.Uniform set(Lorg/joml/Matrix3f;)V -public com.mojang.blaze3d.shaders.Program (Lcom/mojang/blaze3d/shaders/Program$Type;ILjava/lang/String;)V -public com.mojang.blaze3d.shaders.Program$Type getGlType()I +public net.minecraft.data.tags.IntrinsicHolderTagsProvider tag(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/TagAppender; public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen renderSlot(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/inventory/Slot;)V public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen renderFloatingItem(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/item/ItemStack;IILjava/lang/String;)V @@ -72,13 +43,14 @@ public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen draggi public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen isSplittingStack public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen quickCraftingType public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen quickCraftingRemainder -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackItem -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackTime -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackEnd -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackStartX -public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackStartY +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen$SnapbackData +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackData +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen showTooltipWithItemInHand(Lnet/minecraft/world/item/ItemStack;)Z +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen getHoveredSlot(DD)Lnet/minecraft/world/inventory/Slot; public-f net.minecraft.world.inventory.Slot x public-f net.minecraft.world.inventory.Slot y public net.minecraft.world.inventory.AbstractContainerMenu addSlot(Lnet/minecraft/world/inventory/Slot;)Lnet/minecraft/world/inventory/Slot; -public net.minecraft.client.gui.GuiGraphics (Lnet/minecraft/client/Minecraft;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;)V +public net.minecraft.client.gui.render.state.BlitRenderState getBounds(IIIILorg/joml/Matrix3x2f;Lnet/minecraft/client/gui/navigation/ScreenRectangle;)Lnet/minecraft/client/gui/navigation/ScreenRectangle; + +public net.minecraft.client.gui.GuiGraphics minecraft diff --git a/src/main/resources/META-INF/interfaces.json b/src/main/resources/META-INF/interfaces.json new file mode 100644 index 00000000..f1ff8b0f --- /dev/null +++ b/src/main/resources/META-INF/interfaces.json @@ -0,0 +1,14 @@ +{ + "net/minecraft/network/FriendlyByteBuf": [ + "codechicken/lib/packet/CCFriendlyByteBufExtension" + ], + "net/minecraft/network/RegistryFriendlyByteBuf": [ + "codechicken/lib/packet/CCRegistryFriendlyByteBufExtension" + ], + "net/minecraft/client/renderer/OrderedSubmitNodeCollector": [ + 'codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension' + ], + "net/minecraft/client/gui/GuiGraphics": [ + 'codechicken/lib/gui/render/GuiGraphicsExtension' + ] +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index c7b51658..ef0724b1 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -3,6 +3,9 @@ loaderVersion="[2,)" issueTrackerURL="https://github.com/TheCBProject/CodeChickenLib" license="GNU Lesser General Public License v2.1" +[[mixins]] +config="mixins.codechickenlib.json" + [[mods]] modId="codechickenlib" displayName="CodeChicken Lib" @@ -24,7 +27,7 @@ It contains libraries for 3D math and transformations, model rendering, packets, [[dependencies.codechickenlib]] modId="minecraft" type="required" - versionRange="[1.21.1]" + versionRange="[1.21.11]" ordering="NONE" side="BOTH" diff --git a/src/main/resources/assets/codechickenlib/atlases/gui.json b/src/main/resources/assets/codechickenlib/atlases/gui.json deleted file mode 100644 index 5da82735..00000000 --- a/src/main/resources/assets/codechickenlib/atlases/gui.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "sources": [ - { - "type": "directory", - "source": "gui", - "prefix": "gui/" - } - ] -} \ No newline at end of file diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/drag.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/drag.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/cursors/drag.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/drag.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_tlbr.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_tlbr.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_tlbr.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_tlbr.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_trbl.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_trbl.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_diag_trbl.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_trbl.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_h.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_h.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_h.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_h.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_v.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_v.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/cursors/resize_v.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_v.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless_pressed.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless_pressed.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_borderless_pressed.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless_pressed.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_borderless.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_borderless.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_borderless.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_pressed.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_pressed.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_highlight_pressed.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_pressed.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_pressed.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_pressed.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_pressed.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_pressed.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla_disabled.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla_disabled.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/button_vanilla_disabled.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla_disabled.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_borderless.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_borderless.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_borderless.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_vanilla.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_vanilla.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/dynamic/gui_vanilla.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_vanilla.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/widgets/energy_empty.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_empty.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/widgets/energy_empty.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_empty.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/widgets/energy_full.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_full.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/widgets/energy_full.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_full.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/widgets/progress_arrow_empty.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_empty.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/widgets/progress_arrow_empty.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_empty.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/widgets/progress_arrow_full.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_full.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/widgets/progress_arrow_full.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_full.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/widgets/slot.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/widgets/slot.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot.png diff --git a/src/main/resources/assets/codechickenlib/textures/gui/widgets/slot_large.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot_large.png similarity index 100% rename from src/main/resources/assets/codechickenlib/textures/gui/widgets/slot_large.png rename to src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot_large.png diff --git a/src/main/resources/mixins.codechickenlib.json b/src/main/resources/mixins.codechickenlib.json index 3b3388c5..d45f1301 100644 --- a/src/main/resources/mixins.codechickenlib.json +++ b/src/main/resources/mixins.codechickenlib.json @@ -5,11 +5,14 @@ "plugin": "codechicken.lib.internal.mixin.CCLMixinPlugin", "target": "@env(DEFAULT)", "compatibilityLevel": "JAVA_17", + "mixins": [ + "network.FriendlyByteBufMixin", + "network.RegistryFriendlyByteBufMixin" + ], "client": [ "dev.GameNarratorMixin", - "ItemRendererMixin", "MinecraftMixin", - "ShaderInstanceMixin", - "compat.EmbeddiumCCLMixin" + "render.OrderedSubmitNodeCollectorMixin", + "render.GuiGraphicsMixin" ] } diff --git a/src/test/java/codechicken/lib/config/ConfigV3Tests.java b/src/test/java/codechicken/lib/config/ConfigV3Tests.java index b44d549c..21b1e544 100644 --- a/src/test/java/codechicken/lib/config/ConfigV3Tests.java +++ b/src/test/java/codechicken/lib/config/ConfigV3Tests.java @@ -14,6 +14,7 @@ import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongList; +import net.minecraft.network.FriendlyByteBuf; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; @@ -931,7 +932,7 @@ public void testCopy() { @Test public void testTagCategoryRead() { ByteBuf buffer = Unpooled.buffer(); - MCDataByteBuf buf = new MCDataByteBuf(buffer); + FriendlyByteBuf buf = new FriendlyByteBuf(buffer); IllegalStateException ex; ConfigCategoryImpl rootTag = new ConfigCategoryImpl("rootTag", null); @@ -940,7 +941,7 @@ public void testTagCategoryRead() { buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_NO_TAG - 1); - buf.writeString("cat1"); + buf.writeUtf("cat1"); ex = assertThrows(IllegalStateException.class, () -> rootTag.read(buf)); assertEquals("Unknown tag network type: " + (ConfigCategoryImpl.NET_NO_TAG - 1), ex.getMessage()); @@ -964,7 +965,7 @@ public void testTagCategoryRead() { { // Test NET_CAT_TAG behaves as expected. buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_CAT_TAG); - buf.writeString("cat1"); + buf.writeUtf("cat1"); buf.writeVarInt(0); rootTag.read(buf); @@ -990,7 +991,7 @@ public void testTagCategoryRead() { { // Test NET_VAL_TAG behaves as expected. buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_VAL_TAG); - buf.writeString("val1"); + buf.writeUtf("val1"); buf.writeEnum(ValueType.INT); buf.writeInt(22); rootTag.read(buf); @@ -1017,7 +1018,7 @@ public void testTagCategoryRead() { { // Test NET_VAL_LST behaves as expected. buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_VAL_LST); - buf.writeString("lst1"); + buf.writeUtf("lst1"); buf.writeEnum(ValueType.INT); buf.writeVarInt(2); buf.writeInt(22); @@ -1043,7 +1044,7 @@ public void testTagCategoryRead() { @Test public void testTagValueRead() { ByteBuf buffer = Unpooled.buffer(); - MCDataByteBuf buf = new MCDataByteBuf(buffer); + FriendlyByteBuf buf = new FriendlyByteBuf(buffer); buf.writeEnum(ValueType.INT); buf.writeInt(22); @@ -1074,7 +1075,7 @@ public void testTagValueRead() { @Test public void testTagValueListRead() { ByteBuf buffer = Unpooled.buffer(); - MCDataByteBuf buf = new MCDataByteBuf(buffer); + FriendlyByteBuf buf = new FriendlyByteBuf(buffer); buf.writeEnum(ValueType.INT); buf.writeVarInt(2); buf.writeInt(22); @@ -1125,7 +1126,7 @@ public void testReadWriteEquality() { listCat.getValueList("list5").setHexs(new IntArrayList(List.of(0xFFFFFFFF, 0xFF00FF00))); listCat.getValueList("list6").setDoubles(new DoubleArrayList(List.of(4.20, 6.9))); - MCDataByteBuf buf = new MCDataByteBuf(); + FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); root.write(buf); ConfigCategoryImpl root2 = new ConfigCategoryImpl("rootTag", null); @@ -1149,7 +1150,7 @@ public void testResetFormNetwork() { root.getValue("not_synced"); - MCDataByteBuf buf = new MCDataByteBuf(); + FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); root.write(buf); ConfigCategoryImpl root2 = new ConfigCategoryImpl("rootTag", null); @@ -1192,7 +1193,7 @@ public void testConfigSaveWithNetworkSet() throws Throwable { .syncTagToClient(); listCat.getValueList("list1").setStrings(List.of("World", "Hello")); - MCDataByteBuf buf = new MCDataByteBuf(); + FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); root.write(buf); ConfigCategoryImpl root2 = new ConfigCategoryImpl("rootTag", null); diff --git a/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java b/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java deleted file mode 100644 index 0cb112e6..00000000 --- a/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java +++ /dev/null @@ -1,80 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.Quad; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Direction; -import net.neoforged.neoforge.client.textures.UnitTextureAtlasSprite; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Created by covers1624 on 1/1/22. - */ -public class BakedVertexSourceTests { - - static { - // Init vertex attributes. - CCRenderState.instance(); - } - - @Test - public void testExpand() { - BakedVertexSource source = new BakedVertexSource(); - assertEquals(0, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - source.ensureSpace(32); - assertEquals(32, source.getVertices().length); - source.ensureSpace(2048); - assertEquals(2048, source.getVertices().length); - source.ensureSpace(2048); - assertEquals(2048, source.getVertices().length); - } - - @Test - public void testExpandWithQuad() { - Quad unbaked = new Quad(); - unbaked.reset(CachedFormat.BLOCK); - unbaked.setQuadOrientation(Direction.NORTH); - unbaked.setTexture(UnitTextureAtlasSprite.INSTANCE); - BakedQuad quad = unbaked.bake(); - - BakedVertexSource source = new BakedVertexSource(); - source.reset(CachedFormat.BLOCK); - assertEquals(0, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(4, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(8, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(12, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(16, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(20, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(24, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(28, source.getVertexCount()); - assertEquals(28, source.getVertices().length); - - source.reset(CachedFormat.BLOCK); - assertEquals(0, source.getVertexCount()); - assertEquals(28, source.getVertices().length); - } -} diff --git a/src/test/java/codechicken/lib/render/model/MatLibTests.java b/src/test/java/codechicken/lib/render/model/MatLibTests.java index 0a59581f..6d12c702 100644 --- a/src/test/java/codechicken/lib/render/model/MatLibTests.java +++ b/src/test/java/codechicken/lib/render/model/MatLibTests.java @@ -2,7 +2,7 @@ import codechicken.lib.colour.ColourRGBA; import codechicken.lib.test.TestResourceProvider; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -15,7 +15,7 @@ public class MatLibTests { @Test public void testMatLibParse() { - MatLib matLib = MatLib.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test.mtl")); + MatLib matLib = MatLib.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test.mtl")); assertEquals(1, matLib.materials.size()); ModelMaterial material = matLib.getMaterial("Material"); assertNotNull(material); diff --git a/src/test/java/codechicken/lib/render/model/OBJParserTests.java b/src/test/java/codechicken/lib/render/model/OBJParserTests.java index 3c9aa71b..a9a858b7 100644 --- a/src/test/java/codechicken/lib/render/model/OBJParserTests.java +++ b/src/test/java/codechicken/lib/render/model/OBJParserTests.java @@ -3,7 +3,7 @@ import codechicken.lib.render.CCModel; import codechicken.lib.test.TestResourceProvider; import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import org.junit.jupiter.api.Test; import java.util.Map; @@ -19,7 +19,7 @@ public class OBJParserTests { @Test public void testObject() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -28,7 +28,7 @@ public void testObject() { @Test public void testGroup() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test_group.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test_group.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -37,7 +37,7 @@ public void testGroup() { @Test public void testGroupObject() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, ResourceLocation.parse("test:model/test_group_object.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test_group_object.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Group/Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -46,7 +46,7 @@ public void testGroupObject() { @Test public void testMultiObject() { - Map modelMap = new OBJParser(ResourceLocation.parse("test:model/test_multi_object.obj")) + Map modelMap = new OBJParser(Identifier.parse("test:model/test_multi_object.obj")) .provider(TestResourceProvider.INSTANCE) .ignoreMtl() .quads() diff --git a/src/test/java/codechicken/lib/test/TestResourceProvider.java b/src/test/java/codechicken/lib/test/TestResourceProvider.java index 7800e60f..2adbd7e3 100644 --- a/src/test/java/codechicken/lib/test/TestResourceProvider.java +++ b/src/test/java/codechicken/lib/test/TestResourceProvider.java @@ -1,7 +1,7 @@ package codechicken.lib.test; import codechicken.lib.render.model.OBJParserTests; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; @@ -21,7 +21,7 @@ private TestResourceProvider() { } @Override - public Optional getResource(ResourceLocation resource) { + public Optional getResource(Identifier resource) { return Optional.of(new Resource(null, () -> Objects.requireNonNull(OBJParserTests.class.getResourceAsStream("/" + resource.getPath()), "Resource " + resource + " doesnt exist."))); } } From ed84112158b7433450d2a6fbdd34ac1cdab1c6a3 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 26 Jul 2026 07:18:21 +0930 Subject: [PATCH 78/87] Add some helper codecs. --- .../lib/packet/CCStreamCodecs.java | 5 +++ .../java/codechicken/lib/util/CCCodecs.java | 36 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/main/java/codechicken/lib/util/CCCodecs.java diff --git a/src/main/java/codechicken/lib/packet/CCStreamCodecs.java b/src/main/java/codechicken/lib/packet/CCStreamCodecs.java index c7ed0208..3f477f9f 100644 --- a/src/main/java/codechicken/lib/packet/CCStreamCodecs.java +++ b/src/main/java/codechicken/lib/packet/CCStreamCodecs.java @@ -4,13 +4,18 @@ import net.minecraft.network.Utf8String; import net.minecraft.network.VarInt; import net.minecraft.network.VarLong; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; /** * Created by covers1624 on 10/31/25. */ public final class CCStreamCodecs { + public static final StreamCodec BLOCK_STATE = ByteBufCodecs.idMapper(Block.BLOCK_STATE_REGISTRY); + public static final StreamCodec BYTE_ARRAY = StreamCodec.of( (buf, arr) -> { VarInt.write(buf, arr.length); diff --git a/src/main/java/codechicken/lib/util/CCCodecs.java b/src/main/java/codechicken/lib/util/CCCodecs.java new file mode 100644 index 00000000..64ce1049 --- /dev/null +++ b/src/main/java/codechicken/lib/util/CCCodecs.java @@ -0,0 +1,36 @@ +package codechicken.lib.util; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.codecs.PrimitiveCodec; +import io.netty.buffer.Unpooled; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.connection.ConnectionType; + +/** + * Created by covers1624 on 7/26/26. + */ +public class CCCodecs { + + public static Codec embeddedPacket(RegistryAccess registryAccess) { + return new PrimitiveCodec<>() { + @Override + public DataResult read(DynamicOps ops, T input) { + return Codec.BYTE_BUFFER.read(ops, input) + .map(b -> new RegistryFriendlyByteBuf( + Unpooled.wrappedBuffer(b), + registryAccess, + ConnectionType.NEOFORGE + )); + } + + @Override + public T write(DynamicOps ops, RegistryFriendlyByteBuf buf) { + buf.readerIndex(0); + return Codec.BYTE_BUFFER.write(ops, buf.nioBuffer()); + } + }; + } +} From 467ea987db5c557d525061e36e149749663253df Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 26 Jul 2026 17:26:16 +0930 Subject: [PATCH 79/87] Remove CCRS hacks. --- src/main/java/codechicken/lib/render/CCRenderState.java | 8 +------- .../codechicken/lib/render/pipeline/CCRenderPipeline.java | 5 +---- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java index 50dbbca3..ed59f77a 100644 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ b/src/main/java/codechicken/lib/render/CCRenderState.java @@ -79,12 +79,6 @@ public class CCRenderState { */ public LightMatrix lightMatrix = new LightMatrix(); - // TODO, REALLY SERIOUSLY NUKE THIS. - // This was added as a workaround for Multipart to actually seriously disable the lighting engine, - // when building BakedQuads for parts which don't do it themselves. - @Deprecated (forRemoval = true) - public boolean hackyReallyDontComputeLighting; - //vertex outputs public final Vertex5 vert = new Vertex5(); public final Vector3 normal = new Vector3(); @@ -194,7 +188,7 @@ public void bind(RenderType renderType, MultiBufferSource getter, Matrix4 mat) { public void reset() { model = null; pipeline.reset(); - computeLighting = !hackyReallyDontComputeLighting; + computeLighting = true; colour = baseColour = alphaOverride = -1; } diff --git a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java index d0b79999..43497135 100644 --- a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java +++ b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java @@ -13,9 +13,6 @@ public class CCRenderPipeline { private final CCRenderState renderState; - @Deprecated//Hack removed. - public boolean forceFormatAttributes = true; - private final List> attribs = new ArrayList<>(); private final List ops = new ArrayList<>(); private final List nodes = new ArrayList<>(); @@ -57,7 +54,7 @@ public void rebuild() { if (renderState.fmt.contains(VertexFormatElement.COLOR)) { addAttribute(renderState.colourAttrib); } - if (renderState.computeLighting && !renderState.hackyReallyDontComputeLighting) { + if (renderState.computeLighting) { addAttribute(renderState.lightingAttrib); } From dd3bf088417a6c654debd32cea2ca9359e30186c Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 26 Jul 2026 20:26:47 +0930 Subject: [PATCH 80/87] Add some utilities for helping with dynamic models. --- .../codechicken/lib/model/DynamicModel.java | 47 +++++++++++++++++++ .../lib/model/DynamicallyBakedModel.java | 46 ++++++++++++++++++ .../render/buffer/BakedQuadVertexBuilder.java | 33 ++++++++++++- .../lib/render/model/OBJParser.java | 21 +++------ .../codechicken/lib/util/ResourceUtils.java | 2 +- .../lib/render/model/OBJParserTests.java | 4 +- 6 files changed, 133 insertions(+), 20 deletions(-) create mode 100644 src/main/java/codechicken/lib/model/DynamicModel.java create mode 100644 src/main/java/codechicken/lib/model/DynamicallyBakedModel.java diff --git a/src/main/java/codechicken/lib/model/DynamicModel.java b/src/main/java/codechicken/lib/model/DynamicModel.java new file mode 100644 index 00000000..f9ce528e --- /dev/null +++ b/src/main/java/codechicken/lib/model/DynamicModel.java @@ -0,0 +1,47 @@ +package codechicken.lib.model; + +import net.covers1624.quack.util.CrashLock; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.ResourceManagerReloadListener; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.AddClientReloadListenersEvent; + +/** + * Created by covers1624 on 7/26/26. + */ +public abstract class DynamicModel { + + private final CrashLock LOCK = new CrashLock("Already Initialized."); + + protected Identifier identifier; + + public DynamicModel(Identifier identifier) { + this.identifier = identifier; + } + + public void register(IEventBus modBus) { + LOCK.lock(); + + modBus.addListener(AddClientReloadListenersEvent.class, event -> event.addListener(identifier, new ReloadListener())); + } + + /** + * Called to reload your model. + * + * @param resourceManager The resource manager. + */ + protected abstract void reload(ResourceManager resourceManager); + + protected void clear() { + } + + private class ReloadListener implements ResourceManagerReloadListener { + + @Override + public void onResourceManagerReload(ResourceManager resourceManager) { + clear(); + DynamicModel.this.reload(resourceManager); + } + } +} diff --git a/src/main/java/codechicken/lib/model/DynamicallyBakedModel.java b/src/main/java/codechicken/lib/model/DynamicallyBakedModel.java new file mode 100644 index 00000000..dc204a18 --- /dev/null +++ b/src/main/java/codechicken/lib/model/DynamicallyBakedModel.java @@ -0,0 +1,46 @@ +package codechicken.lib.model; + +import net.minecraft.client.renderer.block.model.BlockModelPart; +import net.minecraft.resources.Identifier; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A simple cache around some dynamically loaded model. + *

    + * Created by covers1624 on 7/26/26. + */ +public abstract class DynamicallyBakedModel extends DynamicModel { + + private final Map> parts = new ConcurrentHashMap<>(); + + public DynamicallyBakedModel(Identifier identifier) { + super(identifier); + } + + /** + * Collect this models parts. + * + * @param state The model state. + * @param output The parts to add to. + */ + public final void collect(S state, List output) { + output.addAll(parts.computeIfAbsent(state, this::bake)); + } + + /** + * Called to bake your model into parts. + * + * @param state The state. + * @return The baked parts. + */ + protected abstract List bake(S state); + + @Override + protected void clear() { + super.clear(); + parts.clear(); + } +} diff --git a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java index c2785cdc..943c8cbe 100644 --- a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java +++ b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java @@ -5,6 +5,8 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.QuadCollection; +import net.minecraft.core.Direction; import net.minecraft.util.ARGB; import java.util.ArrayList; @@ -109,9 +111,36 @@ private void endPrevVertex() { } } - public List bake() { + private List finish() { endPrevVertex(); vertex = -1; - return new ArrayList<>(quadList); + return quadList; + } + + public List getQuads() { + return new ArrayList<>(finish()); + } + + /** + * Add all quads as culled on the specified face. + */ + public void getAsCulled(QuadCollection.Builder builder, Direction face) { + finish().forEach(e -> builder.addCulledFace(face, e)); + } + + /** + * Add all quads as culled, based on the orientation of the quad. + *

    + * Does not check if the quad lies on its face. + */ + public void getAsCulled(QuadCollection.Builder builder) { + finish().forEach(e -> builder.addCulledFace(e.direction(), e)); + } + + /** + * Add all the quads to the builder as unculled. + */ + public void getAsUnculled(QuadCollection.Builder builder) { + finish().forEach(builder::addUnculledFace); } } diff --git a/src/main/java/codechicken/lib/render/model/OBJParser.java b/src/main/java/codechicken/lib/render/model/OBJParser.java index bf302860..6d36269c 100644 --- a/src/main/java/codechicken/lib/render/model/OBJParser.java +++ b/src/main/java/codechicken/lib/render/model/OBJParser.java @@ -19,31 +19,27 @@ public class OBJParser { private final Identifier location; - @Nullable - private ResourceProvider provider; + private final ResourceProvider provider; private VertexFormat.Mode vertexMode = VertexFormat.Mode.TRIANGLES; @Nullable private Transformation coordSystem; private boolean ignoreMtl; /** - * Create a new instance of an OBJParser for a nice builder-like structure. - * * @param location The {@link Identifier} of the OBJ. */ + // TODO should we deprecate this and stop promoting blindly reading obj models statically? public OBJParser(Identifier location) { - this.location = location; + this(Minecraft.getInstance().getResourceManager(), location); } /** - * Set the {@link ResourceProvider} used to locate assets. - * - * @param provider The {@link ResourceProvider}. - * @return The same parser. + * @param provider The {@link ResourceProvider} to load from. + * @param location The {@link Identifier} of the OBJ. */ - public OBJParser provider(ResourceProvider provider) { + public OBJParser(ResourceProvider provider, Identifier location) { + this.location = location; this.provider = provider; - return this; } /** @@ -106,9 +102,6 @@ public OBJParser ignoreMtl() { * @return The parsed models. */ public Map parse() { - if (provider == null) { - provider = Minecraft.getInstance().getResourceManager(); - } return parse(provider, location, vertexMode, coordSystem, ignoreMtl); } diff --git a/src/main/java/codechicken/lib/util/ResourceUtils.java b/src/main/java/codechicken/lib/util/ResourceUtils.java index 646fce53..fe0d592e 100644 --- a/src/main/java/codechicken/lib/util/ResourceUtils.java +++ b/src/main/java/codechicken/lib/util/ResourceUtils.java @@ -60,7 +60,7 @@ public static List loadResource(ResourceProvider resourceProvider, Ident return reader.lines().toList(); } } catch (IOException ex) { - throw new RuntimeException("Failed to load MTL file: " + loc, ex); + throw new RuntimeException("Failed to load resource: " + loc, ex); } } } diff --git a/src/test/java/codechicken/lib/render/model/OBJParserTests.java b/src/test/java/codechicken/lib/render/model/OBJParserTests.java index a9a858b7..98c0d455 100644 --- a/src/test/java/codechicken/lib/render/model/OBJParserTests.java +++ b/src/test/java/codechicken/lib/render/model/OBJParserTests.java @@ -7,7 +7,6 @@ import org.junit.jupiter.api.Test; import java.util.Map; -import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -46,8 +45,7 @@ public void testGroupObject() { @Test public void testMultiObject() { - Map modelMap = new OBJParser(Identifier.parse("test:model/test_multi_object.obj")) - .provider(TestResourceProvider.INSTANCE) + Map modelMap = new OBJParser(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test_multi_object.obj")) .ignoreMtl() .quads() .parse(); From f1e90e18c07b7a0f8175f20f2b259370c06d271a Mon Sep 17 00:00:00 2001 From: covers1624 Date: Sun, 26 Jul 2026 20:27:25 +0930 Subject: [PATCH 81/87] Add some utilities for helping with item model extents. --- .../lib/render/ExtentsContainer.java | 36 +++++++++++++++++++ .../java/codechicken/lib/vec/Cuboid6.java | 5 +++ 2 files changed, 41 insertions(+) create mode 100644 src/main/java/codechicken/lib/render/ExtentsContainer.java diff --git a/src/main/java/codechicken/lib/render/ExtentsContainer.java b/src/main/java/codechicken/lib/render/ExtentsContainer.java new file mode 100644 index 00000000..6d5f1695 --- /dev/null +++ b/src/main/java/codechicken/lib/render/ExtentsContainer.java @@ -0,0 +1,36 @@ +package codechicken.lib.render; + +import codechicken.lib.render.buffer.ExtentsConsumer; +import codechicken.lib.vec.Cuboid6; +import com.mojang.blaze3d.vertex.VertexConsumer; +import org.joml.Vector3fc; +import org.jspecify.annotations.Nullable; + +import java.util.function.Consumer; + +/** + * Created by covers1624 on 7/26/26. + */ +public final class ExtentsContainer { + + private @Nullable Cuboid6 extents; + + public void visitExtents(Consumer extents, Consumer cons) { + var box = get(cons); + extents.accept(box.min.vector3f()); + extents.accept(box.max.vector3f()); + } + + public Cuboid6 get(Consumer extentsBuilder) { + if (extents == null) { + Cuboid6 box = new Cuboid6(); + extentsBuilder.accept(new ExtentsConsumer(box::enclose)); + extents = box; + } + return extents; + } + + public void reset() { + extents = null; + } +} diff --git a/src/main/java/codechicken/lib/vec/Cuboid6.java b/src/main/java/codechicken/lib/vec/Cuboid6.java index 8a866d70..d8517ce9 100644 --- a/src/main/java/codechicken/lib/vec/Cuboid6.java +++ b/src/main/java/codechicken/lib/vec/Cuboid6.java @@ -13,6 +13,7 @@ import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; +import org.joml.Vector3fc; import java.math.BigDecimal; import java.math.MathContext; @@ -217,6 +218,10 @@ public Cuboid6 enclose(Vector3 vec) { return enclose(vec.x, vec.y, vec.z, vec.x, vec.y, vec.z); } + public Cuboid6 enclose(Vector3fc vec) { + return enclose(vec.x(), vec.y(), vec.z(), vec.x(), vec.y(), vec.z()); + } + public Cuboid6 enclose(Cuboid6 c) { return enclose(c.min.x, c.min.y, c.min.z, c.max.x, c.max.y, c.max.z); } From 2fa08644d6e5786f0c0dbf126bdf9f897b51ae07 Mon Sep 17 00:00:00 2001 From: MrTJP Date: Tue, 6 Oct 2026 09:18:33 -0400 Subject: [PATCH 82/87] BakedQuadVertexBuilder bug fix and shading option (#476) * Fix ARGB order in BakedQuadVertexBuilder * Add shade/ao options in BakedQuadVertexBuilder --- .../render/buffer/BakedQuadVertexBuilder.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java index 943c8cbe..c7a62fa9 100644 --- a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java +++ b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java @@ -22,6 +22,9 @@ public class BakedQuadVertexBuilder implements VertexConsumer, ISpriteAwareVerte private final List quadList = new ArrayList<>(); private final VertexFormat.Mode mode; + private boolean shade = false; + private boolean ambientOcclusion = true; + private final Quad current = new Quad(); private int vertex = -1; @@ -38,9 +41,19 @@ public BakedQuadVertexBuilder(VertexFormat.Mode mode) { public void reset() { quadList.clear(); + shade = false; + ambientOcclusion = true; vertex = -1; } + public void setShade(boolean shade) { + this.shade = shade; + } + + public void setAmbientOcclusion(boolean ambientOcclusion) { + this.ambientOcclusion = ambientOcclusion; + } + @Override public void sprite(TextureAtlasSprite sprite) { current.sprite = sprite; @@ -61,7 +74,7 @@ public VertexConsumer setColor(int color) { @Override public VertexConsumer setColor(int red, int green, int blue, int alpha) { - setColor(ARGB.color(red, green, blue, alpha)); + setColor(ARGB.color(alpha, red, green, blue)); return this; } @@ -106,6 +119,8 @@ private void endPrevVertex() { throw new IllegalStateException("Sprite not set."); } current.calculateOrientation(false); + current.shade = shade; + current.ambientOcclusion = ambientOcclusion; quadList.add(current.bake()); vertex = 0; } From 356ce8367706f38cec5762b116ab6abe8f37c430 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Tue, 6 Oct 2026 11:36:21 +1030 Subject: [PATCH 83/87] Hoist TransformationList.compile up to Transformation. --- src/main/java/codechicken/lib/vec/Matrix4.java | 5 +++++ src/main/java/codechicken/lib/vec/Transformation.java | 6 ++++++ src/main/java/codechicken/lib/vec/TransformationList.java | 1 + .../java/codechicken/lib/vec/VariableTransformation.java | 5 +++++ 4 files changed, 17 insertions(+) diff --git a/src/main/java/codechicken/lib/vec/Matrix4.java b/src/main/java/codechicken/lib/vec/Matrix4.java index 42d4443c..271e94e8 100644 --- a/src/main/java/codechicken/lib/vec/Matrix4.java +++ b/src/main/java/codechicken/lib/vec/Matrix4.java @@ -565,6 +565,11 @@ public static Vector3 gluProject(Vector3 obj, Matrix4 modelMatrix, Matrix4 projM return winPos; } + @Override + public Matrix4 compile() { + return copy(); + } + @Override public void apply(Matrix4 mat) { mat.multiply(this); diff --git a/src/main/java/codechicken/lib/vec/Transformation.java b/src/main/java/codechicken/lib/vec/Transformation.java index c511671b..9a1c3558 100644 --- a/src/main/java/codechicken/lib/vec/Transformation.java +++ b/src/main/java/codechicken/lib/vec/Transformation.java @@ -32,6 +32,12 @@ public TransformationList with(Transformation t) { return new TransformationList(this, t); } + public Matrix4 compile() { + Matrix4 mat = new Matrix4(); + apply(mat); + return mat; + } + @Override public boolean load(CCRenderState ccrs) { ccrs.pipeline.addRequirement(ccrs.normalAttrib.operationID()); diff --git a/src/main/java/codechicken/lib/vec/TransformationList.java b/src/main/java/codechicken/lib/vec/TransformationList.java index 00194bbf..5064d73d 100644 --- a/src/main/java/codechicken/lib/vec/TransformationList.java +++ b/src/main/java/codechicken/lib/vec/TransformationList.java @@ -39,6 +39,7 @@ public TransformationList(TransformationList other) { mat = other.mat; } + @Override public Matrix4 compile() { if (mat == null) { mat = new Matrix4(); diff --git a/src/main/java/codechicken/lib/vec/VariableTransformation.java b/src/main/java/codechicken/lib/vec/VariableTransformation.java index 5cc37cdc..e935b0a1 100644 --- a/src/main/java/codechicken/lib/vec/VariableTransformation.java +++ b/src/main/java/codechicken/lib/vec/VariableTransformation.java @@ -18,6 +18,11 @@ public void apply(Matrix4 mat) { mat.multiply(this.mat); } + @Override + public Matrix4 compile() { + return mat.copy(); + } + @Override public Transformation copy() { return this; From 8dd870b23b0385333be78b07064797a8b30abb93 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Tue, 6 Oct 2026 11:37:02 +1030 Subject: [PATCH 84/87] Fix submitBorderFill applying flipping the border and fill colors. --- .../java/codechicken/lib/gui/render/GuiGraphicsExtension.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java b/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java index eb0407d6..63bb6398 100644 --- a/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java +++ b/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java @@ -111,8 +111,8 @@ private GuiGraphics self() { x0, x1, y0, y1, border, - fillColor, - borderColor + borderColor, + fillColor ) ); } From 81a43f5dcd7538199e5b4d80196e4548b75fc4c3 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Tue, 6 Oct 2026 11:37:36 +1030 Subject: [PATCH 85/87] Fix gui sprites using the wrong sheet ids. --- .../codechicken/lib/gui/modular/SpriteSupplier.java | 5 +++-- .../lib/gui/modular/elements/GuiSlots.java | 12 +++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java b/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java index 1818b77a..f3ab8c22 100644 --- a/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java +++ b/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java @@ -2,6 +2,7 @@ import com.google.common.base.Suppliers; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Sheets; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.Material; import net.minecraft.data.AtlasIds; @@ -36,7 +37,7 @@ default void ifPresent(Consumer cons) { } static SpriteSupplier gui(Identifier spriteLoc) { - return of(AtlasIds.GUI, spriteLoc); + return of(Sheets.GUI_SHEET, spriteLoc); } static SpriteSupplier of(Identifier atlasLoc, Identifier spriteLoc) { @@ -45,7 +46,7 @@ static SpriteSupplier of(Identifier atlasLoc, Identifier spriteLoc) { } static SpriteSupplier gui(Supplier sup) { - return of(() -> new Material(AtlasIds.GUI, sup.get())); + return of(() -> new Material(Sheets.GUI_SHEET, sup.get())); } static SpriteSupplier of(Supplier sup) { diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java index 934e691b..fee6ad0b 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -12,6 +12,8 @@ import net.covers1624.quack.collection.FastStream; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.Sheets; +import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.data.AtlasIds; import net.minecraft.resources.Identifier; import net.minecraft.world.inventory.Slot; @@ -37,12 +39,12 @@ public class GuiSlots extends GuiElement implements BackgroundRender { public static final SpriteSupplier[] ARMOR_SLOTS = new SpriteSupplier[] { - SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_helmet")), - SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_chestplate")), - SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_leggings")), - SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_boots")) + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_helmet")), + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_chestplate")), + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_leggings")), + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_boots")) }; - public static final SpriteSupplier OFF_HAND_SLOT = SpriteSupplier.of(AtlasIds.ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_shield")); + public static final SpriteSupplier OFF_HAND_SLOT = SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_shield")); private final int firstSlot; private final int slotCount; From ad1a7e43875e029f9cb93c2d81f9c859e5b6f3a8 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Tue, 6 Oct 2026 11:37:55 +1030 Subject: [PATCH 86/87] Add configureLabel to GuiButton. --- .../codechicken/lib/gui/modular/elements/GuiButton.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java index d16ccf3b..1e867d06 100644 --- a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java @@ -15,6 +15,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -169,6 +170,13 @@ public GuiButton setLabel(@Nullable GuiText label) { return label; } + public GuiButton configureLabel(Consumer configure) { + if (label != null) { + configure.accept(label); + } + return this; + } + /** * By default, hover time is reset when button is pressed. * THis allows you to disable that functionality to the tooltip will remain open when button is pressed. From 70d056d6862540198a965a3cba55124dd7fdc072 Mon Sep 17 00:00:00 2001 From: covers1624 Date: Wed, 4 Nov 2026 23:31:31 +1030 Subject: [PATCH 87/87] Split client packet registrations in StreamNetworkChannel. --- .../java/codechicken/lib/CodeChickenLib.java | 7 +- .../codechicken/lib/internal/CCLNetwork.java | 24 +-- .../lib/internal/CCLNetworkClient.java | 26 +++ .../codechicken/lib/internal/ClientInit.java | 2 + .../lib/packet/StreamNetworkChannel.java | 175 +++++++++++++----- 5 files changed, 170 insertions(+), 64 deletions(-) create mode 100644 src/main/java/codechicken/lib/internal/CCLNetworkClient.java diff --git a/src/main/java/codechicken/lib/CodeChickenLib.java b/src/main/java/codechicken/lib/CodeChickenLib.java index 31fc2709..10a8ea3e 100644 --- a/src/main/java/codechicken/lib/CodeChickenLib.java +++ b/src/main/java/codechicken/lib/CodeChickenLib.java @@ -37,9 +37,6 @@ public CodeChickenLib(ModContainer container, IEventBus modBus) { .path(Paths.get("config/ccl.cfg")) .load(); - if (FMLEnvironment.getDist().isClient()) { - ClientInit.init(modBus); - } ConfigSyncManager.init(modBus); @@ -48,5 +45,9 @@ public CodeChickenLib(ModContainer container, IEventBus modBus) { TileChunkLoadHook.init(); // ConditionalIngredient.Serializer.init(); DataGenerators.init(modBus); + + if (FMLEnvironment.getDist().isClient()) { + ClientInit.init(modBus); + } } } diff --git a/src/main/java/codechicken/lib/internal/CCLNetwork.java b/src/main/java/codechicken/lib/internal/CCLNetwork.java index 2511cb8e..e264f5fc 100644 --- a/src/main/java/codechicken/lib/internal/CCLNetwork.java +++ b/src/main/java/codechicken/lib/internal/CCLNetwork.java @@ -4,6 +4,8 @@ import codechicken.lib.config.ConfigSyncManager; import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; import codechicken.lib.packet.StreamNetworkChannel; +import codechicken.lib.packet.StreamNetworkChannel.BidirectionalPacketHandle; +import codechicken.lib.packet.StreamNetworkChannel.ConfigurationPacketHandle; import codechicken.lib.render.particle.CustomParticleHandler; import net.minecraft.network.RegistryFriendlyByteBuf; import net.neoforged.bus.api.IEventBus; @@ -17,24 +19,16 @@ */ public class CCLNetwork { - public static final StreamNetworkChannel CHANNEL = new StreamNetworkChannel(MOD_ID) + protected static final StreamNetworkChannel CHANNEL = new StreamNetworkChannel(MOD_ID) .optional(); - public static final StreamNetworkChannel.BidirectionalPacketHandle GUI_SYNC = CHANNEL.playBidirectional("gui_sync", - ModularGuiContainerMenu::handlePacketFromClient, - ModularGuiContainerMenu::handlePacketFromServer - ); + public static final BidirectionalPacketHandle GUI_SYNC = CHANNEL.playBidirectional("gui_sync", ModularGuiContainerMenu::handlePacketFromClient); + public static final BidirectionalPacketHandle TILE_MESSAGE = CHANNEL.playBidirectional("tile_message", CCLNetwork::handleTileMessageServer); - public static final StreamNetworkChannel.BidirectionalPacketHandle TILE_MESSAGE = CHANNEL.playBidirectional( - "tile_message", - CCLNetwork::handleTileMessageServer, - CCLNetwork::handleTileMessageClient - ); + public static final ConfigurationPacketHandle CONFIG_SYNC = CHANNEL.configurationToClient("config_sync", ConfigSyncManager.ConfigSyncConfigurationTask::new); public static void init(IEventBus modBus, ModContainer container) { CHANNEL.init(modBus, container); - - CHANNEL.configurationToClient("config_sync", ConfigSyncManager.ConfigSyncConfigurationTask::new, ConfigSyncManager::readSyncPacket); } private static void handleTileMessageServer(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { @@ -42,10 +36,4 @@ private static void handleTileMessageServer(RegistryFriendlyByteBuf packet, IPay tile.onInternalServerPacket(packet, ctx); } } - - private static void handleTileMessageClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { - if (ctx.player().level().getBlockEntity(packet.readBlockPos()) instanceof ModularBlockEntity tile) { - tile.onInternalClientPacket(packet, ctx); - } - } } diff --git a/src/main/java/codechicken/lib/internal/CCLNetworkClient.java b/src/main/java/codechicken/lib/internal/CCLNetworkClient.java new file mode 100644 index 00000000..6c0cdd26 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/CCLNetworkClient.java @@ -0,0 +1,26 @@ +package codechicken.lib.internal; + +import codechicken.lib.block.ModularBlockEntity; +import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; + +/** + * Created by covers1624 on 11/4/26. + */ +public class CCLNetworkClient extends CCLNetwork { + + public static void initClient() { + CHANNEL.assignClientHandler(GUI_SYNC, ModularGuiContainerMenu::handlePacketFromServer); + CHANNEL.assignClientHandler(TILE_MESSAGE, CCLNetworkClient::handleTileMessageClient); + + CHANNEL.assignClientHandler(CONFIG_SYNC, ConfigSyncManager::readSyncPacket); + } + + private static void handleTileMessageClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + if (ctx.player().level().getBlockEntity(packet.readBlockPos()) instanceof ModularBlockEntity tile) { + tile.onInternalClientPacket(packet, ctx); + } + } +} diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java index 772b197b..08a12f99 100644 --- a/src/main/java/codechicken/lib/internal/ClientInit.java +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -24,6 +24,8 @@ public class ClientInit { public static void init(IEventBus modBus) { LOCK.lock(); + CCLNetworkClient.initClient(); + loadClientConfig(); CCRenderEventHandler.init(); HighlightHandler.init(); diff --git a/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java b/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java index 0d86ab11..dc87533d 100644 --- a/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java +++ b/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java @@ -17,19 +17,23 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.ModContainer; +import net.neoforged.fml.loading.FMLEnvironment; import net.neoforged.neoforge.network.configuration.ICustomConfigurationTask; import net.neoforged.neoforge.network.connection.ConnectionType; import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent; import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; import net.neoforged.neoforge.network.handling.IPayloadContext; -import net.neoforged.neoforge.network.registration.PayloadRegistrar; +import net.neoforged.neoforge.network.handling.IPayloadHandler; +import net.neoforged.neoforge.network.handling.MainThreadPayloadHandler; +import net.neoforged.neoforge.network.registration.HandlerThread;import net.neoforged.neoforge.network.registration.PayloadRegistrar; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.BiFunction; -import java.util.function.Function; + +import static java.util.Objects.requireNonNull; /** * A simple Stream based network channel, very similar to the NeoForge api, however @@ -81,15 +85,15 @@ public StreamNetworkChannel optional() { /** * Register a packet to be set to the client during gameplay. + *

    + * The packet handle must be assigned via {@link #assignClientHandler} on the client-side only. * - * @param name The name of the packet. - * @param handler The handler for the packet. - * @return A hande to construct packets. + * @param name The name of the packet. + * @return A handle to construct packets. + * @see #assignClientHandler(ClientPacketHandle, PlayHandler) */ - public ClientPacketHandle playToClient(String name, PlayHandler handler) { - var type = createType("play", name, PlayPacketType::new); - type.clientHandler = handler; - return type; + public ClientPacketHandle playToClient(String name) { + return createType("play", name, PacketKind.CLIENT_HANDLED, PlayPacketType::new); } /** @@ -97,38 +101,77 @@ public ClientPacketHandle playToClient(String name, PlayHandler handler) { * * @param name The name of the packet. * @param handler The handler for the packet. - * @return A hande to construct packets. + * @return A handle to construct packets. */ public ServerPacketHandle playToServer(String name, PlayHandler handler) { - var type = createType("play", name, PlayPacketType::new); + var type = createType("play", name, PacketKind.SERVER_HANDLED, PlayPacketType::new); type.serverHandler = handler; return type; } /** * Register a packet to be set to either the client or the server during gameplay. + *

    + * The packet's client handle must be assigned via {@link #assignClientHandler} on the client-side only. * * @param name The name of the packet. * @param serverHandler The handler for the packet server-side. - * @param clientHandler The handler for the packet client-side. - * @return A hande to construct packets. + * @return A handle to construct packets. + * @see #assignClientHandler(ClientPacketHandle, PlayHandler) */ - public BidirectionalPacketHandle playBidirectional(String name, PlayHandler serverHandler, PlayHandler clientHandler) { - var type = createType("play", name, PlayPacketType::new); - type.clientHandler = clientHandler; + public BidirectionalPacketHandle playBidirectional(String name, PlayHandler serverHandler) { + var type = createType("play", name, PacketKind.BI_DIRECTIONAL, PlayPacketType::new); type.serverHandler = serverHandler; return type; } + /** + * Assign the client-side handler for a packet. + * + * @param handle The packet handle to attach to. + * @param handler The handler. + */ + public void assignClientHandler(ClientPacketHandle handle, PlayHandler handler) { + // ClientPacketHandle is sealed. + var packet = ((PlayPacketType) handle); + // Technically possible with whacky casts. + if (packet.kind != PacketKind.CLIENT_HANDLED && packet.kind != PacketKind.BI_DIRECTIONAL) { + throw new IllegalStateException("Server packets can't have client handlers."); + } + if (packet.clientHandler != null) { + throw new IllegalArgumentException("Client handler already assigned for packet. " + packet.type.id()); + } + + packet.clientHandler = requireNonNull(handler); + } + /** * Register a packet to configure a connecting client. * * @param name The name of the packet. * @param factory The factory to construct a {@link ICustomConfigurationTask}. - * @param handler The handler for the packet client-side. + * @return The packet handle. + */ + public ConfigurationPacketHandle configurationToClient(String name, ConfigurationTaskFactory factory) { + return createType("configuration", name, PacketKind.CLIENT_HANDLED, (id, kind) -> new ConfigurationPacketType(id, kind, factory)); + } + + /** + * Assign the client-side handler for a configuration task packet. + * + * @param handle The packet handle to attach to. + * @param handler The handler. */ - public void configurationToClient(String name, ConfigurationTaskFactory factory, ConfigurationHandler handler) { - createType("configuration", name, id -> new ConfigurationPacketType(id, factory, handler)); + public void assignClientHandler(ConfigurationPacketHandle handle, ConfigurationHandler handler) { + var packet = ((ConfigurationPacketType) handle); + if (packet.kind != PacketKind.CLIENT_HANDLED && packet.kind != PacketKind.BI_DIRECTIONAL) { + throw new IllegalStateException("Server packets can't have client handlers."); + } + + if (packet.handler != null) { + throw new IllegalArgumentException("Handler already assigned for packet. " + packet.type.id()); + } + packet.handler = requireNonNull(handler); } // region Events @@ -150,11 +193,11 @@ private void onGameConfigurationEvent(RegisterConfigurationTasksEvent event) { } // endregion - private > T createType(String phase, String name, Function func) { - var id = makeId("play", name); + private > T createType(String phase, String name, PacketKind kind, BiFunction func) { + var id = makeId(phase, name); if (packets.containsKey(id)) throw new IllegalArgumentException("Packet with name " + name + " for the " + phase + " phase is already registered."); - var type = func.apply(id); + var type = func.apply(id, kind); packets.put(id, type); return type; } @@ -177,25 +220,54 @@ private PacketType(Identifier id) { private static final class PlayPacketType extends PacketType implements BidirectionalPacketHandle { + private final PacketKind kind; private @Nullable PlayHandler clientHandler; private @Nullable PlayHandler serverHandler; - private PlayPacketType(Identifier id) { + private PlayPacketType(Identifier id, PacketKind kind) { super(id); + this.kind = kind; + } + + private IPayloadHandler clientHandler() { + if (clientHandler == null) { + throw new IllegalStateException("Packet " + type.id() + " does not have a client handler assigned."); + } + + return clientHandler::accept; + } + + private IPayloadHandler serverHandler() { + // Should not be possible.. + if (serverHandler == null) { + throw new IllegalStateException("Packet " + type.id() + " does not have a server handler assigned."); + } + + return serverHandler::accept; } @Override public void register(PayloadRegistrar registrar) { var codec = StreamPacket.createCodec(type); - if (clientHandler != null && serverHandler != null) { - registrar.playBidirectional(type, codec, serverHandler::accept, clientHandler::accept); - } else if (clientHandler != null) { - registrar.playToClient(type, codec, clientHandler::accept); - } else if (serverHandler != null) { - registrar.playToServer(type, codec, serverHandler::accept); - } else { - throw new IllegalStateException("Expected clientHandler or serverHandler to be non-null? This should not actually be possible."); + switch (kind) { + case CLIENT_HANDLED -> { + if (FMLEnvironment.getDist().isClient()) { + registrar.playToClient(type, codec, clientHandler()); + } else { + registrar.playToClient(type, codec); + } + } + case SERVER_HANDLED -> registrar.playToServer(type, codec, serverHandler()); + case BI_DIRECTIONAL -> { + if (FMLEnvironment.getDist().isClient()) { + if (FMLEnvironment.getDist().isClient()) { + registrar.playBidirectional(type, codec, serverHandler(), clientHandler()); + } else { + registrar.playBidirectional(type, codec, serverHandler()); + } + } + } } } @@ -220,28 +292,37 @@ public StreamPacket.ToServer toServer() { } } - private static final class ConfigurationPacketType extends PacketType { + private static final class ConfigurationPacketType extends PacketType implements ConfigurationPacketHandle { + private final PacketKind kind; public final ConfigurationTask.Type configurationType; private final ConfigurationTaskFactory factory; - private final ConfigurationHandler handler; + private @Nullable ConfigurationHandler handler; - private ConfigurationPacketType(Identifier id, ConfigurationTaskFactory factory, ConfigurationHandler handler) { + private ConfigurationPacketType(Identifier id, PacketKind kind, ConfigurationTaskFactory factory) { super(id); + this.kind = kind; this.factory = factory; - this.handler = handler; configurationType = new ConfigurationTask.Type(type.id()); } + private IPayloadHandler handler() { + if (handler == null) { + throw new IllegalStateException("Packet " + type.id() + " does not have a handler assigned."); + } + + return handler::accept; + } + @Override public void register(PayloadRegistrar registrar) { var codec = ConfigurationStreamPacket.createCodec(type); - registrar.configurationToClient( - type, - codec, - handler::accept - ); + if (FMLEnvironment.getDist().isClient()) { + registrar.configurationToClient(type, codec, handler()); + } else { + registrar.configurationToClient(type, codec); + } } public ConfigurationTask getTask(ServerConfigurationPacketListener listener) { @@ -303,10 +384,12 @@ public interface ConfigurationContext { */ public interface ConfigurationTaskFactory extends BiFunction { } + public sealed interface ConfigurationPacketHandle { } + /** * A handle for constructing client-bound packets. */ - public interface ClientPacketHandle { + public sealed interface ClientPacketHandle { /** * Construct a packet bound for a client. @@ -360,7 +443,7 @@ default StreamPacket.ToClient toClient(Entity entity) { /** * A handle for constructing server-bound packets. */ - public interface ServerPacketHandle { + public sealed interface ServerPacketHandle { /** * Construct a packet bound for the server. @@ -373,5 +456,11 @@ public interface ServerPacketHandle { /** * A handle for constructing a packet bound for a client or the server. */ - public interface BidirectionalPacketHandle extends ClientPacketHandle, ServerPacketHandle { } + public sealed interface BidirectionalPacketHandle extends ClientPacketHandle, ServerPacketHandle { } + + private enum PacketKind { + CLIENT_HANDLED, + SERVER_HANDLED, + BI_DIRECTIONAL + } }

+ * Created by brandon3055 on 28/08/2023 + */ +public class Constraints { + + /** + * Bind an elements geometry to a reference element. + * + * @param element The element to be bound. + * @param reference The element to be bound to. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference) { + bind(element, reference, 0.0); + } + + /** + * Bind an elements geometry to a reference element with border offsets. (Border offsets may be positive or negative) + * + * @param element The element to be bound. + * @param reference The element to be bound to. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference, double borders) { + bind(element, reference, borders, borders, borders, borders); + } + + /** + * Bind an elements geometry to a reference element with border offsets. (Border offsets may be positive or negative) + * + * @param element The element to be bound. + * @param reference The element to be bound to. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference, double top, double left, double bottom, double right) { + element.constrain(TOP, relative(reference.get(TOP), top)); + element.constrain(LEFT, relative(reference.get(LEFT), left)); + element.constrain(BOTTOM, relative(reference.get(BOTTOM), -bottom)); + element.constrain(RIGHT, relative(reference.get(RIGHT), -right)); + } + + /** + * Bind an elements geometry to a reference element with border offsets. (Border offsets may be positive or negative) + * The border offsets are dynamic, meaning if the values stored in the {@link Borders} object are updated, this binding will reflect those changes automatically. + * + * @param element The element to be bound. + * @param reference The element to be bound to. + * @param borders Border offsets. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference, Borders borders) { + element.constrain(TOP, relative(reference.get(TOP), borders::top)); + element.constrain(LEFT, relative(reference.get(LEFT), borders::left)); + element.constrain(BOTTOM, relative(reference.get(BOTTOM), () -> -borders.bottom())); + element.constrain(RIGHT, relative(reference.get(RIGHT), () -> -borders.right())); + } + + + public static void size(ConstrainedGeometry element, double width, double height) { + element.constrain(WIDTH, literal(width)); + element.constrain(HEIGHT, literal(height)); + } + + public static void size(ConstrainedGeometry element, Supplier width, Supplier height) { + element.constrain(WIDTH, dynamic(width)); + element.constrain(HEIGHT, dynamic(height)); + } + + public static void pos(ConstrainedGeometry element, double left, double top) { + element.constrain(LEFT, literal(left)); + element.constrain(TOP, literal(top)); + } + + public static void pos(ConstrainedGeometry element, Supplier left, Supplier top) { + element.constrain(LEFT, dynamic(left)); + element.constrain(TOP, dynamic(top)); + } + + public static void center(ConstrainedGeometry element, ConstrainedGeometry centerOn) { + element.constrain(TOP, midPoint(centerOn.get(TOP), centerOn.get(BOTTOM), () -> element.ySize() / -2)); + element.constrain(LEFT, midPoint(centerOn.get(LEFT), centerOn.get(RIGHT), () -> element.xSize() / -2)); + } + + /** + * Constrain the specified element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + */ + public static void placeInside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position) { + placeInside(target, reference, position, 0, 0); + } + + /** + * Constrain the specified element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + public static void placeInside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position, double xOffset, double yOffset) { + switch (position) { + case TOP_LEFT -> target + .constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + case TOP_CENTER -> target + .constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); + case TOP_RIGHT -> target + .constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case MIDDLE_RIGHT -> target + .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_RIGHT -> target + .constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_CENTER -> target + .constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); + case BOTTOM_LEFT -> target + .constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + case MIDDLE_LEFT -> target + .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + } + } + + /** + * Constrain the specified element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + */ + public static void placeOutside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position) { + placeOutside(target, reference, position, 0, 0); + } + + /** + * Constrain the specified element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + public static void placeOutside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position, double xOffset, double yOffset) { + switch (position) { + case TOP_LEFT -> target + .constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + case TOP_CENTER -> target + .constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); + case TOP_RIGHT -> target + .constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case MIDDLE_RIGHT -> target + .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_RIGHT -> target + .constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_CENTER -> target + .constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (target.xSize() / -2) + xOffset)); + case BOTTOM_LEFT -> target + .constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + case MIDDLE_LEFT -> target + .constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (target.ySize() / -2) + yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + } + } + + public enum LayoutPos { + TOP_LEFT, + TOP_CENTER, + TOP_RIGHT, + MIDDLE_RIGHT, + MIDDLE_LEFT, + BOTTOM_RIGHT, + BOTTOM_CENTER, + BOTTOM_LEFT + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ContentElement.java b/src/main/java/codechicken/lib/gui/modular/lib/ContentElement.java new file mode 100644 index 00000000..6db976a5 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ContentElement.java @@ -0,0 +1,14 @@ +package codechicken.lib.gui.modular.lib; + + +import codechicken.lib.gui.modular.elements.GuiElement; + +/** + * Implemented by elements that have a separate child element to which content should be added. + * e.g. scroll element, manipulable element etc... + * Created by brandon3055 on 13/11/2023 + */ +public interface ContentElement> { + + T getContentElement(); +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java new file mode 100644 index 00000000..4ef4cd96 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java @@ -0,0 +1,100 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.CodeChickenLib; +import net.minecraft.client.Minecraft; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.Resource; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.BufferUtils; +import org.lwjgl.glfw.GLFW; +import org.lwjgl.glfw.GLFWImage; +import org.lwjgl.system.MemoryUtil; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * Created by brandon3055 on 11/5/20. + */ +public class CursorHelper { + public static final Logger LOGGER = LogManager.getLogger(); + + public static final ResourceLocation DRAG = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/drag.png"); + public static final ResourceLocation RESIZE_H = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_h.png"); + public static final ResourceLocation RESIZE_V = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_v.png"); + public static final ResourceLocation RESIZE_TRBL = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_trbl.png"); + public static final ResourceLocation RESIZE_TLBR = new ResourceLocation(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_tlbr.png"); + + private static final Map cursors = new HashMap<>(); + private static ResourceLocation active = null; + + private static long createCursor(ResourceLocation cursorTexture) { + try { + Resource resource = Minecraft.getInstance().getResourceManager().getResource(cursorTexture).orElse(null); + if (resource == null) return MemoryUtil.NULL; + BufferedImage bufferedimage = ImageIO.read(resource.open()); + GLFWImage glfwImage = imageToGLFWImage(bufferedimage); + return GLFW.glfwCreateCursor(glfwImage, 16, 16); + } catch (Exception e) { + LOGGER.warn("An error occurred while creating cursor", e); + } + return 0; + } + + private static GLFWImage imageToGLFWImage(BufferedImage image) { + if (image.getType() != BufferedImage.TYPE_INT_ARGB_PRE) { + final BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); + final Graphics2D graphics = convertedImage.createGraphics(); + final int targetWidth = image.getWidth(); + final int targetHeight = image.getHeight(); + graphics.drawImage(image, 0, 0, targetWidth, targetHeight, null); + graphics.dispose(); + image = convertedImage; + } + final ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4); + for (int i = 0; i < image.getHeight(); i++) { + for (int j = 0; j < image.getWidth(); j++) { + int colorSpace = image.getRGB(j, i); + buffer.put((byte) ((colorSpace << 8) >> 24)); + buffer.put((byte) ((colorSpace << 16) >> 24)); + buffer.put((byte) ((colorSpace << 24) >> 24)); + buffer.put((byte) (colorSpace >> 24)); + } + } + buffer.flip(); + final GLFWImage result = GLFWImage.create(); + result.set(image.getWidth(), image.getHeight(), buffer); + return result; + } + + public static void setCursor(@Nullable ResourceLocation cursor) { + if (cursor != active) { + active = cursor; + long window = Minecraft.getInstance().getWindow().getWindow(); + long newCursor = active == null ? 0 : cursors.computeIfAbsent(cursor, CursorHelper::createCursor); + GLFW.glfwSetCursor(window, newCursor); + } + } + + public static void resetCursor() { + if (active != null) { + setCursor(null); + } + } + + public static void onResourceReload() { + cursors.values().forEach(cursor -> { + if (cursor != MemoryUtil.NULL) { + GLFW.glfwDestroyCursor(cursor); + } + }); + cursors.clear(); + } +} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java b/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java new file mode 100644 index 00000000..aa15ddfa --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java @@ -0,0 +1,30 @@ +package codechicken.lib.gui.modular.lib; + +import net.minecraft.resources.ResourceLocation; + +import java.util.function.Function; + +/** + * Designed for use with DynamicTextureProvider + *