diff --git a/dependencies.gradle b/dependencies.gradle index 04d2dd05aba..13a83428d8c 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,7 +1,7 @@ dependencies { compileOnly(libs.jetbrains.annotations) - testJarJar(testApi(libs.testframework.get())) + testApi(libs.testframework.get()) jarJar(api(forge.ldlib.get())) @@ -30,6 +30,11 @@ dependencies { compileOnly(variantOf(forge.create) { classifier("slim") }) compileOnly(forge.flywheel.forge.api) + // Create + compileOnly(forge.ponder) + compileOnly(variantOf(forge.create) { classifier("slim") }) + compileOnly(forge.flywheel.forge.api) + // KJS compileOnly(forge.bundles.kjs) @@ -90,7 +95,7 @@ dependencies { extraLocalRuntime(forge.trenzalore) extraLocalRuntime(forge.curios) // extraLocalRuntime(forge.worldstripper) - localRuntime(forge.cc.tweaked.forge.impl) + extraLocalRuntime(forge.cc.tweaked.forge.impl) localRuntime(forge.bundles.kjs) diff --git a/gradle/forge.versions.toml b/gradle/forge.versions.toml index 2808d3fad9b..a681c5203d8 100644 --- a/gradle/forge.versions.toml +++ b/gradle/forge.versions.toml @@ -6,30 +6,38 @@ configuration = "3.1.1-neoforge" jei = "19.25.1.328" rei = "16.0.799" emi = "1.1.22+1.21.1" + ae2 = "19.2.8" + kubejs = "2101.7.2-build.336" rhino = "2101.2.7-build.81" architectury = "13.0.8" clothconfig = "15.0.140" -create = "6.0.8-168" -ponder = "1.0.64" -flywheel = "1.0.5" + curios = "9.4.2+1.21.1" kotlinforforge = "5.7.0" + journeyMapApi = "2.0.0-1.21.1-SNAPSHOT" ftblibrary = "2101.1.30" ftbteams = "2101.1.9" ftbquests = "2101.1.21" ftbchunks = "2101.1.14" -ccTweaked = "1.116.0" -resourcefullib = "3.0.12" + gamestages = "17.0.1" bookshelf = "21.1.56" + +ccTweaked = "1.116.0" + +resourcefullib = "3.0.12" # TODO update these once there's 1.21 versions argonauts = "1.2.4" # FIXME for some reason their maven only has versions up to 1.1.10? latest on modrinth is 1.1.13 heracles = "1.1.10" +create = "6.0.8-168" +ponder = "1.0.64" +flywheel = "1.0.5" + ## modrinth maven ## jade = "15.10.0+neoforge" sodium = "mc1.21.1-0.6.13-neoforge" @@ -46,7 +54,6 @@ journeyMap = "6383889" spark = "6225208" observable = "5733591" - [libraries] ldlib = { module = "com.lowdragmc.ldlib:ldlib-neoforge-1.21.1", version.ref = "ldlib" } registrate = { module = "com.tterrag.registrate:Registrate", version.ref = "registrate" } @@ -63,16 +70,15 @@ rei-neoforge = { module = "me.shedaniel:RoughlyEnoughItems-neoforge", ver emi = { module = "dev.emi:emi-neoforge", version.ref = "emi" } ae2 = { module = "org.appliedenergistics:appliedenergistics2", version.ref = "ae2" } + kubejs = { module = "dev.latvian.mods:kubejs-neoforge", version.ref = "kubejs" } rhino = { module = "dev.latvian.mods:rhino", version.ref = "rhino" } architectury = { module = "dev.architectury:architectury-neoforge", version.ref = "architectury" } clothconfig = { module = "me.shedaniel.cloth:cloth-config-neoforge", version.ref = "clothconfig" } -create = { module = "com.simibubi.create:create-1.21.1", version.ref = "create" } -ponder = { module = "net.createmod.ponder:Ponder-NeoForge-1.21.1", version.ref = "ponder"} -flywheel-forge-api = { module = "dev.engine-room.flywheel:flywheel-neoforge-api-1.21.1", version.ref = "flywheel"} -flywheel-forge = { module = "dev.engine-room.flywheel:flywheel-neoforge-1.21.1", version.ref = "flywheel"} + curios = { module = "top.theillusivec4.curios:curios-neoforge", version.ref = "curios" } kotlinforforge = { module = "thedarkcolour:kotlinforforge-neoforge", version.ref = "kotlinforforge" } + journeymap-api = { module = "info.journeymap:journeymap-api-neoforge", version.ref = "journeyMapApi" } ftblibrary = { module = "dev.ftb.mods:ftb-library-neoforge", version.ref = "ftblibrary" } ftbteams = { module = "dev.ftb.mods:ftb-teams-neoforge", version.ref = "ftbteams" } @@ -90,6 +96,11 @@ heracles = { module = "earth.terrarium.heracles:heracles-forge-1.20.1 # argonauts = { module = "earth.terrarium.odyssey_allies:odyssey_allies-neoforge-1.21.1`", version.ref = "argonauts" } # heracles = { module = "earth.terrarium.odyssey_quests:odyssey_quests-neoforge-1.21.1", version.ref = "heracles" } +create = { module = "com.simibubi.create:create-1.21.1", version.ref = "create" } +ponder = { module = "net.createmod.ponder:Ponder-NeoForge-1.21.1", version.ref = "ponder" } +flywheel-forge-api = { module = "dev.engine-room.flywheel:flywheel-neoforge-api-1.21.1", version.ref = "flywheel" } +flywheel-forge = { module = "dev.engine-room.flywheel:flywheel-neoforge-1.21.1", version.ref = "flywheel" } + jade = { module = "maven.modrinth:jade", version.ref = "jade" } sodium = { module = "maven.modrinth:sodium", version.ref = "sodium" } iris = { module = "maven.modrinth:iris", version.ref = "iris" } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index 2779f50e134..02c651e44df 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -9,14 +9,6 @@ java { withSourcesJar() } -// Use delombok'd files for sources -sourcesJar { - exclude { - sourceSets.main.allSource.contains it.file - } - from delombok -} - base { archivesName = "${project.name}-${libs.versions.minecraft.get()}" } diff --git a/src/main/java/com/gregtechceu/gtceu/api/GTValues.java b/src/main/java/com/gregtechceu/gtceu/api/GTValues.java index e9a1182ccd0..184e4860c33 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/GTValues.java +++ b/src/main/java/com/gregtechceu/gtceu/api/GTValues.java @@ -121,6 +121,7 @@ public static int[] tiersBetween(int minInclusive, int maxInclusive) { MODID_KUBEJS = "kubejs", MODID_IRIS = "iris", MODID_SODIUM = "sodium", + MODID_CREATE = "create", MODID_CURIOS = "curios", MODID_MODERNFIX = "modernfix", MODID_JOURNEYMAP = "journeymap", @@ -133,8 +134,7 @@ public static int[] tiersBetween(int minInclusive, int maxInclusive) { MODID_HERACLES = "heracles", MODID_GAMESTAGES = "gamestages", MODID_FTB_QUEST = "ftbquests", - MODID_CCTWEAKED = "computercraft", - MODID_CREATE = "create"; + MODID_CCTWEAKED = "computercraft"; /** * Spray painting compat modids diff --git a/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java b/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java index 0749e52e8f1..9220836888a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java +++ b/src/main/java/com/gregtechceu/gtceu/api/capability/ICoverable.java @@ -211,11 +211,11 @@ static boolean doesCoverCollide(Direction side, List collisionBox, d @Nullable static Direction rayTraceCoverableSide(ICoverable coverable, Player player) { - HitResult rayTrace = ToolHelper.getPlayerDefaultRaytrace(player); + BlockHitResult rayTrace = ToolHelper.getPlayerDefaultRaytrace(player); if (rayTrace.getType() != HitResult.Type.BLOCK) { return null; } - return traceCoverSide((BlockHitResult) rayTrace); + return traceCoverSide(rayTrace); } default boolean hasDynamicCovers() { diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java index a03284357eb..c045bfd7c7a 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/Material.java @@ -36,6 +36,7 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import dev.latvian.mods.rhino.util.HideFromJS; import dev.latvian.mods.rhino.util.RemapPrefixForJS; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; @@ -564,7 +565,7 @@ public int hashCode() { return Objects.hashCode(this.getResourceLocation()); } - @SuppressWarnings("UnusedReturnValue") + @SuppressWarnings({ "UnusedReturnValue", "unused" }) // API, need to treat all of these as used @RemapPrefixForJS("kjs$") public static class Builder { @@ -1835,6 +1836,7 @@ public Builder addDefaultEnchant(ResourceKey enchant, int level) { * * @return The finalized Material. */ + @HideFromJS public Material buildAndRegister() { materialInfo.componentList = composition.isEmpty() && this.compositionSupplier != null ? ImmutableList.copyOf(compositionSupplier.stream().map(MaterialStackWrapper::toMatStack) diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ArmorProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ArmorProperty.java index 4412ffe1fa0..3545e2ad171 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ArmorProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ArmorProperty.java @@ -175,6 +175,9 @@ public ArmorProperty.Builder protectionValues(Map prote return this; } + /** + * Set an Ingredient to use as the repair ingredient when repairing armors made of this Material in an Anvil. + */ public ArmorProperty.Builder repairIngredient(@Nullable Supplier repairIngredient) { if (repairIngredient == null) { armorProperty.repairIngredient = () -> null; @@ -216,10 +219,16 @@ public ArmorProperty.Builder dyeable(boolean dyeable) { return this; } + /** + * Set the texture layers for armor made of this Material. + */ public ArmorProperty.Builder layers(ArmorMaterial.Layer... layers) { return layers(Arrays.asList(layers)); } + /** + * Set the texture layers for armor made of this Material. + */ public ArmorProperty.Builder layers(List layers) { armorProperty.layers = layers; return this; diff --git a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java index 83201f7e028..1b8588fa640 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/chemical/material/properties/ToolProperty.java @@ -120,6 +120,7 @@ public class ToolProperty implements IMaterialProperty { /** * Enchantment to be applied to tools made from this Material. */ + @Getter private final Object2IntMap> enchantments = new Object2IntArrayMap<>(); public ToolProperty(float harvestSpeed, float attackDamage, int durability, int harvestLevel, GTToolType[] types) { @@ -141,10 +142,6 @@ public ToolProperty() { this(1.0F, 1.0F, 100, 2, GTToolType.getTypes().values().toArray(GTToolType[]::new)); } - public Object2IntMap> getEnchantments() { - return enchantments; - } - @Override public void verifyProperty(MaterialProperties properties) { if (!properties.hasProperty(PropertyKey.WOOD)) { diff --git a/src/main/java/com/gregtechceu/gtceu/data/pack/event/RegisterDynamicResourcesEvent.java b/src/main/java/com/gregtechceu/gtceu/api/data/pack/event/RegisterDynamicResourcesEvent.java similarity index 84% rename from src/main/java/com/gregtechceu/gtceu/data/pack/event/RegisterDynamicResourcesEvent.java rename to src/main/java/com/gregtechceu/gtceu/api/data/pack/event/RegisterDynamicResourcesEvent.java index 26dd884312f..4b866b5f786 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/pack/event/RegisterDynamicResourcesEvent.java +++ b/src/main/java/com/gregtechceu/gtceu/api/data/pack/event/RegisterDynamicResourcesEvent.java @@ -1,4 +1,4 @@ -package com.gregtechceu.gtceu.data.pack.event; +package com.gregtechceu.gtceu.api.data.pack.event; import net.neoforged.bus.api.Event; import net.neoforged.fml.event.IModBusEvent; diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternals.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternals.java new file mode 100644 index 00000000000..a1fc36791f8 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternals.java @@ -0,0 +1,99 @@ +/* + * Copyright 2022 QuiltMC + * Modified by the Steam 'n' Rails (Railways) team + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.config.ConfigHolder; + +import net.minecraft.SharedConstants; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.util.datafix.DataFixers; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixUtils; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.*; + +import java.util.function.BiFunction; + +import static com.google.common.base.Preconditions.checkArgument; + +@ApiStatus.Internal +public abstract class DataFixesInternals { + + public static final BiFunction BASE_SCHEMA = (version, parent) -> { + checkArgument(version == 0, "version must be 0"); + checkArgument(parent == null, "parent must be null"); + return get().createBaseSchema(); + }; + + public record DataFixerEntry(DataFixer dataFixer, int currentVersion) {} + + @Contract(pure = true) + @Range(from = 0, to = Integer.MAX_VALUE) + public static int getModDataVersion(@NotNull Dynamic compound) { + return compound.get("GTCEu_DataVersion").asInt(0); + } + + private static DataFixesInternals instance; + + public static @NotNull DataFixesInternals get() { + if (instance == null) { + // Init config in case it's not loaded yet + ConfigHolder.init(); + if (!ConfigHolder.INSTANCE.compat.doDatafixers) { + instance = new NoOpDataFixesInternals(); + return instance; + } + + Schema latestVanillaSchema; + try { + latestVanillaSchema = DataFixers.getDataFixer() + .getSchema(DataFixUtils + .makeKey(SharedConstants.getCurrentVersion().getDataVersion().getVersion())); + } catch (Exception e) { + latestVanillaSchema = null; + } + + if (latestVanillaSchema == null) { + GTCEu.LOGGER.warn("[GTCEuM DFU] Failed to initialize! Either someone stopped DFU from initializing,"); + GTCEu.LOGGER.warn("[GTCEuM DFU] or this Minecraft build is hosed."); + GTCEu.LOGGER.warn("[GTCEuM DFU] Using no-op implementation."); + instance = new NoOpDataFixesInternals(); + } else { + instance = new DataFixesInternalsImpl(latestVanillaSchema); + } + } + + return instance; + } + + public abstract void registerFixer(@Range(from = 0, to = Integer.MAX_VALUE) int currentVersion, + @NotNull DataFixer dataFixer); + + public abstract @Nullable DataFixerEntry getFixerEntry(); + + @Contract(value = "-> new", pure = true) + public abstract @NotNull Schema createBaseSchema(); + + public abstract @NotNull Dynamic updateWithAllFixers(DSL.TypeReference dataFixTypes, + @NotNull Dynamic dynamic); + + public abstract @NotNull CompoundTag addModDataVersions(@NotNull CompoundTag compound); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternalsImpl.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternalsImpl.java new file mode 100644 index 00000000000..ed7963a6090 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/DataFixesInternalsImpl.java @@ -0,0 +1,82 @@ +/* + * Copyright 2022 QuiltMC + * Modified by the Steam 'n' Rails (Railways) team + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.gregtechceu.gtceu.common.datafixer.schemas.V0; + +import net.minecraft.nbt.CompoundTag; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Range; + +@ApiStatus.Internal +public final class DataFixesInternalsImpl extends DataFixesInternals { + + private final @NotNull Schema latestVanillaSchema; + + private DataFixerEntry dataFixer; + + public DataFixesInternalsImpl(@NotNull Schema latestVanillaSchema) { + this.latestVanillaSchema = latestVanillaSchema; + + this.dataFixer = null; + } + + @Override + public void registerFixer(@Range(from = 0, to = Integer.MAX_VALUE) int currentVersion, + @NotNull DataFixer dataFixer) { + if (this.dataFixer != null) { + throw new IllegalArgumentException("GTCEu already has a registered data fixer"); + } + + this.dataFixer = new DataFixerEntry(dataFixer, currentVersion); + } + + @Override + public @Nullable DataFixerEntry getFixerEntry() { + return dataFixer; + } + + @Override + public @NotNull Schema createBaseSchema() { + return new V0(0, this.latestVanillaSchema); + } + + @Override + public @NotNull Dynamic updateWithAllFixers(DSL.TypeReference type, @NotNull Dynamic dynamic) { + if (dataFixer != null) { + int modDataVersion = DataFixesInternals.getModDataVersion(dynamic); + dynamic = dataFixer.dataFixer().update(type, dynamic, modDataVersion, dataFixer.currentVersion()); + } + + return dynamic; + } + + @Override + public @NotNull CompoundTag addModDataVersions(@NotNull CompoundTag compound) { + if (dataFixer != null) + compound.putInt("GTCEu_DataVersion", dataFixer.currentVersion()); + + return compound; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/EmptySchema.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/EmptySchema.java new file mode 100644 index 00000000000..d52a41cd072 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/EmptySchema.java @@ -0,0 +1,52 @@ +/* + * Copyright 2022 QuiltMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.Type; +import com.mojang.datafixers.types.templates.TypeTemplate; +import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; +import org.jetbrains.annotations.Range; + +import java.util.Map; +import java.util.function.Supplier; + +/** + * Represents an empty {@link Schema}, having no parent and containing no type definitions. + */ +public final class EmptySchema extends FirstSchema { + + /** + * Constructs an empty schema. + * + * @param versionKey the data version key + */ + public EmptySchema(@Range(from = 0, to = Integer.MAX_VALUE) int versionKey) { + super(versionKey); + } + + // Ensure the schema stays empty. + @Override + public void registerType(boolean recursive, DSL.TypeReference type, Supplier template) { + throw new UnsupportedOperationException(); + } + + @Override + protected Map> buildTypes() { + return Object2ObjectMaps.emptyMap(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/FirstSchema.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/FirstSchema.java new file mode 100644 index 00000000000..a04730bf6d5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/FirstSchema.java @@ -0,0 +1,50 @@ +/* + * Copyright 2022 QuiltMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.templates.TypeTemplate; +import org.jetbrains.annotations.Range; + +import java.util.Map; +import java.util.function.Supplier; + +public class FirstSchema extends Schema { + + /** + * Creates a schema. + * + * @param versionKey the data version key + */ + public FirstSchema(@Range(from = 0, to = Integer.MAX_VALUE) int versionKey) { + super(versionKey, null); + } + + // all of these methods refer to this.parent without checking if its null + @Override + public void registerTypes(Schema schema, Map> entityTypes, + Map> blockEntityTypes) {} + + @Override + public Map> registerEntities(Schema schema) { + return Map.of(); + } + + @Override + public Map> registerBlockEntities(Schema schema) { + return Map.of(); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/LICENSE b/src/main/java/com/gregtechceu/gtceu/api/datafixer/LICENSE new file mode 100644 index 00000000000..ad5b29c1e36 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/LICENSE @@ -0,0 +1,205 @@ +Certain portions of the datafixer are taken from the +Quilt Standard Library (https://github.com/QuiltMC/quilt-standard-libraries), +and as such are licensed under the following license: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/NoOpDataFixesInternals.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/NoOpDataFixesInternals.java new file mode 100644 index 00000000000..2b3b0481ed7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/NoOpDataFixesInternals.java @@ -0,0 +1,60 @@ +/* + * Copyright 2022 QuiltMC + * Modified by the Steam 'n' Rails (Railways) team + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.api.datafixer; + +import net.minecraft.nbt.CompoundTag; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Range; + +public class NoOpDataFixesInternals extends DataFixesInternals { + + private final Schema schema; + + public NoOpDataFixesInternals() { + schema = new EmptySchema(0); + } + + @Override + public void registerFixer(@Range(from = 0, to = Integer.MAX_VALUE) int currentVersion, + @NotNull DataFixer dataFixer) {} + + @Override + public @Nullable DataFixerEntry getFixerEntry() { + return null; + } + + @Override + public @NotNull Schema createBaseSchema() { + return schema; + } + + @Override + public @NotNull Dynamic updateWithAllFixers(DSL.TypeReference dataFixTypes, @NotNull Dynamic dynamic) { + return dynamic; + } + + @Override + public @NotNull CompoundTag addModDataVersions(@NotNull CompoundTag compound) { + return compound; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/datafixer/fixes/ToolBehaviorRemainderFix.java b/src/main/java/com/gregtechceu/gtceu/api/datafixer/fixes/ToolBehaviorRemainderFix.java new file mode 100644 index 00000000000..8eb3cccdf3a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/datafixer/fixes/ToolBehaviorRemainderFix.java @@ -0,0 +1,30 @@ +package com.gregtechceu.gtceu.api.datafixer.fixes; + +import net.minecraft.util.datafix.fixes.ItemStackComponentRemainderFix; + +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.NotNull; + +public abstract class ToolBehaviorRemainderFix extends ItemStackComponentRemainderFix { + + private final String behaviorId; + private final String newBehaviorId; + + public ToolBehaviorRemainderFix(Schema outputSchema, String name, String behaviorId) { + this(outputSchema, name, behaviorId, behaviorId); + } + + public ToolBehaviorRemainderFix(Schema outputSchema, String name, String behaviorId, String newBehaviorId) { + super(outputSchema, name, "gtceu:tool_behaviors"); + this.behaviorId = behaviorId; + this.newBehaviorId = newBehaviorId; + } + + @Override + protected final @NotNull Dynamic fixComponent(@NotNull Dynamic tag) { + return tag.renameAndFixField(behaviorId, newBehaviorId, this::fixBehavior); + } + + protected abstract @NotNull Dynamic fixBehavior(@NotNull Dynamic tag); +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/gui/widget/FloatInputWidget.java b/src/main/java/com/gregtechceu/gtceu/api/gui/widget/FloatInputWidget.java new file mode 100644 index 00000000000..3a5d6dd178e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/api/gui/widget/FloatInputWidget.java @@ -0,0 +1,88 @@ +package com.gregtechceu.gtceu.api.gui.widget; + +import com.lowdragmc.lowdraglib.gui.widget.TextFieldWidget; +import com.lowdragmc.lowdraglib.utils.Position; +import com.lowdragmc.lowdraglib.utils.Size; + +import net.minecraft.util.Mth; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * A widget containing a floating point input field, as well as adjacent buttons for increasing or decreasing the value. + * + *

+ * The buttons' change amount can be altered with Ctrl, Shift, or both.
+ * The input is limited by a minimum and maximum value. + *

+ */ +public class FloatInputWidget extends NumberInputWidget { + + public FloatInputWidget(Supplier valueSupplier, Consumer onChanged) { + super(valueSupplier, onChanged); + } + + public FloatInputWidget(Position position, Supplier valueSupplier, Consumer onChanged) { + super(position, valueSupplier, onChanged); + } + + public FloatInputWidget(Position position, Size size, Supplier valueSupplier, Consumer onChanged) { + super(position, size, valueSupplier, onChanged); + } + + public FloatInputWidget(int x, int y, int width, int height, Supplier valueSupplier, + Consumer onChanged) { + super(x, y, width, height, valueSupplier, onChanged); + } + + @Override + protected Float defaultMin() { + return 0.0f; + } + + @Override + protected Float defaultMax() { + return Float.MAX_VALUE; + } + + @Override + protected String toText(Float value) { + return String.valueOf(value); + } + + @Override + protected Float fromText(String value) { + return Float.parseFloat(value); + } + + @Override + protected ChangeValues getChangeValues() { + return new ChangeValues<>(1.0f, 0.1f, 0.01f, 0.001f); + } + + @Override + protected Float add(Float a, Float b) { + return a + b; + } + + @Override + protected Float multiply(Float a, Float b) { + return a * b; + } + + @Override + protected Float clamp(Float value, Float min, Float max) { + return Mth.clamp(value, min, max); + } + + @Override + protected void setTextFieldRange(TextFieldWidget textField, Float min, Float max) { + textField.setNumbersOnly(min, max); + } + + @Override + protected Float getOne(boolean positive) { + return positive ? 1.0f : -1.0f; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/api/gui/widget/PatternPreviewWidget.java b/src/main/java/com/gregtechceu/gtceu/api/gui/widget/PatternPreviewWidget.java index 94834a0612c..3f45e06d3ef 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/gui/widget/PatternPreviewWidget.java +++ b/src/main/java/com/gregtechceu/gtceu/api/gui/widget/PatternPreviewWidget.java @@ -483,11 +483,9 @@ private static class PartInfo { public List getItemStack() { return Arrays.stream(itemStackKey.getItemStack()) - .map(itemStack -> { - var item = itemStack.copy(); - item.setCount(amount); - return item; - }).filter((ItemStack item) -> !item.isEmpty()).toList(); + .map(stack -> stack.copyWithCount(amount)) + .filter(item -> !item.isEmpty()) + .toList(); } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/item/datacomponents/FacadeWrapper.java b/src/main/java/com/gregtechceu/gtceu/api/item/datacomponents/FacadeWrapper.java deleted file mode 100644 index d0c8b846254..00000000000 --- a/src/main/java/com/gregtechceu/gtceu/api/item/datacomponents/FacadeWrapper.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.gregtechceu.gtceu.api.item.datacomponents; - -import net.minecraft.network.RegistryFriendlyByteBuf; -import net.minecraft.network.codec.ByteBufCodecs; -import net.minecraft.network.codec.StreamCodec; -import net.minecraft.world.level.block.state.BlockState; - -import com.mojang.serialization.Codec; - -public record FacadeWrapper(BlockState state) { - - public static final Codec CODEC = BlockState.CODEC.xmap(FacadeWrapper::new, FacadeWrapper::state); - public static final StreamCodec STREAM_CODEC = ByteBufCodecs - .fromCodecWithRegistries(CODEC); - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof FacadeWrapper(BlockState thatState))) - return false; - - return state == thatState; - } -} diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/fancyconfigurator/AutoStockingFancyConfigurator.java b/src/main/java/com/gregtechceu/gtceu/api/machine/fancyconfigurator/AutoStockingFancyConfigurator.java index 94620e8736c..40b203f409c 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/fancyconfigurator/AutoStockingFancyConfigurator.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/fancyconfigurator/AutoStockingFancyConfigurator.java @@ -17,7 +17,7 @@ public class AutoStockingFancyConfigurator implements IFancyConfigurator { - private IMEStockingPart machine; + private final IMEStockingPart machine; public AutoStockingFancyConfigurator(IMEStockingPart machine) { this.machine = machine; diff --git a/src/main/java/com/gregtechceu/gtceu/api/machine/steam/SteamEnergyRecipeHandler.java b/src/main/java/com/gregtechceu/gtceu/api/machine/steam/SteamEnergyRecipeHandler.java index 00da2c0adf0..17d760a5aef 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/machine/steam/SteamEnergyRecipeHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/machine/steam/SteamEnergyRecipeHandler.java @@ -40,7 +40,8 @@ public List handleRecipeInner(IO io, GTRecipe recipe, List 0) { - var steam = io == IO.IN ? SizedFluidIngredient.of(GTMaterials.Steam.getFluidTag(), totalSteam) : + SizedFluidIngredient steam = io == IO.IN ? + SizedFluidIngredient.of(GTMaterials.Steam.getFluidTag(), totalSteam) : SizedFluidIngredient.of(GTMaterials.Steam.getFluid(totalSteam)); List list = new ArrayList<>(); list.add(steam); @@ -48,7 +49,7 @@ public List handleRecipeInner(IO io, GTRecipe recipe, List { - public GraphicsComponent(double x, double y, double x2, double y2, String rendererId, CompoundTag renderData) { - this((float) x, (float) y, (float) x2, (float) y2, rendererId, renderData); - } - + // spotless:off public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( Codec.FLOAT.fieldOf("x").forGetter(GraphicsComponent::x), Codec.FLOAT.fieldOf("y").forGetter(GraphicsComponent::y), Codec.FLOAT.fieldOf("x2").forGetter(GraphicsComponent::x2), Codec.FLOAT.fieldOf("y2").forGetter(GraphicsComponent::y2), Codec.STRING.fieldOf("rendererId").forGetter(GraphicsComponent::rendererId), - CompoundTag.CODEC.fieldOf("renderData").forGetter(GraphicsComponent::renderData)) - .apply(instance, GraphicsComponent::new)); + CompoundTag.CODEC.fieldOf("renderData").forGetter(GraphicsComponent::renderData) + ).apply(instance, GraphicsComponent::new)); + // spotless:on + + public GraphicsComponent(double x, double y, double x2, double y2, String rendererId, CompoundTag renderData) { + this((float) x, (float) y, (float) x2, (float) y2, rendererId, renderData); + } @Override public IMonitorRenderer get() { @@ -48,12 +48,4 @@ public void render(CentralMonitorMachine machine, MonitorGroup group, float part } }; } - - public Tag toTag() { - return CODEC.encodeStart(NbtOps.INSTANCE, this).getOrThrow(); - } - - public static GraphicsComponent fromTag(Tag tag) { - return CODEC.decode(NbtOps.INSTANCE, tag).getOrThrow().getFirst(); - } } diff --git a/src/main/java/com/gregtechceu/gtceu/api/placeholder/MultiLineComponent.java b/src/main/java/com/gregtechceu/gtceu/api/placeholder/MultiLineComponent.java index 6d857a1c66f..1af66a91277 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/placeholder/MultiLineComponent.java +++ b/src/main/java/com/gregtechceu/gtceu/api/placeholder/MultiLineComponent.java @@ -1,14 +1,10 @@ package com.gregtechceu.gtceu.api.placeholder; import net.minecraft.ChatFormatting; -import net.minecraft.core.HolderLookup; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; import net.minecraft.network.chat.*; import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @@ -17,23 +13,17 @@ import org.jetbrains.annotations.UnmodifiableView; import java.util.*; +import java.util.stream.Collectors; @Accessors(chain = true) public class MultiLineComponent extends ArrayList { - public static final Codec CODEC = ComponentSerialization.CODEC.listOf() - .xmap(list -> { - if (((List) list) instanceof MultiLineComponent multiLine) { - return multiLine; - } - MultiLineComponent multiLine = new MultiLineComponent(); - for (Component c : list) { - multiLine.add(c.copy()); - } - return multiLine; - }, MultiLineComponent::toImmutable); - - public MultiLineComponent() {} + // spotless:off + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + ComponentSerialization.CODEC.listOf().fieldOf("text").forGetter(MultiLineComponent::toImmutable), + GraphicsComponent.CODEC.listOf().orElse(Collections.emptyList()).fieldOf("graphics").forGetter(MultiLineComponent::getGraphics) + ).apply(instance, MultiLineComponent::of)); + // spotless:on @Getter @Setter @@ -42,19 +32,34 @@ public MultiLineComponent() {} @Getter private final List graphics = new ArrayList<>(); + public MultiLineComponent() {} + public MultiLineComponent(List components) { super(components); } + protected static MultiLineComponent of(List lines, List graphics) { + MultiLineComponent component = lines.stream() + .map(Component::copy) + .collect(Collectors.toCollection(MultiLineComponent::new)); + component.addGraphics(graphics); + return component; + } + public static MultiLineComponent of(List lines) { - List mutableLines = lines.stream() + return lines.stream() .map(Component::copy) - .toList(); - return new MultiLineComponent(mutableLines); + .collect(Collectors.toCollection(MultiLineComponent::new)); } public static MultiLineComponent of(Component c) { - return new MultiLineComponent(List.of(c.copy())); + return MultiLineComponent.of(c.copy()); + } + + public static MultiLineComponent of(MutableComponent c) { + MultiLineComponent value = new MultiLineComponent(); + value.add(c); + return value; } public static MultiLineComponent literal(char c) { @@ -173,38 +178,6 @@ public MultiLineComponent withStyle(ChatFormatting... style) { return Collections.unmodifiableList(this); } - public Tag toTag(HolderLookup.Provider registries) { - CompoundTag compoundTag = new CompoundTag(); - ListTag tag = new ListTag(); - for (MutableComponent component : this) { - tag.add(StringTag.valueOf(Component.Serializer.toJson(component, registries))); - } - compoundTag.put("text", tag); - ListTag graphicsTag = new ListTag(); - for (GraphicsComponent component : this.getGraphics()) { - graphicsTag.add(component.toTag()); - } - compoundTag.put("graphics", graphicsTag); - return compoundTag; - } - - public static MultiLineComponent fromTag(@Nullable Tag tag, HolderLookup.Provider registries) { - MultiLineComponent out = MultiLineComponent.empty(); - out.clear(); - if (tag == null) return out; - if (tag instanceof ListTag listTag) { - for (Tag i : listTag) { - out.add(Component.Serializer.fromJson(i.getAsString(), registries)); - } - } else if (tag instanceof CompoundTag compoundTag) { - ListTag textTag = compoundTag.getList("text", Tag.TAG_STRING); - for (Tag i : textTag) out.add(Component.Serializer.fromJson(i.getAsString(), registries)); - ListTag graphicsTag = compoundTag.getList("graphics", Tag.TAG_COMPOUND); - for (Tag i : graphicsTag) out.addGraphics(GraphicsComponent.fromTag(i)); - } - return out; - } - public long toLong() { if (this.isEmpty()) return 0; if (this.size() > 1) throw new NumberFormatException(this.toString()); @@ -215,7 +188,7 @@ public long toLong() { } public MultiLineComponent addGraphics(GraphicsComponent... graphicsComponents) { - return this.addGraphics(List.of(graphicsComponents)); + return this.addGraphics(Arrays.asList(graphicsComponents)); } public MultiLineComponent addGraphics(Collection graphicsComponents) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderContext.java b/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderContext.java index dbf688a8dfd..3853b7cdfcf 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderContext.java +++ b/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderContext.java @@ -5,7 +5,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; -import net.neoforged.neoforge.items.ItemStackHandler; +import net.neoforged.neoforge.items.IItemHandler; import lombok.With; import org.jetbrains.annotations.Nullable; @@ -15,7 +15,7 @@ public record PlaceholderContext(Level level, BlockPos pos, Direction side, - @Nullable ItemStackHandler itemStackHandler, + @Nullable IItemHandler itemHandler, @Nullable CoverBehavior cover, @Nullable MultiLineComponent previousText, UUID uuid, @@ -24,7 +24,7 @@ public record PlaceholderContext(Level level, public PlaceholderContext(Level level, BlockPos pos, Direction side, - @Nullable ItemStackHandler itemStackHandler, + @Nullable IItemHandler itemStackHandler, @Nullable CoverBehavior cover, @Nullable MultiLineComponent previousText, UUID uuid) { diff --git a/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderHandler.java b/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderHandler.java index d1316b39630..1b3342874f2 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/api/placeholder/PlaceholderHandler.java @@ -87,9 +87,10 @@ public static void addRenderer(String id, IPlaceholderRenderer renderer) { public static MultiLineComponent processPlaceholder(List placeholder, PlaceholderContext context, Object2IntOpenHashMap indices) throws PlaceholderException { - if (!placeholderExists(placeholder.get(0))) - throw new UnknownPlaceholderException(placeholder.get(0).toString()); - String name = placeholder.get(0).toString(); + if (!placeholderExists(placeholder.getFirst())) { + throw new UnknownPlaceholderException(placeholder.getFirst().toString()); + } + String name = placeholder.getFirst().toString(); indices.addTo(name, 1); return placeholders.get(name).apply(context.withIndex(indices.getInt(name)), placeholder.subList(1, placeholder.size())); @@ -114,8 +115,11 @@ public static MultiLineComponent processPlaceholders(String s, PlaceholderContex stack.peek().getLast().appendNewline(); line++; symbol = 0; - } else if (c == NEWLINE) continue; - else stack.peek().getLast().append(c); + } else if (c == NEWLINE) { + continue; + } else { + stack.peek().getLast().append(c); + } } else { switch (c) { case ESCAPE -> escapeNext = true; @@ -176,8 +180,10 @@ public static MultiLineComponent processPlaceholders(String s, PlaceholderContex exception.setLineInfo(line, symbol); exceptions.add(exception); } - if (exceptions.isEmpty()) + if (exceptions.isEmpty()) { return stack.peek().stream().reduce(MultiLineComponent.empty(), MultiLineComponent::append); + } + MultiLineComponent out = MultiLineComponent.literal("Exceptions:"); out.appendNewline(); exceptions.forEach(exception -> { @@ -209,6 +215,7 @@ public static Widget getPlaceholderHandlerUI(String filter) { } }; onSearch.accept(filter); + TextTextureWidget placeholderReferenceLabel = new TextTextureWidget( 280, 0, 160, 15, diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/event/CraftingComponentModificationEvent.java b/src/main/java/com/gregtechceu/gtceu/api/recipe/event/CraftingComponentModificationEvent.java similarity index 82% rename from src/main/java/com/gregtechceu/gtceu/data/recipe/event/CraftingComponentModificationEvent.java rename to src/main/java/com/gregtechceu/gtceu/api/recipe/event/CraftingComponentModificationEvent.java index bd7af5cce79..1bbe26db74a 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/event/CraftingComponentModificationEvent.java +++ b/src/main/java/com/gregtechceu/gtceu/api/recipe/event/CraftingComponentModificationEvent.java @@ -1,4 +1,4 @@ -package com.gregtechceu.gtceu.data.recipe.event; +package com.gregtechceu.gtceu.api.recipe.event; import net.neoforged.bus.api.Event; diff --git a/src/main/java/com/gregtechceu/gtceu/api/registry/registrate/GTRegistrate.java b/src/main/java/com/gregtechceu/gtceu/api/registry/registrate/GTRegistrate.java index 4258791640e..fa8a55d38b5 100644 --- a/src/main/java/com/gregtechceu/gtceu/api/registry/registrate/GTRegistrate.java +++ b/src/main/java/com/gregtechceu/gtceu/api/registry/registrate/GTRegistrate.java @@ -52,7 +52,6 @@ import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; -import java.util.function.Supplier; public class GTRegistrate extends AbstractRegistrate { @@ -242,15 +241,11 @@ public GTBlockBuilder block(P parent, String name, return this.currentTab; } - public void creativeModeTab(Supplier> currentTab) { - this.currentTab = currentTab.get(); - } - public void resetCreativeModeTab() { this.currentTab = null; } - public void creativeModeTab(RegistryEntry currentTab) { + public void creativeModeTab(@Nullable RegistryEntry currentTab) { this.currentTab = currentTab; } diff --git a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java index 2385f0cf29e..072b3c2b258 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/client/ClientProxy.java @@ -3,6 +3,7 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.cosmetics.event.RegisterGTCapesEvent; +import com.gregtechceu.gtceu.api.data.pack.event.RegisterDynamicResourcesEvent; import com.gregtechceu.gtceu.api.item.IComponentItem; import com.gregtechceu.gtceu.api.item.IGTTool; import com.gregtechceu.gtceu.client.model.item.FacadeUnbakedModel; @@ -36,7 +37,6 @@ import com.gregtechceu.gtceu.common.item.QuantumTankMachineItem; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.data.model.builder.PipeModelBuilder; -import com.gregtechceu.gtceu.data.pack.event.RegisterDynamicResourcesEvent; import com.gregtechceu.gtceu.integration.kjs.GTKubeJSPlugin; import com.gregtechceu.gtceu.integration.map.ClientCacheManager; import com.gregtechceu.gtceu.integration.map.cache.client.GTClientCache; diff --git a/src/main/java/com/gregtechceu/gtceu/client/model/pipe/PipeModel.java b/src/main/java/com/gregtechceu/gtceu/client/model/pipe/PipeModel.java index aa80c3583e5..6e73948b11e 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/model/pipe/PipeModel.java +++ b/src/main/java/com/gregtechceu/gtceu/client/model/pipe/PipeModel.java @@ -1,10 +1,11 @@ package com.gregtechceu.gtceu.client.model.pipe; import com.gregtechceu.gtceu.api.block.PipeBlock; +import com.gregtechceu.gtceu.api.data.pack.event.RegisterDynamicResourcesEvent; import com.gregtechceu.gtceu.api.registry.registrate.GTBlockBuilder; import com.gregtechceu.gtceu.api.registry.registrate.provider.GTBlockstateProvider; +import com.gregtechceu.gtceu.common.data.GTBlockStateProperties; import com.gregtechceu.gtceu.data.model.builder.PipeModelBuilder; -import com.gregtechceu.gtceu.data.pack.event.RegisterDynamicResourcesEvent; import com.gregtechceu.gtceu.utils.GTMath; import com.gregtechceu.gtceu.utils.GTUtil; diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighlightRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighlightRenderer.java index 7e14ff80769..72e3089331a 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighlightRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/BlockHighlightRenderer.java @@ -96,7 +96,7 @@ public static void renderBlockHighlight(PoseStack poseStack, Camera camera, Bloc drawGridOverlays(poseStack, multiBufferSource, cameraPos, target, side -> finalGridHighlight.sideTips(player, blockPos, state, toolType, held, side)); } else { - var facing = target.getDirection(); + Direction facing = target.getDirection(); var texture = gridHighlight.sideTips(player, blockPos, state, toolType, held, facing); if (texture != null) { RenderSystem.disableDepthTest(); @@ -276,10 +276,10 @@ private static void drawLine(PoseStack.Pose pose, VertexConsumer buffer, Vector3 buffer.addVertex(pose.pose(), from.x(), from.y(), from.z()) .setColor(rColour, gColour, bColour, 1f) - .setNormal(normal.x(), normal.y(), normal.z()); + .setNormal(pose, normal.x(), normal.y(), normal.z()); buffer.addVertex(pose.pose(), to.x(), to.y(), to.z()) .setColor(rColour, gColour, bColour, 1f) - .setNormal(normal.x(), normal.y(), normal.z()); + .setNormal(pose, normal.x(), normal.y(), normal.z()); } private static void drawResourceTexture(PoseStack poseStack, MultiBufferSource bufferSource, diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorImageRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorImageRenderer.java index 459a4789d10..03623826da6 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorImageRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorImageRenderer.java @@ -25,7 +25,7 @@ public MonitorImageRenderer(String url) { @Override public void render(CentralMonitorMachine machine, MonitorGroup group, float partialTick, PoseStack poseStack, MultiBufferSource buffer, int packedLight, int packedOverlay) { - BlockPos rel = group.getRow(0, machine::toRelative).get(0); + BlockPos rel = group.getRow(0, machine::toRelative).getFirst(); BlockPos size = group.getRow(-1, machine::toRelative).getLast() .offset(-rel.getX() + 1, -rel.getY() + 1, -rel.getZ() + 1); diff --git a/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorTextRenderer.java b/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorTextRenderer.java index 4492f7e38ea..4c07aec1c75 100644 --- a/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorTextRenderer.java +++ b/src/main/java/com/gregtechceu/gtceu/client/renderer/monitor/MonitorTextRenderer.java @@ -22,9 +22,9 @@ public class MonitorTextRenderer implements IMonitorRenderer { private final MultiLineComponent text; private final float scale; - public MonitorTextRenderer(MultiLineComponent text, double scale) { + public MonitorTextRenderer(MultiLineComponent text, float scale) { this.text = text; - this.scale = (float) scale; + this.scale = scale; } @Override @@ -72,16 +72,9 @@ public void render(CentralMonitorMachine machine, MonitorGroup group, float part return; } } - Minecraft.getInstance().font.drawInBatch( - line, - 9, y, - 0xFFFFFF, - false, - poseStack.last().pose(), - buffer, - Font.DisplayMode.NORMAL, - 0, - LightTexture.FULL_BRIGHT); + Minecraft.getInstance().font.drawInBatch(line, 9, y, 0xFFFFFF, false, + poseStack.last().pose(), buffer, Font.DisplayMode.NORMAL, + 0, LightTexture.FULL_BRIGHT); y += Minecraft.getInstance().font.lineHeight * scale; didAnything = true; } diff --git a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java index b85f3595920..944b3e35c47 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java +++ b/src/main/java/com/gregtechceu/gtceu/common/CommonProxy.java @@ -50,6 +50,7 @@ import com.gregtechceu.gtceu.common.data.item.*; import com.gregtechceu.gtceu.common.data.machines.GTMachineUtils; import com.gregtechceu.gtceu.common.data.materials.GTFoods; +import com.gregtechceu.gtceu.common.datafixer.GTDataFixers; import com.gregtechceu.gtceu.common.fluid.potion.BottleItemFluidHandler; import com.gregtechceu.gtceu.common.fluid.potion.PotionItemFluidHandler; import com.gregtechceu.gtceu.common.item.DrumMachineItem; @@ -69,7 +70,9 @@ import com.gregtechceu.gtceu.data.pack.GTPackSource; import com.gregtechceu.gtceu.data.placeholder.GTPlaceholders; import com.gregtechceu.gtceu.data.recipe.*; +import com.gregtechceu.gtceu.integration.ae2.GTAEPlaceholders; import com.gregtechceu.gtceu.integration.cctweaked.CCTweakedPlugin; +import com.gregtechceu.gtceu.integration.create.GTCreateIntegration; import com.gregtechceu.gtceu.integration.kjs.GTCEuStartupEvents; import com.gregtechceu.gtceu.integration.kjs.GTKubeJSPlugin; import com.gregtechceu.gtceu.integration.kjs.events.MaterialModificationEventJS; @@ -181,7 +184,14 @@ public static void onRegister(RegisterEvent event) { GTSoundEntries.init(); GTDamageTypes.init(); + GTPlaceholders.initPlaceholders(); + if (GTCEu.Mods.isCreateLoaded()) { + GTCreateIntegration.init(); + } + if (GTCEu.Mods.isAE2Loaded()) { + GTAEPlaceholders.init(); + } GTBlocks.init(); GTFluids.init(); @@ -214,7 +224,7 @@ public static void onRegister(RegisterEvent event) { GTParticleTypes.PARTICLE_TYPES.register(modBus); GregTechDatagen.initPost(); - GTValueProviderTypes.init(modBus); + GTValueProviderTypes.register(modBus); GTFeatures.register(modBus); WorldGenLayers.registerAll(); VeinGenerators.registerAddonGenerators(); @@ -225,6 +235,7 @@ public static void onRegister(RegisterEvent event) { SyncedKeyMappings.init(); MachineOwner.init(); ChestGenHooks.init(); + GTDataFixers.init(); } @ApiStatus.Internal diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java index bdd06bd5c41..f47fac11c2d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTItems.java @@ -27,9 +27,9 @@ import com.gregtechceu.gtceu.common.item.armor.GTArmorMaterials; import com.gregtechceu.gtceu.common.item.behavior.*; import com.gregtechceu.gtceu.common.item.behavior.MachineConfigCopyBehaviour; +import com.gregtechceu.gtceu.common.item.behavior.modules.ImageModuleBehaviour; +import com.gregtechceu.gtceu.common.item.behavior.modules.TextModuleBehaviour; import com.gregtechceu.gtceu.common.item.datacomponents.DataItem; -import com.gregtechceu.gtceu.common.item.modules.ImageModuleBehaviour; -import com.gregtechceu.gtceu.common.item.modules.TextModuleBehaviour; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.data.lang.LangHandler; import com.gregtechceu.gtceu.data.recipe.CustomTags; @@ -2589,11 +2589,7 @@ public static ItemEntry createFluidCell(Material mat, int capacit .onRegister(attach(new ImageModuleBehaviour())) .register(); - public static void init() { - // GTMaterialItems.generateMaterialItems(); - // GTMaterialItems.generateTools(); - // GTMaterialItems.generateArmors(); - } + public static void init() {} public static NonNullConsumer materialInfo(ItemMaterialInfo materialInfo) { return item -> ItemMaterialData.registerMaterialInfo(item, materialInfo); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java index 3b36a0de3a8..07218580193 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMachines.java @@ -40,6 +40,7 @@ import net.minecraft.ChatFormatting; import net.minecraft.core.Registry; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentUtils; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.fluids.FluidStack; import net.neoforged.neoforge.fluids.FluidType; @@ -139,7 +140,7 @@ public class GTMachines { .rotationState(RotationState.NON_Y_AXIS) .recipeType(DUMMY_RECIPES) .tooltips(Component.translatable("gtceu.universal.tooltip.uses_per_tick_steam", isHP ? 32 : 16) - .append(ChatFormatting.GRAY + ", ") + .append(ComponentUtils.DEFAULT_SEPARATOR) .append(Component.translatable("gtceu.machine.miner.per_block", isHP ? 240 / 20 : 280 / 20))) .tooltipBuilder((item, tooltip) -> { @@ -416,7 +417,7 @@ public class GTMachines { int tickSpeed = ConfigHolder.INSTANCE.machines.minerSpeed / (tier * 2); tooltip.add(Component.translatable("gtceu.machine.miner.tooltip", maxArea, maxArea)); tooltip.add(Component.translatable("gtceu.universal.tooltip.uses_per_tick", energyPerTick) - .append(Component.literal(", ").withStyle(ChatFormatting.GRAY)) + .append(ComponentUtils.DEFAULT_SEPARATOR) .append(Component.translatable("gtceu.machine.miner.per_block", tickSpeed / 20))); tooltip.add(Component.translatable("gtceu.universal.tooltip.voltage_in", FormattingUtil.formatNumbers(GTValues.V[tier]), diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java index c7e6d63a36d..50f6bcd915d 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTMaterials.java @@ -539,7 +539,7 @@ private static void excludeAllGemsButNormal(Material material) { public static Material VanadiumGallium; public static Material WroughtIron; public static Material Wulfenite; - public static Material YellowLimonite; + public static Material Limonite; public static Material YttriumBariumCuprate; public static Material NetherQuartz; public static Material CertusQuartz; diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTOreVeins.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTOreVeins.java index 6ef734a47e9..03c762a44a2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTOreVeins.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTOreVeins.java @@ -245,7 +245,7 @@ public static void bootstrap(BootstrapContext context) { .biomes(BiomeTags.IS_NETHER) .veinedVeinGenerator(generator -> generator .oreBlock(new VeinBlockDefinition(Goethite, 3)) - .oreBlock(new VeinBlockDefinition(YellowLimonite, 2)) + .oreBlock(new VeinBlockDefinition(Limonite, 2)) .oreBlock(new VeinBlockDefinition(Hematite, 2)) .rareBlock(new VeinBlockDefinition(Gold, 1)) .rareBlockChance(0.075f) @@ -527,7 +527,7 @@ public static void bootstrap(BootstrapContext context) { .biomes(BiomeTags.IS_OVERWORLD) .veinedVeinGenerator(generator -> generator .oreBlock(new VeinBlockDefinition(Goethite, 5)) - .oreBlock(new VeinBlockDefinition(YellowLimonite, 2)) + .oreBlock(new VeinBlockDefinition(Limonite, 2)) .oreBlock(new VeinBlockDefinition(Hematite, 2)) .oreBlock(new VeinBlockDefinition(Malachite, 1)) .veininessThreshold(0.01f) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTReferences.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTReferences.java new file mode 100644 index 00000000000..8d41f8704ea --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTReferences.java @@ -0,0 +1,23 @@ +package com.gregtechceu.gtceu.common.data; + +import com.mojang.datafixers.DSL; + +public class GTReferences { + + public static final DSL.TypeReference MATERIAL_NAME = reference("material_name"); + + public static DSL.TypeReference reference(final String pName) { + return new DSL.TypeReference() { + + @Override + public String typeName() { + return pName; + } + + @Override + public String toString() { + return "@" + pName; + } + }; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTValueProviderTypes.java b/src/main/java/com/gregtechceu/gtceu/common/data/GTValueProviderTypes.java index 9535df0c1d5..fdc5de09b3b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTValueProviderTypes.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/GTValueProviderTypes.java @@ -15,32 +15,30 @@ public class GTValueProviderTypes { - public static final DeferredRegister> INT_PROVIDER_TYPE_REGISTER = DeferredRegister.create( - Registries.INT_PROVIDER_TYPE, - GTCEu.MOD_ID); - public static final DeferredRegister> FLOAT_PROVIDER_TYPE_REGISTER = DeferredRegister.create( - Registries.FLOAT_PROVIDER_TYPE, - GTCEu.MOD_ID); + public static final DeferredRegister> INT_PROVIDER_TYPES = DeferredRegister + .create(Registries.INT_PROVIDER_TYPE, GTCEu.MOD_ID); + public static final DeferredRegister> FLOAT_PROVIDER_TYPES = DeferredRegister + .create(Registries.FLOAT_PROVIDER_TYPE, GTCEu.MOD_ID); - public static final DeferredHolder, IntProviderType> FLOORED = INT_PROVIDER_TYPE_REGISTER + public static final DeferredHolder, IntProviderType> FLOORED = INT_PROVIDER_TYPES .register( "floored", () -> () -> FlooredInt.CODEC); - public static final DeferredHolder, FloatProviderType> MULTIPLIED = FLOAT_PROVIDER_TYPE_REGISTER + public static final DeferredHolder, FloatProviderType> MULTIPLIED = FLOAT_PROVIDER_TYPES .register("multiplied", () -> () -> MultipliedFloat.CODEC); - public static final DeferredHolder, FloatProviderType> ADDED = FLOAT_PROVIDER_TYPE_REGISTER + public static final DeferredHolder, FloatProviderType> ADDED = FLOAT_PROVIDER_TYPES .register( "added", () -> () -> AddedFloat.CODEC); - public static final DeferredHolder, FloatProviderType> CASTED = FLOAT_PROVIDER_TYPE_REGISTER + public static final DeferredHolder, FloatProviderType> CASTED = FLOAT_PROVIDER_TYPES .register( "casted", () -> () -> CastedFloat.CODEC); - public static void init(IEventBus bus) { - INT_PROVIDER_TYPE_REGISTER.register(bus); - FLOAT_PROVIDER_TYPE_REGISTER.register(bus); + public static void register(IEventBus bus) { + INT_PROVIDER_TYPES.register(bus); + FLOAT_PROVIDER_TYPES.register(bus); } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/item/GTDataComponents.java b/src/main/java/com/gregtechceu/gtceu/common/data/item/GTDataComponents.java index 575bbc72a08..0f1dde19fef 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/item/GTDataComponents.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/item/GTDataComponents.java @@ -23,6 +23,8 @@ import net.minecraft.util.Unit; import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.enchantment.ItemEnchantments; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; import net.neoforged.neoforge.fluids.SimpleFluidContent; import net.neoforged.neoforge.registries.DeferredHolder; import net.neoforged.neoforge.registries.DeferredRegister; @@ -91,6 +93,7 @@ public class GTDataComponents { public static final DeferredHolder, DataComponentType> DATA_ITEM = DATA_COMPONENTS .registerComponentType("data_item", builder -> builder.persistent(DataItem.CODEC) .networkSynchronized(DataItem.STREAM_CODEC)); + public static final DeferredHolder, DataComponentType> MAGNET = DATA_COMPONENTS .registerComponentType("magnet", builder -> builder.persistent(ItemMagnetBehavior.MagnetComponent.CODEC) @@ -129,6 +132,9 @@ public class GTDataComponents { .registerComponentType("data_copy_tag", builder -> builder.persistent(CustomData.CODEC) .networkSynchronized(CustomData.STREAM_CODEC)); + public static final DeferredHolder, DataComponentType> FORMAT_STRING_LIST = DATA_COMPONENTS + .registerComponentType("format_string_list", builder -> builder.persistent(FormatStringList.CODEC) + .networkSynchronized(FormatStringList.STREAM_CODEC)); public static final DeferredHolder, DataComponentType> COMPUTER_MONITOR_DATA = DATA_COMPONENTS .registerComponentType("computer_monitor_cover_data", builder -> builder.persistent(FormatStringList.CODEC) .networkSynchronized(FormatStringList.STREAM_CODEC)); @@ -174,9 +180,9 @@ public class GTDataComponents { builder -> builder.persistent(Unit.CODEC).networkSynchronized(UNIT_STREAM_CODEC)); // misc - public static final DeferredHolder, DataComponentType> FACADE = DATA_COMPONENTS - .registerComponentType("facade", builder -> builder.persistent(FacadeWrapper.CODEC) - .networkSynchronized(FacadeWrapper.STREAM_CODEC)); + public static final DeferredHolder, DataComponentType> FACADE = DATA_COMPONENTS + .registerComponentType("facade", builder -> builder.persistent(BlockState.CODEC) + .networkSynchronized(ByteBufCodecs.idMapper(Block.BLOCK_STATE_REGISTRY))); public static final DeferredHolder, DataComponentType> LAMP_DATA = DATA_COMPONENTS .registerComponentType("lamp", builder -> builder.persistent(LampBlockItem.LampData.CODEC) .networkSynchronized(LampBlockItem.LampData.STREAM_CODEC)); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTMachineUtils.java b/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTMachineUtils.java index ca7ff792903..e4773637f0f 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTMachineUtils.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/machines/GTMachineUtils.java @@ -430,8 +430,7 @@ public static MachineDefinition[] registerConverter(GTRegistrate registrate, int final var tab = registrate.creativeModeTab(); if (!ConfigHolder.INSTANCE.compat.energy.enableFEConverters) { - // REGISTRATE.creativeModeTab(null); - registrate.creativeModeTab(() -> null); + registrate.creativeModeTab(null); } MachineDefinition[] converters = registerTieredMachines(registrate, amperage + "a_energy_converter", @@ -456,8 +455,7 @@ public static MachineDefinition[] registerConverter(GTRegistrate registrate, int ALL_TIERS); if (!ConfigHolder.INSTANCE.compat.energy.enableFEConverters) { - // REGISTRATE.creativeModeTab(MACHINE); - registrate.creativeModeTab(() -> tab); + registrate.creativeModeTab(tab); } return converters; } @@ -550,18 +548,9 @@ public static MachineDefinition[] registerQuantumTanks(GTRegistrate registrate, MachineDefinition[] definitions = new MachineDefinition[GTValues.TIER_COUNT]; for (int tier : tiers) { long maxAmount = 4000 * FluidType.BUCKET_VOLUME * (long) Math.pow(2, tier - 1); - // <<<<<<< HEAD:src/main/java/com/gregtechceu/gtceu/data/machine/GTMachineUtils.java - var register = REGISTRATE + var register = registrate .machine(GTValues.VN[tier].toLowerCase(Locale.ROOT) + "_" + name, (holder) -> new QuantumTankMachine(holder, tier, maxAmount)) - // ======= - // var register = registrate.machine( - // GTValues.VN[tier].toLowerCase(Locale.ROOT) + "_" + name, - // MachineDefinition::new, (holder) -> new QuantumTankMachine(holder, tier, maxAmount), - // MetaMachineBlock::new, QuantumTankMachineItem::new, - // MetaMachineBlockEntity::new) - // >>>>>>> - // v7.1.0-1.20.1:src/main/java/com/gregtechceu/gtceu/common/data/machines/GTMachineUtils.java .langValue(toEnglishName(name) + " " + LVT[tier]) .blockProp(Block.Properties::dynamicShape) .rotationState(RotationState.ALL) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java index 5f6a189feeb..057b906b38b 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/FirstDegreeMaterials.java @@ -738,7 +738,7 @@ public static void register() { .components(Lead, 1, Molybdenum, 1, Oxygen, 4) .buildAndRegister(); - YellowLimonite = new Material.Builder(GTCEu.id("yellow_limonite")) + Limonite = new Material.Builder(GTCEu.id("limonite")) .dust().ore() .color(0xf5e315).secondaryColor(0xc06f33).iconSet(METALLIC) .flags(DECOMPOSITION_BY_CENTRIFUGING, BLAST_FURNACE_CALCITE_DOUBLE) diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/materials/MaterialFlagAddition.java b/src/main/java/com/gregtechceu/gtceu/common/data/materials/MaterialFlagAddition.java index 9af9bdcaf91..52334c037c7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/materials/MaterialFlagAddition.java +++ b/src/main/java/com/gregtechceu/gtceu/common/data/materials/MaterialFlagAddition.java @@ -103,7 +103,7 @@ public static void register() { oreProp.setOreByProducts(Topaz); oreProp = Goethite.getProperty(PropertyKey.ORE); - oreProp.setOreByProducts(Malachite, YellowLimonite); + oreProp.setOreByProducts(Malachite, Limonite); oreProp.setSeparatedInto(Iron); oreProp.setDirectSmeltResult(Iron); @@ -256,7 +256,7 @@ public static void register() { oreProp = Uraninite.getProperty(PropertyKey.ORE); oreProp.setOreByProducts(Uraninite, Thorium, Silver); - oreProp = YellowLimonite.getProperty(PropertyKey.ORE); + oreProp = Limonite.getProperty(PropertyKey.ORE); oreProp.setOreByProducts(Nickel, Goethite, CobaltOxide); oreProp.setSeparatedInto(Iron); oreProp.setWashedIn(SodiumPersulfate); diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/GTDataFixers.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/GTDataFixers.java new file mode 100644 index 00000000000..cd9b4aa61da --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/GTDataFixers.java @@ -0,0 +1,114 @@ +package com.gregtechceu.gtceu.common.datafixer; + +import com.gregtechceu.gtceu.GTCEu; +import com.gregtechceu.gtceu.api.GTCEuAPI; +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; +import com.gregtechceu.gtceu.common.datafixer.fixes.*; +import com.gregtechceu.gtceu.config.ConfigHolder; + +import net.minecraft.util.datafix.DataFixTypes; +import net.minecraft.util.datafix.fixes.AddNewChoices; +import net.minecraft.util.datafix.fixes.BlockRenameFix; +import net.minecraft.util.datafix.fixes.ItemRenameFix; +import net.minecraft.util.datafix.fixes.References; +import net.minecraft.util.datafix.schemas.NamespacedSchema; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import com.mojang.datafixers.DataFixerBuilder; +import com.mojang.datafixers.schemas.Schema; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.BiFunction; +import java.util.function.UnaryOperator; +import java.util.regex.Pattern; + +import static com.gregtechceu.gtceu.api.datafixer.DataFixesInternals.BASE_SCHEMA; + +@SuppressWarnings("SameParameterValue") +public class GTDataFixers { + + private static final BiFunction SAME_NAMESPACED = NamespacedSchema::new; + + public static void init() { + if (!ConfigHolder.INSTANCE.compat.doDatafixers) { + return; + } + + GTCEu.LOGGER.info("Registering data fixers"); + + DataFixesInternals api = DataFixesInternals.get(); + + DataFixerBuilder builder = new DataFixerBuilder(GTCEuAPI.GT_DATA_VERSION); + addFixers(builder); + + ExecutorService executor = Executors.newSingleThreadExecutor( + new ThreadFactoryBuilder().setNameFormat("GTCEu Datafixer Bootstrap") + .setDaemon(true).setPriority(1).build()); + DataFixerBuilder.Result result = builder.build(); + result.optimize(DataFixTypes.TYPES_FOR_LEVEL_LIST, executor); + api.registerFixer(GTCEuAPI.GT_DATA_VERSION, result.fixer()); + } + + public static void addFixers(DataFixerBuilder builder) { + Schema schemaV0 = builder.addSchema(0, BASE_SCHEMA); + builder.addFixer(new AddNewChoices(schemaV0, "Added GT block entities", References.BLOCK_ENTITY)); + + Schema schemaV1 = builder.addSchema(1, SAME_NAMESPACED); + builder.addFixer(ItemRenameFix.create(schemaV1, "advanced_nanomuscle_chestplate rename fix", + createRenamer("gtceu:avanced_nanomuscle_chestplate", "gtceu:advanced_nanomuscle_chestplate"))); + + builder.addFixer(ItemRenameFix.create(schemaV1, "U238 item rename fix", + createRenamer(Pattern.compile("gtceu:(.*)uranium_"), "gtceu:$1uranium_238_"))); + builder.addFixer(BlockRenameFix.create(schemaV1, "U238 block rename fix", + createRenamer(Pattern.compile("gtceu:(.*)uranium_"), "gtceu:$1uranium_238_"))); + builder.addFixer(ItemRenameFix.create(schemaV1, "Pu239 item rename fix", + createRenamer(Pattern.compile("gtceu:(.*)plutonium_"), "gtceu:$1plutonium_239_"))); + builder.addFixer(BlockRenameFix.create(schemaV1, "Pu239 block rename fix", + createRenamer(Pattern.compile("gtceu:(.*)plutonium_"), "gtceu:$1plutonium_239_"))); + builder.addFixer(ItemRenameFix.create(schemaV1, "Red granite item rename fix", + createRenamer(Pattern.compile("gtceu:(.*)granite_red"), "gtceu:$1red_granite"))); + builder.addFixer(BlockRenameFix.create(schemaV1, "Red granite block rename fix", + createRenamer(Pattern.compile("gtceu:(.*)granite_red"), "gtceu:$1red_granite"))); + + builder.addFixer(ItemRenameFix.create(schemaV1, "Raw oil bucket rename fix", + createRenamer(OilVariantsRenameFix.RENAMED_ITEM_IDS))); + builder.addFixer(BlockRenameFix.create(schemaV1, "Raw oil block rename fix", + createRenamer(OilVariantsRenameFix.RENAMED_BLOCK_IDS))); + + builder.addFixer(new GTItemStackComponentizationFix(schemaV1)); + Schema schemaV2 = builder.addSchema(2, SAME_NAMESPACED); + builder.addFixer(ItemRenameFix.create(schemaV2, "Tungstensteel rename fix", + createRenamer(Pattern.compile("gtceu:(.*)tungstensteel"), "gtceu:$1tungsten_steel"))); + + builder.addFixer(ItemRenameFix.create(schemaV2, "Palladium Substation Casing item rename fix", + createRenamer("gtceu:palladium_substation", "gtceu:palladium_substation_casing"))); + builder.addFixer(BlockRenameFix.create(schemaV2, "Palladium Substation Casing block rename fix", + createRenamer("gtceu:palladium_substation", "gtceu:palladium_substation_casing"))); + + Schema schemaV3 = builder.addSchema(3, SAME_NAMESPACED); + builder.addFixer(new GTToolComponentFix(schemaV3)); + builder.addFixer(new EntityDamageBehaviorFix(schemaV3)); + + Schema schemaV4 = builder.addSchema(4, SAME_NAMESPACED); + builder.addFixer(new DataItemComponentFix(schemaV4)); + builder.addFixer(ItemRenameFix.create(schemaV1, "Limonite rename fix", + createRenamer(Pattern.compile("gtceu:(.*)yellow_limonite"), "gtceu:$1limonite"))); + builder.addFixer(BlockRenameFix.create(schemaV1, "Limonite rename fix", + createRenamer(Pattern.compile("gtceu:(.*)yellow_limonite"), "gtceu:$1limonite"))); + } + + private static UnaryOperator createRenamer(String oldName, String newName) { + return id -> Objects.equals(NamespacedSchema.ensureNamespaced(id), oldName) ? newName : id; + } + + private static UnaryOperator createRenamer(Map renameMap) { + return id -> renameMap.getOrDefault(NamespacedSchema.ensureNamespaced(id), id); + } + + private static UnaryOperator createRenamer(Pattern check, String replaceWith) { + return id -> check.matcher(NamespacedSchema.ensureNamespaced(id)).replaceAll(replaceWith); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/DataItemComponentFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/DataItemComponentFix.java index 8b137891791..3c996b22eb2 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/DataItemComponentFix.java +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/DataItemComponentFix.java @@ -1 +1,21 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; +import net.minecraft.util.datafix.fixes.ItemStackComponentRemainderFix; + +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.Nullable; + +public class DataItemComponentFix extends ItemStackComponentRemainderFix { + + public DataItemComponentFix(Schema outputSchema) { + super(outputSchema, "GTDataItemComponentFix", "gtceu:data_item"); + } + + @SuppressWarnings("NullableProblems") // this method is passed to Optional#map, where null is a valid return value. + @Override + protected @Nullable Dynamic fixComponent(Dynamic tag) { + // remove the old tag entirely to be replaced with the new one + return null; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/EntityDamageBehaviorFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/EntityDamageBehaviorFix.java new file mode 100644 index 00000000000..0290d288936 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/EntityDamageBehaviorFix.java @@ -0,0 +1,43 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; + +import com.gregtechceu.gtceu.api.datafixer.fixes.ToolBehaviorRemainderFix; + +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +public class EntityDamageBehaviorFix extends ToolBehaviorRemainderFix { + + public EntityDamageBehaviorFix(Schema outputSchema) { + super(outputSchema, "EntityDamageBehaviorFix", "gtceu:tool_behaviors"); + } + + @Override + protected @NotNull Dynamic fixBehavior(@NotNull Dynamic tag) { + Optional> bonusList = tag.get("bonus_list").result(); + tag = tag.remove("bonus_list"); + + if (bonusList.isPresent()) { + final Dynamic dynamic = tag; + var map = bonusList.get().asMap(key -> key.asString(""), + value -> value.asFloat(0.0f)); + if (map.isEmpty()) return tag; + + tag = tag.set("bonus_list", tag.createList( + map.entrySet().stream() + .map(entry -> { + Dynamic bonus = dynamic.emptyMap() + .set("bonus", dynamic.createFloat(entry.getValue())); + if (entry.getKey().isEmpty()) { + bonus = bonus.set("entities", bonus.emptyList()); + } else { + bonus = bonus.set("entities", bonus.createString("#" + entry.getKey())); + } + return bonus; + }))); + } + return tag; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/GTItemStackComponentizationFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/GTItemStackComponentizationFix.java new file mode 100644 index 00000000000..cad802e212e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/GTItemStackComponentizationFix.java @@ -0,0 +1,268 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; + +import com.gregtechceu.gtceu.utils.FormattingUtil; + +import net.minecraft.util.datafix.fixes.References; +import net.minecraft.util.datafix.schemas.NamespacedSchema; + +import com.mojang.datafixers.DataFix; +import com.mojang.datafixers.DataFixUtils; +import com.mojang.datafixers.TypeRewriteRule; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.OptionalDynamic; + +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +public class GTItemStackComponentizationFix extends DataFix { + + private static final Set ARMOR_IDS = Set.of( + "gtceu:nightvision_goggles", + "gtceu:nanomuscle_chestplate", + "gtceu:nanomuscle_leggings", + "gtceu:nanomuscle_boots", + "gtceu:nanomuscle_helmet", + "gtceu:face_mask", + "gtceu:rubber_gloves", + "gtceu:hazmat_chestpiece", + "gtceu:hazmat_leggings", + "gtceu:hazmat_boots", + "gtceu:hazmat_headpiece", + "gtceu:quarktech_chestplate", + "gtceu:quarktech_leggings", + "gtceu:quarktech_boots", + "gtceu:quarktech_helmet", + "gtceu:liquid_fuel_jetpack", + "gtceu:electric_jetpack", + "gtceu:advanced_electric_jetpack", + "gtceu:avanced_nanomuscle_chestplate", + "gtceu:advanced_quarktech_chestplate"); + + public GTItemStackComponentizationFix(Schema outputSchema) { + super(outputSchema, true); + } + + @Override + protected TypeRewriteRule makeRule() { + return this.writeFixAndRead( + "ItemStack componentization: GTCEuM edition", + this.getInputSchema().getType(References.ITEM_STACK), + this.getOutputSchema().getType(References.ITEM_STACK), + dynamic -> { + Optional> optional = ItemStackData.read(dynamic).map(data -> { + fixItemStack(data, data.tag); + return data.write(); + }); + return DataFixUtils.orElse(optional, dynamic); + }); + } + + private static void fixItemStack(ItemStackData data, Dynamic tag) { + // Fix tool info tag + OptionalDynamic gtTool = data.removeTag("GT.Tool"); + if (gtTool.result().isPresent()) { + Dynamic dynamic = tag.emptyMap() + .set("tool_speed", tag.createFloat(gtTool.get("ToolSpeed").asFloat(0.0f))) + .set("attack_damage", tag.createFloat(gtTool.get("AttackDamage").asFloat(0.0f))) + .set("enchantability", tag.createInt(gtTool.get("Enchantability").asInt(0))) + .set("harvest_level", tag.createInt(gtTool.get("HarvestLevel").asInt(0))) + .set("last_crafting_use", tag.createInt(gtTool.get("LastCraftingUse").asInt(0))); + data.setComponent("gtceu:gt_tool", dynamic); + + data.setComponent("minecraft:max_damage", gtTool.get("MaxDamage")); + data.setComponent("minecraft:damage", gtTool.get("Damage")); + OptionalDynamic dynamic1 = gtTool.get("TintColor"); + if (dynamic1.result().isPresent()) { + Dynamic colorDynamic = tag.emptyMap() + .set("rgb", tag.createInt(dynamic1.asInt(0))) + .set("showInTooltip", tag.createBoolean(false)); + data.setComponent("minecraft:dyed_color", colorDynamic); + } + data.setComponent("gtceu:disallow_container_item", gtTool.get("DisallowContainerItem")); + } + + // fix tool behaviors tag + fixGtToolBehaviors(data, tag); + + // Fix power info tags + if (tag.get("Charge").result().isPresent()) { + OptionalDynamic charge = data.removeTag("Charge"); + OptionalDynamic maxCharge = data.removeTag("MaxCharge"); + OptionalDynamic infinite = data.removeTag("Infinite"); + OptionalDynamic dischargeMode = data.removeTag("DischargeMode"); + Dynamic dynamic = tag.emptyMap() + .set("max_charge", tag.createLong(maxCharge.asLong(-1))) + .set("charge", tag.createLong(charge.asLong(0))) + .set("infinite", tag.createBoolean(infinite.asBoolean(false))) + .set("discharge_mode", tag.createBoolean(dischargeMode.asBoolean(false))); + data.setComponent("gtceu:energy_content", dynamic); + } + + // Fix magnet tag + if (tag.get("IsActive").result().isPresent()) { + OptionalDynamic isActive = data.removeTag("IsActive"); + data.setComponent("item_magnet", isActive); + } + + // Fix armors + if (data.is(ARMOR_IDS)) { + OptionalDynamic toggleTimer = data.removeTag("toggleTimer"); + OptionalDynamic hover = data.removeTag("hover"); + OptionalDynamic burnTimer = data.removeTag("burnTimer"); + OptionalDynamic canShare = data.removeTag("canShare"); + OptionalDynamic nightVision = data.removeTag("Nightvision"); + OptionalDynamic consumerTicks = data.removeTag("consumerTicks"); + Dynamic dynamic = tag.emptyMap() + .set("toggle_timer", tag.createByte(toggleTimer.asByte((byte) 0))) + .set("hover", tag.createBoolean(hover.asBoolean(false))) + .set("burn_timer", tag.createShort(burnTimer.asShort((short) 0))) + .set("can_share", tag.createBoolean(canShare.asBoolean(false))) + .set("nightvision", tag.createBoolean(nightVision.asBoolean(false))) + .set("consumer_ticks", tag.createByte(consumerTicks.asByte((byte) 0))); + data.setComponent("gtceu:armor", dynamic); + } + } + + private static void fixGtToolBehaviors(ItemStackData data, Dynamic tag) { + OptionalDynamic gtBehaviorsOpt = data.removeTag("GT.Behaviours"); + + Optional> gtBehaviors = gtBehaviorsOpt.result(); + if (gtBehaviors.isPresent()) { + Dynamic dynamic = tag.emptyMap() + .set("max_column", tag.createInt(gtBehaviors.get().remove("MaxAoEColumn").asInt(0))) + .set("max_row", tag.createInt(gtBehaviors.get().remove("MaxAoERow").asInt(0))) + .set("max_layer", tag.createInt(gtBehaviors.get().remove("MaxAoELayer").asInt(0))) + .set("column", tag.createInt(gtBehaviors.get().remove("AoEColumn").asInt(0))) + .set("row", tag.createInt(gtBehaviors.get().remove("AoERow").asInt(0))) + .set("layer", tag.createInt(gtBehaviors.get().remove("AoELayer").asInt(0))); + data.setComponent("gtceu:aoe", dynamic); + + Map> map = gtBehaviors.get().asMap(val -> val.asString(""), + Function.identity()); + if (!map.isEmpty()) { + dynamic = tag.emptyMap(); + + for (var entry : map.entrySet()) { + if (entry.getKey().equals("RelocateMinedBlocks")) { + data.setComponent("gtceu:relocate_mined_blocks", createEmpty(tag)); + continue; + } else if (entry.getKey().contains("AoE")) { + continue; + } + dynamic = dynamic.set("gtceu:" + FormattingUtil.toLowerCaseUnderscore(entry.getKey()), + createEmpty(tag)); + } + + data.setComponent("gtceu:tool_behaviors", dynamic); + } + } + } + + // I love generics <3 + private static Dynamic createEmpty(Dynamic dynamic) { + return new Dynamic<>(dynamic.getOps(), dynamic.getOps().empty()); + } + + static class ItemStackData { + + private final String item; + private Dynamic components; + private final Dynamic remainder; + Dynamic tag; + + private ItemStackData(String pItem, Dynamic pNbt) { + this.item = NamespacedSchema.ensureNamespaced(pItem); + this.components = pNbt.emptyMap(); + this.tag = pNbt.get("components").get("minecraft:custom_data") + .result().orElseGet(() -> (Dynamic) pNbt.get("tag").orElseEmptyMap()); + this.remainder = pNbt.remove("tag").set("components", pNbt.get("components") + .orElseEmptyMap().remove("minecraft:custom_data")); + } + + public static Optional read(final Dynamic pTag) { + return pTag.get("id") + .asString() + .map(itemId -> new ItemStackData(itemId, pTag)) + .result(); + } + + public OptionalDynamic removeTag(String pKey) { + OptionalDynamic optionaldynamic = this.tag.get(pKey); + this.tag = this.tag.remove(pKey); + return optionaldynamic; + } + + public void setComponent(String pComponent, Dynamic pValue) { + this.components = this.components.set(pComponent, pValue); + } + + public void setComponent(String pComponent, OptionalDynamic pValue) { + pValue.result().ifPresent(p_332105_ -> this.components = this.components.set(pComponent, p_332105_)); + } + + public Dynamic moveTagInto(String pOldKey, Dynamic pTag, String pNewKey) { + Optional> optional = this.removeTag(pOldKey).result(); + return optional.isPresent() ? pTag.set(pNewKey, optional.get()) : pTag; + } + + public void moveTagToComponent(String pKey, String pComponent, Dynamic pTag) { + Optional> optional = this.removeTag(pKey).result(); + if (optional.isPresent() && !optional.get().equals(pTag)) { + this.setComponent(pComponent, optional.get()); + } + } + + public void moveTagToComponent(String pKey, String pComponent) { + this.removeTag(pKey).result().ifPresent(p_330514_ -> this.setComponent(pComponent, p_330514_)); + } + + public void fixSubTag(String pKey, boolean pSkipIfEmpty, UnaryOperator> pFixer) { + OptionalDynamic optionaldynamic = this.tag.get(pKey); + if (!pSkipIfEmpty || !optionaldynamic.result().isEmpty()) { + Dynamic dynamic = optionaldynamic.orElseEmptyMap(); + dynamic = pFixer.apply(dynamic); + if (dynamic.equals(dynamic.emptyMap())) { + this.tag = this.tag.remove(pKey); + } else { + this.tag = this.tag.set(pKey, dynamic); + } + } + } + + public Dynamic write() { + Dynamic dynamic = this.tag; + + if (!this.components.equals(this.tag.emptyMap())) { + dynamic = dynamic.set("components", this.components); + } + + return mergeRemainder(dynamic, this.remainder); + } + + private static Dynamic mergeRemainder(Dynamic tag, Dynamic remainder) { + DynamicOps ops = tag.getOps(); + return ops.getMap(tag.getValue()) + .flatMap(mapLike -> ops.mergeToMap(remainder.convert(ops).getValue(), mapLike)) + .map(object -> new Dynamic<>(ops, object)) + .result() + .orElse(tag); + } + + public boolean is(String pItem) { + return this.item.equals(pItem); + } + + public boolean is(Set pItems) { + return pItems.contains(this.item); + } + + public boolean hasComponent(String pComponent) { + return this.components.get(pComponent).result().isPresent(); + } + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/GTToolComponentFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/GTToolComponentFix.java new file mode 100644 index 00000000000..1d3bc76e34a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/GTToolComponentFix.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; + +import net.minecraft.util.datafix.fixes.ItemStackComponentRemainderFix; + +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +public class GTToolComponentFix extends ItemStackComponentRemainderFix { + + public GTToolComponentFix(Schema outputSchema) { + super(outputSchema, "GTToolComponentFix", "gtceu:gt_tool"); + } + + @Override + protected @NotNull Dynamic fixComponent(Dynamic tag) { + tag.remove("tool_speed").remove("attack_damage").remove("harvest_level"); + + Optional> lastCraftingUse = tag.get("last_crafting_use").result(); + if (lastCraftingUse.isEmpty()) { + tag = tag.set("last_crafting_use", tag.createInt(0)); + } + + return tag; + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java new file mode 100644 index 00000000000..b4efc7f6654 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/fixes/OilVariantsRenameFix.java @@ -0,0 +1,20 @@ +package com.gregtechceu.gtceu.common.datafixer.fixes; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class OilVariantsRenameFix { + + public static final Map RENAMED_ITEM_IDS = ImmutableMap.builder() + .put("gtceu:oil_heavy_bucket", "gtceu:heavy_oil_bucket") + .put("gtceu:oil_light_bucket", "gtceu:light_oil_bucket") + .put("gtceu:oil_medium_bucket", "gtceu:raw_oil_bucket") + .build(); + + public static final Map RENAMED_BLOCK_IDS = ImmutableMap.builder() + .put("gtceu:oil_heavy", "gtceu:heavy_oil") + .put("gtceu:oil_light", "gtceu:light_oil") + .put("gtceu:oil_medium", "gtceu:raw_oil") + .build(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java new file mode 100644 index 00000000000..09d080e9415 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/common/datafixer/schemas/V0.java @@ -0,0 +1,64 @@ +package com.gregtechceu.gtceu.common.datafixer.schemas; + +import com.gregtechceu.gtceu.api.machine.MachineDefinition; +import com.gregtechceu.gtceu.api.registry.GTRegistries; +import com.gregtechceu.gtceu.common.data.GTReferences; + +import net.minecraft.util.datafix.fixes.References; +import net.minecraft.util.datafix.schemas.NamespacedSchema; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.datafixers.types.templates.TypeTemplate; + +import java.util.*; +import java.util.function.Supplier; + +public class V0 extends NamespacedSchema { + + public V0(int versionKey, Schema parent) { + super(versionKey, parent); + } + + @Override + public void registerTypes(Schema schema, Map> entityTypes, + Map> blockEntityTypes) { + super.registerTypes(schema, entityTypes, blockEntityTypes); + schema.registerType(false, GTReferences.MATERIAL_NAME, () -> DSL.constType(namespacedString())); + } + + @Override + public Map> registerBlockEntities(Schema schema) { + Map> map = super.registerBlockEntities(schema); + for (MachineDefinition definition : GTRegistries.MACHINES) { + registerInventory(schema, map, definition.getId().toString()); + } + return map; + } + + protected static void registerInventory(Schema schema, Map> map, String name) { + schema.register(map, name, () -> DSL.or( + DSL.fields( + "importItems", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema)))), + "exportItems", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema))))), + DSL.or( + DSL.fields( + "inventory", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema))))), + DSL.or( + DSL.fields( + "cache", + DSL.field("storage", + DSL.field("Items", + DSL.list(References.ITEM_STACK.in(schema))))), + DSL.remainder())))); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/behavior/DataItemBehavior.java b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/DataItemBehavior.java index eda26a9aebc..b500374a527 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/behavior/DataItemBehavior.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/DataItemBehavior.java @@ -1,14 +1,17 @@ package com.gregtechceu.gtceu.common.item.behavior; -import com.gregtechceu.gtceu.api.blockentity.MetaMachineBlockEntity; import com.gregtechceu.gtceu.api.capability.GTCapabilityHelper; import com.gregtechceu.gtceu.api.capability.ICoverable; import com.gregtechceu.gtceu.api.item.component.IInteractionItem; +import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.feature.IDataStickInteractable; import com.gregtechceu.gtceu.common.data.item.GTDataComponents; import com.gregtechceu.gtceu.common.item.datacomponents.BindingData; import com.gregtechceu.gtceu.common.machine.owner.MachineOwner; +import com.gregtechceu.gtceu.core.mixins.EntityAccessor; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; @@ -24,50 +27,50 @@ public class DataItemBehavior implements IInteractionItem { protected DataItemBehavior() {} @Override - public InteractionResultHolder use(ItemStack item, Level level, Player player, - InteractionHand usedHand) { - if (player.isShiftKeyDown()) { - ItemStack stack = player.getItemInHand(usedHand); - int permissionLevel = 0; - while (player.hasPermissions(permissionLevel)) permissionLevel++; - + public InteractionResultHolder use(ItemStack stack, Level level, + Player player, InteractionHand usedHand) { + if (player.isSecondaryUseActive()) { + int permissionLevel = ((EntityAccessor) player).gtceu$getPermissionLevel(); stack.set(GTDataComponents.BINDING_DATA, new BindingData(permissionLevel, player.getUUID())); - return new InteractionResultHolder<>(InteractionResult.SUCCESS, stack); + + return InteractionResultHolder.sidedSuccess(stack, level.isClientSide); } - return IInteractionItem.super.use(item, level, player, usedHand); + return IInteractionItem.super.use(stack, level, player, usedHand); } @Override public InteractionResult onItemUseFirst(ItemStack itemStack, UseOnContext context) { - ICoverable coverable = GTCapabilityHelper.getCoverable(context.getLevel(), context.getClickedPos(), - context.getClickedFace()); - if (coverable != null && - coverable.getCoverAtSide(context.getClickedFace()) instanceof IDataStickInteractable interactable) { + Level level = context.getLevel(); + BlockPos pos = context.getClickedPos(); + Direction face = context.getClickedFace(); + Player player = context.getPlayer(); + + ICoverable coverable = GTCapabilityHelper.getCoverable(level, pos, face); + if (coverable != null && coverable.getCoverAtSide(face) instanceof IDataStickInteractable interactable) { if (context.isSecondaryUseActive()) { if (!itemStack.has(GTDataComponents.RESEARCH_ITEM)) { - return interactable.onDataStickShiftUse(context.getPlayer(), itemStack); + return interactable.onDataStickShiftUse(player, itemStack); } } else { - return interactable.onDataStickUse(context.getPlayer(), itemStack); + return interactable.onDataStickUse(player, itemStack); } } - if (context.getLevel().getBlockEntity(context.getClickedPos()) instanceof MetaMachineBlockEntity blockEntity) { - var machine = blockEntity.getMetaMachine(); - if (!MachineOwner.canOpenOwnerMachine(context.getPlayer(), machine)) { + + MetaMachine machine = MetaMachine.getMachine(level, pos); + if (machine != null) { + if (!MachineOwner.canOpenOwnerMachine(player, machine)) { return InteractionResult.FAIL; } if (machine instanceof IDataStickInteractable interactable) { if (context.isSecondaryUseActive()) { if (!itemStack.has(GTDataComponents.RESEARCH_ITEM)) { - return interactable.onDataStickShiftUse(context.getPlayer(), itemStack); + return interactable.onDataStickShiftUse(player, itemStack); } } else { - return interactable.onDataStickUse(context.getPlayer(), itemStack); + return interactable.onDataStickUse(player, itemStack); } - } else { - return InteractionResult.PASS; } } - return InteractionResult.sidedSuccess(context.getLevel().isClientSide); + return InteractionResult.PASS; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/behavior/FacadeItemBehaviour.java b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/FacadeItemBehaviour.java index d0687ddd720..59a880fbd23 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/behavior/FacadeItemBehaviour.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/FacadeItemBehaviour.java @@ -2,7 +2,6 @@ import com.gregtechceu.gtceu.api.item.component.ICustomDescriptionId; import com.gregtechceu.gtceu.api.item.component.ISubItemHandler; -import com.gregtechceu.gtceu.api.item.datacomponents.FacadeWrapper; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.item.GTDataComponents; import com.gregtechceu.gtceu.utils.memoization.GTMemoizer; @@ -53,7 +52,7 @@ public static void setFacadeState(ItemStack itemStack, BlockState state) { if (!isValidFacade(state)) { state = Blocks.STONE.defaultBlockState(); } - itemStack.set(GTDataComponents.FACADE, new FacadeWrapper(state)); + itemStack.set(GTDataComponents.FACADE, state); } public static boolean isValidFacade(ItemStack itemStack) { @@ -89,10 +88,9 @@ private static BlockState getFacadeStateUnsafe(ItemStack itemStack) { if (facade == null) { return null; } - BlockState facadeStack = facade.state(); - if (facadeStack.isEmpty() || !isValidFacade(facadeStack)) { + if (facade.isEmpty() || !isValidFacade(facade)) { return null; } - return facadeStack; + return facade; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/modules/ImageModuleBehaviour.java b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/modules/ImageModuleBehaviour.java similarity index 97% rename from src/main/java/com/gregtechceu/gtceu/common/item/modules/ImageModuleBehaviour.java rename to src/main/java/com/gregtechceu/gtceu/common/item/behavior/modules/ImageModuleBehaviour.java index a9947553b4c..5bd1b5560c8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/modules/ImageModuleBehaviour.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/modules/ImageModuleBehaviour.java @@ -1,4 +1,4 @@ -package com.gregtechceu.gtceu.common.item.modules; +package com.gregtechceu.gtceu.common.item.behavior.modules; import com.gregtechceu.gtceu.api.gui.GuiTextures; import com.gregtechceu.gtceu.api.item.component.IMonitorModuleItem; diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/modules/TextModuleBehaviour.java b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/modules/TextModuleBehaviour.java similarity index 71% rename from src/main/java/com/gregtechceu/gtceu/common/item/modules/TextModuleBehaviour.java rename to src/main/java/com/gregtechceu/gtceu/common/item/behavior/modules/TextModuleBehaviour.java index 69e6c0b68e0..b30d0954e39 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/modules/TextModuleBehaviour.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/behavior/modules/TextModuleBehaviour.java @@ -1,6 +1,7 @@ -package com.gregtechceu.gtceu.common.item.modules; +package com.gregtechceu.gtceu.common.item.behavior.modules; import com.gregtechceu.gtceu.api.gui.GuiTextures; +import com.gregtechceu.gtceu.api.gui.widget.FloatInputWidget; import com.gregtechceu.gtceu.api.item.component.IAddInformation; import com.gregtechceu.gtceu.api.item.component.IMonitorModuleItem; import com.gregtechceu.gtceu.api.placeholder.MultiLineComponent; @@ -9,13 +10,13 @@ import com.gregtechceu.gtceu.client.renderer.monitor.IMonitorRenderer; import com.gregtechceu.gtceu.client.renderer.monitor.MonitorTextRenderer; import com.gregtechceu.gtceu.common.data.item.GTDataComponents; +import com.gregtechceu.gtceu.common.item.datacomponents.FormatStringList; import com.gregtechceu.gtceu.common.item.datacomponents.TextLineList; import com.gregtechceu.gtceu.common.machine.multiblock.electric.CentralMonitorMachine; import com.gregtechceu.gtceu.common.machine.multiblock.electric.monitor.MonitorGroup; import com.gregtechceu.gtceu.common.network.packets.SCPacketMonitorGroupNBTChange; import com.lowdragmc.lowdraglib.gui.widget.ButtonWidget; -import com.lowdragmc.lowdraglib.gui.widget.TextFieldWidget; import com.lowdragmc.lowdraglib.gui.widget.Widget; import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup; import com.lowdragmc.lowdraglib.gui.widget.codeeditor.CodeEditorWidget; @@ -28,13 +29,12 @@ import net.minecraft.world.item.TooltipFlag; import net.neoforged.neoforge.network.PacketDistributor; +import org.apache.commons.lang3.mutable.MutableFloat; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.UUID; -import java.util.function.Supplier; -import java.util.stream.Collectors; public class TextModuleBehaviour implements IMonitorModuleItem, IAddInformation { @@ -63,7 +63,7 @@ public void tick(ItemStack stack, CentralMonitorMachine machine, MonitorGroup gr @Override public IMonitorRenderer getRenderer(ItemStack stack) { TextLineList lines = stack.getOrDefault(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY); - return new MonitorTextRenderer(MultiLineComponent.of(lines.lines()), Math.max(lines.scale(), .0001)); + return new MonitorTextRenderer(MultiLineComponent.of(lines.lines()), Math.max(lines.scale(), 0.0001f)); } @Override @@ -71,52 +71,41 @@ public Widget createUIWidget(ItemStack stack, CentralMonitorMachine machine, Mon WidgetGroup builder = new WidgetGroup(); CodeEditorWidget editor = new CodeEditorWidget(0, 0, 120, 80); // editor.codeEditor.setLanguageDefinition(PlaceholderHandler.LANG_DEFINITION); - TextFieldWidget scaleInput = new TextFieldWidget( + + float scaleValue = stack.getOrDefault(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY).scale(); + if (!stack.has(GTDataComponents.TEXT_LINE_LIST)) { + stack.set(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY); + PacketDistributor.sendToServer(new SCPacketMonitorGroupNBTChange(stack, group, machine)); + } + MutableFloat currentScale = new MutableFloat(scaleValue); + FloatInputWidget scaleInput = new FloatInputWidget( -50, 47, 40, 10, - null, - null); + currentScale::getValue, + currentScale::setValue); + scaleInput.setHoverTooltips(Component.translatable("gtceu.gui.central_monitor.text_scale")); + builder.addWidget(scaleInput); + ButtonWidget saveButton = new ButtonWidget(-40, 22, 20, 20, click -> { if (!click.isRemote) return; - List lines = editor.getLines().stream() - .map(Component::literal) - .collect(Collectors.toList()); - float scale = 1.0f; - try { - scale = Float.parseFloat(scaleInput.getCurrentString()); - } catch (NumberFormatException ignored) {} - stack.set(GTDataComponents.TEXT_LINE_LIST, new TextLineList(lines, scale)); + stack.set(GTDataComponents.FORMAT_STRING_LIST, new FormatStringList(editor.getLines())); + + final float newValue = Mth.clamp(currentScale.floatValue(), 0.0001f, 1000.0f); + stack.update(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY, lines -> lines.withScale(newValue)); PacketDistributor.sendToServer(new SCPacketMonitorGroupNBTChange(stack, group, machine)); }); saveButton.setButtonTexture(GuiTextures.BUTTON_CHECK); - List tmp = new ArrayList<>(); - Supplier scaleInputSupplier = () -> { - if (tmp.isEmpty()) { - tmp.add(true); - } else { - scaleInput.setTextSupplier(null); - } - if (!stack.has(GTDataComponents.TEXT_LINE_LIST)) { - stack.update(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY, - lines -> lines.withScale(1.0f)); - PacketDistributor.sendToServer(new SCPacketMonitorGroupNBTChange(stack, group, machine)); - return "1"; - } - return String.valueOf(Mth.clamp(stack.get(GTDataComponents.TEXT_LINE_LIST).scale(), .0001f, 1000f)); - }; - scaleInput.setTextSupplier(scaleInputSupplier); - scaleInput.setHoverTooltips(Component.translatable("gtceu.gui.central_monitor.text_scale")); - List formatStringLines = stack.getOrDefault(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY) - .lines().stream() - .map(Component::getString) - .collect(Collectors.toList()); + builder.addWidget(saveButton); + + List formatStringLines = stack.getOrDefault(GTDataComponents.FORMAT_STRING_LIST, FormatStringList.EMPTY) + .lines(); editor.setLines(formatStringLines); builder.addWidget(editor); - builder.addWidget(saveButton); + Widget placeholderReference = PlaceholderHandler.getPlaceholderHandlerUI(""); - builder.addWidget(scaleInput); placeholderReference.setSelfPosition(-100, -50); builder.addWidget(placeholderReference); + return builder; } @@ -138,19 +127,17 @@ public void setScale(ItemStack stack, float scale) { } public void setPlaceholderText(ItemStack stack, String text) { - List lines = new ArrayList<>(); - for (String line : text.split("\n")) { - lines.add(Component.literal(line)); - } - stack.update(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY, - textLineList -> textLineList.withLines(lines)); + List lines = Arrays.asList(text.split("\n")); + + stack.update(GTDataComponents.FORMAT_STRING_LIST, FormatStringList.EMPTY, + formatStringList -> formatStringList.withLines(lines)); } public String getPlaceholderText(ItemStack stack) { StringBuilder formatStringLines = new StringBuilder(); - List lines = stack.getOrDefault(GTDataComponents.TEXT_LINE_LIST, TextLineList.EMPTY).lines(); - for (Component line : lines) { - formatStringLines.append(line.getString()).append('\n'); + List lines = stack.getOrDefault(GTDataComponents.FORMAT_STRING_LIST, FormatStringList.EMPTY).lines(); + for (String line : lines) { + formatStringLines.append(line).append('\n'); } return formatStringLines.toString(); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/item/datacomponents/FormatStringList.java b/src/main/java/com/gregtechceu/gtceu/common/item/datacomponents/FormatStringList.java index ab0eab43b09..29cf0a35ecc 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/item/datacomponents/FormatStringList.java +++ b/src/main/java/com/gregtechceu/gtceu/common/item/datacomponents/FormatStringList.java @@ -5,13 +5,14 @@ import com.mojang.serialization.Codec; import io.netty.buffer.ByteBuf; +import lombok.With; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collections; import java.util.List; -public record FormatStringList(List lines) { +public record FormatStringList(@With List lines) { public static final Codec CODEC = Codec.STRING.listOf() .xmap(FormatStringList::new, FormatStringList::lines); diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java index c06921a20e4..6154a965f47 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/electric/WorldAcceleratorMachine.java @@ -25,40 +25,37 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.BlockHitResult; -import it.unimi.dsi.fastutil.objects.Object2BooleanFunction; -import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import lombok.Getter; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Set; public class WorldAcceleratorMachine extends TieredEnergyMachine implements IControllable { - private static final Map> blacklistedClasses = new Object2ObjectOpenHashMap<>(); - private static final Object2BooleanFunction> blacklistCache = new Object2BooleanOpenHashMap<>(); + private static final Set> blacklistedTypes = new ObjectOpenHashSet<>(); private static boolean gatheredClasses = false; - // Hard-coded blacklist for blockentities - private static final List blockEntityClassNamesBlackList = new ArrayList<>(); - - public static final BooleanProperty RANDOM_TICK_PROPERTY = GTMachineModelProperties.IS_RANDOM_TICK_MODE; + // Hardcoded blacklist for block entity types + private static final List blockEntityTypeBlackList = new ArrayList<>(); protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder( WorldAcceleratorMachine.class, TieredEnergyMachine.MANAGED_FIELD_HOLDER); @@ -84,7 +81,7 @@ public class WorldAcceleratorMachine extends TieredEnergyMachine implements ICon @DescSynced @RequireRerender private boolean active = false; - private TickableSubscription tickSubs; + private @Nullable TickableSubscription tickSubs; public WorldAcceleratorMachine(IMachineBlockEntity holder, int tier, Object... args) { super(holder, tier, GTMachineUtils.defaultTankSizeFunction, args); @@ -94,13 +91,13 @@ public WorldAcceleratorMachine(IMachineBlockEntity holder, int tier, Object... a } @Override - protected @NotNull NotifiableEnergyContainer createEnergyContainer(Object @NotNull... args) { + protected NotifiableEnergyContainer createEnergyContainer(Object @NotNull... args) { long tierVoltage = GTValues.V[getTier()]; return new NotifiableEnergyContainer(this, tierVoltage * 256L, tierVoltage, 8, 0L, 0L); } @Override - public @NotNull ManagedFieldHolder getFieldHolder() { + public ManagedFieldHolder getFieldHolder() { return MANAGED_FIELD_HOLDER; } @@ -166,15 +163,18 @@ public boolean drainEnergy(boolean simulate) { return false; } - private void tickBlockEntity(@NotNull T blockEntity) { + private void tickBlockEntity(T blockEntity) { BlockPos pos = blockEntity.getBlockPos(); - // noinspection unchecked - BlockEntityTicker blockEntityTicker = this.getLevel().getBlockState(pos).getTicker(this.getLevel(), - (BlockEntityType) blockEntity.getType()); - if (blockEntityTicker == null) return; + Level level = blockEntity.getLevel(); + if (level == null) return; + + @SuppressWarnings("unchecked") + BlockEntityTicker ticker = level.getBlockState(pos) + .getTicker(level, (BlockEntityType) blockEntity.getType()); + if (ticker == null) return; + for (int i = 0; i < speed - 1; i++) { - blockEntityTicker.tick(blockEntity.getLevel(), blockEntity.getBlockPos(), blockEntity.getBlockState(), - blockEntity); + ticker.tick(level, blockEntity.getBlockPos(), blockEntity.getBlockState(), blockEntity); } } @@ -182,21 +182,7 @@ private boolean canAccelerate(BlockEntity blockEntity) { if (blockEntity instanceof PipeBlockEntity || blockEntity instanceof IMachineBlockEntity) return false; generateWorldAcceleratorBlacklist(); - final Class blockEntityClass = blockEntity.getClass(); - if (blacklistCache.containsKey(blockEntityClass)) { - return blacklistCache.getBoolean(blockEntityClass); - } - - for (Class clazz : blacklistedClasses.values()) { - if (clazz.isAssignableFrom(blockEntityClass)) { - // Is a subclass, so it cannot be accelerated - blacklistCache.put(blockEntityClass, false); - return false; - } - } - - blacklistCache.put(blockEntityClass, true); - return true; + return blacklistedTypes.contains(blockEntity.getType()); } @Override @@ -223,8 +209,8 @@ public void setWorkingEnabled(boolean workingEnabled) { } @Override - public ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, Set toolTypes, - ItemStack held, Direction side) { + public @Nullable ResourceTexture sideTips(Player player, BlockPos pos, BlockState state, Set toolTypes, + ItemStack held, Direction side) { if (toolTypes.contains(GTToolType.SOFT_MALLET)) { return isWorkingEnabled ? GuiTextures.TOOL_PAUSE : GuiTextures.TOOL_START; } @@ -250,9 +236,9 @@ protected ItemInteractionResult onSoftMalletClick(Player playerIn, InteractionHa } @Override - protected @NotNull ItemInteractionResult onScrewdriverClick(Player playerIn, InteractionHand hand, - ItemStack held, Direction gridSide, - BlockHitResult hitResult) { + protected ItemInteractionResult onScrewdriverClick(Player playerIn, InteractionHand hand, + ItemStack held, Direction gridSide, + BlockHitResult hitResult) { if (!isRemote()) { isRandomTickMode = !isRandomTickMode; setRenderState(getRenderState().setValue(GTMachineModelProperties.IS_RANDOM_TICK_MODE, isRandomTickMode)); @@ -264,24 +250,25 @@ protected ItemInteractionResult onSoftMalletClick(Player playerIn, InteractionHa } private static void generateWorldAcceleratorBlacklist() { - if (!gatheredClasses) { - for (String name : ConfigHolder.INSTANCE.machines.worldAcceleratorBlacklist) { - if (!blacklistedClasses.containsKey(name)) { - try { - blacklistedClasses.put(name, Class.forName(name)); - } catch (ClassNotFoundException ignored) { - GTCEu.LOGGER.warn("Could not find class {} for World Accelerator Blacklist!", name); - } - } - } + if (gatheredClasses) { + return; + } + for (ResourceLocation id : blockEntityTypeBlackList) { + BlockEntityType type = BuiltInRegistries.BLOCK_ENTITY_TYPE.get(id); + if (type == null) continue; + blacklistedTypes.add(type); + } - for (String className : blockEntityClassNamesBlackList) { - try { - blacklistedClasses.put(className, Class.forName(className)); - } catch (ClassNotFoundException ignored) {} + for (ResourceLocation id : ConfigHolder.INSTANCE.machines.worldAcceleratorBlacklist) { + BlockEntityType type = BuiltInRegistries.BLOCK_ENTITY_TYPE.get(id); + if (blacklistedTypes.contains(type)) continue; + if (type == null) { + GTCEu.LOGGER.warn("Could not find block entity type {} for World Accelerator Blacklist!", id); + continue; } - - gatheredClasses = true; + blacklistedTypes.add(type); } + + gatheredClasses = true; } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CentralMonitorMachine.java b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CentralMonitorMachine.java index f16040aeb0a..d28d56439e7 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CentralMonitorMachine.java +++ b/src/main/java/com/gregtechceu/gtceu/common/machine/multiblock/electric/CentralMonitorMachine.java @@ -83,7 +83,7 @@ public class CentralMonitorMachine extends WorkableElectricMultiblockMachine private final Set selectedComponents = new HashSet<>(); private final List selectedTargets = new ArrayList<>(); - private MultiblockState patternFindingState; + private @Nullable MultiblockState patternFindingState; private static TraceabilityPredicate MULTI_PREDICATE = null; @@ -133,8 +133,7 @@ protected RecipeLogic createRecipeLogic(Object... args) { } public void tick() { - Level level = getLevel(); - if (!(level instanceof ServerLevel serverLevel)) { + if (!(getLevel() instanceof ServerLevel level)) { return; } @@ -149,7 +148,7 @@ public void tick() { continue; } module.tick(stack, this, group); - PacketDistributor.sendToPlayersTrackingChunk(serverLevel, new ChunkPos(getPos()), + PacketDistributor.sendToPlayersTrackingChunk(level, new ChunkPos(getPos()), new SCPacketMonitorGroupNBTChange(stack, group, this)); } } @@ -358,8 +357,8 @@ public Widget createUIWidget() { groupConfig.clearAllWidgets(); groupConfig.addWidget(new LabelWidget(0, 5, () -> { String currentName = ""; - if (configGroup.get(0) != null) { - currentName = configGroup.get(0).getName(); + if (configGroup.getFirst() != null) { + currentName = configGroup.getFirst().getName(); } return Component.translatable("gtceu.central_monitor.gui.currently_editing", currentName).getString(); })); @@ -427,7 +426,7 @@ public Widget createUIWidget() { 16, 16, GuiTextures.IO_CONFIG_COVER_SETTINGS, click -> { - if (configGroup.get(0) == null) { + if (configGroup.getFirst() == null) { openGroupConfig.accept(group); } else { openGroupConfig.accept(null); @@ -466,7 +465,7 @@ public Widget createUIWidget() { imageButtons.get(rel.getY()).get(rel.getX()).accept(it); } if (!selectedTargets.isEmpty()) { - rightClickCallbacks.getOrDefault(selectedTargets.get(0).getPos(), () -> {}).run(); + rightClickCallbacks.getOrDefault(selectedTargets.getFirst().getPos(), () -> {}).run(); } }); setTargetButton.setOnPressCallback(click -> { @@ -483,7 +482,7 @@ public Widget createUIWidget() { if (group == null) return; if (selectedTargets.isEmpty()) group.setTarget(null); else { - group.setTarget(selectedTargets.get(0).getPos()); + group.setTarget(selectedTargets.getFirst().getPos()); group.setDataSlot(dataSlot[0] - 1); } }); @@ -514,7 +513,7 @@ public Widget createUIWidget() { imageButtons.get(rel.getY()).get(rel.getX()).accept(it); } if (!selectedTargets.isEmpty()) { - rightClickCallbacks.getOrDefault(selectedTargets.get(0).getPos(), () -> {}).run(); + rightClickCallbacks.getOrDefault(selectedTargets.getFirst().getPos(), () -> {}).run(); } }); createGroupButton.setButtonTexture(new TextTexture("gtceu.central_monitor.gui.create_group")); @@ -544,7 +543,7 @@ public Widget createUIWidget() { it.remove(); } - if (!selectedTargets.isEmpty() && selectedTargets.get(0) == component) { + if (!selectedTargets.isEmpty() && selectedTargets.getFirst() == component) { ColorRectTexture rect = new ColorRectTexture(Color.BLUE); textures.setTextures(rect, texture); } else { @@ -575,7 +574,7 @@ public Widget createUIWidget() { } selectedComponents.add(component); ColorRectTexture rect = new ColorRectTexture( - (selectedTargets.isEmpty() || selectedTargets.get(0) != component) ? Color.RED : + (selectedTargets.isEmpty() || selectedTargets.getFirst() != component) ? Color.RED : Color.PINK); textures.setTextures(rect, texture); } @@ -593,7 +592,7 @@ public Widget createUIWidget() { }; Runnable rightClickCallback = () -> { if (!selectedTargets.isEmpty()) { - if (selectedTargets.get(0).getPos() == component.getPos()) { + if (selectedTargets.getFirst().getPos() == component.getPos()) { selectedTargets.clear(); if (selectedComponents.contains(component)) { ColorRectTexture rect = new ColorRectTexture(Color.RED); @@ -608,7 +607,7 @@ public Widget createUIWidget() { rightClickCallbacks.get(selectedTargets.get(0).getPos()).run(); } catch (StackOverflowError e) { GTCEu.LOGGER.error( - "Stack overflow when right-clicking monitor component {} at {} (selectedTarget is {} at {})", + "Stack overflow when right-clicking monitor component {} at {} (selectedTarget={}, at {})", component, component.getPos(), selectedTargets.get(0), selectedTargets.get(0).getPos()); } diff --git a/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java b/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java index c915353746d..5204af1066c 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java +++ b/src/main/java/com/gregtechceu/gtceu/common/network/GTNetwork.java @@ -3,9 +3,7 @@ import com.gregtechceu.gtceu.api.GTCEuAPI; import com.gregtechceu.gtceu.common.network.packets.*; import com.gregtechceu.gtceu.common.network.packets.hazard.*; -import com.gregtechceu.gtceu.common.network.packets.prospecting.SPacketProspectBedrockFluid; -import com.gregtechceu.gtceu.common.network.packets.prospecting.SPacketProspectBedrockOre; -import com.gregtechceu.gtceu.common.network.packets.prospecting.SPacketProspectOre; +import com.gregtechceu.gtceu.common.network.packets.prospecting.*; import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; import net.neoforged.neoforge.network.registration.PayloadRegistrar; @@ -28,14 +26,14 @@ public static void registerPayloads(RegisterPayloadHandlersEvent event) { registar.playToClient(SPacketSyncLevelHazards.TYPE, SPacketSyncLevelHazards.CODEC, SPacketSyncLevelHazards::execute); registar.playToClient(SPacketProspectOre.TYPE, SPacketProspectOre.CODEC, SPacketProspectOre::execute); - registar.playToClient(SPacketProspectBedrockOre.TYPE, SPacketProspectBedrockOre.CODEC, SPacketProspectBedrockOre::execute); registar.playToClient(SPacketProspectBedrockFluid.TYPE, SPacketProspectBedrockFluid.CODEC, SPacketProspectBedrockFluid::execute); + registar.playToClient(SPacketProspectBedrockOre.TYPE, SPacketProspectBedrockOre.CODEC, SPacketProspectBedrockOre::execute); registar.playToClient(SPacketSendWorldID.TYPE, SPacketSendWorldID.CODEC, SPacketSendWorldID::execute); registar.playToClient(SPacketNotifyCapeChange.TYPE, SPacketNotifyCapeChange.CODEC, SPacketNotifyCapeChange::execute); registar.playBidirectional(SCPacketShareProspection.TYPE, SCPacketShareProspection.CODEC, SCPacketShareProspection::execute); - // spotless:on + // spotless:on } } diff --git a/src/main/java/com/gregtechceu/gtceu/common/network/packets/CPacketImageRequest.java b/src/main/java/com/gregtechceu/gtceu/common/network/packets/CPacketImageRequest.java index 15675822945..e10d66334a6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/network/packets/CPacketImageRequest.java +++ b/src/main/java/com/gregtechceu/gtceu/common/network/packets/CPacketImageRequest.java @@ -3,12 +3,15 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.misc.ImageCache; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.network.handling.IPayloadContext; +import io.netty.buffer.ByteBuf; +import lombok.AccessLevel; +import lombok.Getter; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -17,23 +20,17 @@ public class CPacketImageRequest implements CustomPacketPayload { public static final ResourceLocation ID = GTCEu.id("image_request"); public static final Type TYPE = new Type<>(ID); - public static final StreamCodec CODEC = StreamCodec - .ofMember(CPacketImageRequest::encode, CPacketImageRequest::new); + public static final StreamCodec CODEC = StreamCodec.composite( + ByteBufCodecs.STRING_UTF8, CPacketImageRequest::getUrl, + CPacketImageRequest::new); + @Getter(AccessLevel.PRIVATE) private final String url; public CPacketImageRequest(String url) { this.url = url; } - public CPacketImageRequest(FriendlyByteBuf buf) { - this.url = buf.readUtf(); - } - - public void encode(FriendlyByteBuf buffer) { - buffer.writeUtf(url); - } - public void execute(IPayloadContext context) { ImageCache.queryServerImage(url, image -> { try { diff --git a/src/main/java/com/gregtechceu/gtceu/common/network/packets/SCPacketMonitorGroupNBTChange.java b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SCPacketMonitorGroupNBTChange.java index b0badd01337..35ced335855 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/network/packets/SCPacketMonitorGroupNBTChange.java +++ b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SCPacketMonitorGroupNBTChange.java @@ -5,81 +5,63 @@ import com.gregtechceu.gtceu.common.machine.multiblock.electric.CentralMonitorMachine; import com.gregtechceu.gtceu.common.machine.multiblock.electric.monitor.MonitorGroup; -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.neoforged.neoforge.common.util.LogicalSidedProvider; import net.neoforged.neoforge.items.IItemHandlerModifiable; import net.neoforged.neoforge.network.handling.IPayloadContext; +import lombok.AccessLevel; +import lombok.Getter; import org.jetbrains.annotations.NotNull; -import java.util.Optional; - public class SCPacketMonitorGroupNBTChange implements CustomPacketPayload { - public static final ResourceLocation ID = GTCEu.id("spacket_monitor_group_nbt_change"); + public static final ResourceLocation ID = GTCEu.id("monitor_group_nbt_change"); public static final Type TYPE = new Type<>(ID); public static final StreamCodec CODEC = StreamCodec - .ofMember(SCPacketMonitorGroupNBTChange::encode, SCPacketMonitorGroupNBTChange::new); + .composite( + ItemStack.OPTIONAL_STREAM_CODEC, SCPacketMonitorGroupNBTChange::getStack, + ByteBufCodecs.VAR_INT, SCPacketMonitorGroupNBTChange::getMonitorGroupId, + BlockPos.STREAM_CODEC, SCPacketMonitorGroupNBTChange::getPos, + SCPacketMonitorGroupNBTChange::new); + @Getter(AccessLevel.PRIVATE) private final ItemStack stack; + @Getter(AccessLevel.PRIVATE) private final int monitorGroupId; + @Getter(AccessLevel.PRIVATE) private final BlockPos pos; public SCPacketMonitorGroupNBTChange(ItemStack stack, MonitorGroup group, CentralMonitorMachine machine) { - this.stack = stack; - this.monitorGroupId = machine.getMonitorGroups().indexOf(group); - this.pos = machine.getPos(); + this(stack, machine.getMonitorGroups().indexOf(group), machine.getPos()); } - public SCPacketMonitorGroupNBTChange(RegistryFriendlyByteBuf buf) { - this.stack = ItemStack.STREAM_CODEC.decode(buf); - this.monitorGroupId = buf.readVarInt(); - this.pos = buf.readBlockPos(); - } - - public void encode(RegistryFriendlyByteBuf buffer) { - ItemStack.STREAM_CODEC.encode(buffer, stack); - // buffer.writeItemStack(stack, false); - buffer.writeVarInt(monitorGroupId); - buffer.writeBlockPos(pos); + public SCPacketMonitorGroupNBTChange(ItemStack stack, int monitorGroupId, BlockPos pos) { + this.stack = stack; + this.monitorGroupId = monitorGroupId; + this.pos = pos; } public void execute(IPayloadContext context) { - Level level = LogicalSidedProvider.CLIENTWORLD.get(context.flow().getReceptionSide()) - .or(() -> { - if (context.player() instanceof ServerPlayer player) { - return Optional.ofNullable(player).map(ServerPlayer::level); - } - return Optional.empty(); - }) - .orElse(null); - if (level == null) return; + Level level = context.player().level(); - MetaMachine machine = MetaMachine.getMachine(level, pos); + MetaMachine machine = MetaMachine.getMachine(level, this.pos); if (machine instanceof CentralMonitorMachine centralMonitor) { - IItemHandlerModifiable itemHandler = centralMonitor.getMonitorGroups().get(monitorGroupId) + IItemHandlerModifiable itemHandler = centralMonitor.getMonitorGroups() + .get(this.monitorGroupId) .getItemStackHandler(); - if (ItemStack.isSameItem(itemHandler.getStackInSlot(0), stack)) { - itemHandler.setStackInSlot(0, stack); + if (ItemStack.isSameItem(itemHandler.getStackInSlot(0), this.stack)) { + itemHandler.setStackInSlot(0, this.stack); } } } - private static class ClientCallWrapper { - - private static Level getClientLevel() { - return Minecraft.getInstance().level; - } - } - @Override public @NotNull Type type() { return TYPE; diff --git a/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketImageResponse.java b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketImageResponse.java index 29990bafc68..203490666e8 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketImageResponse.java +++ b/src/main/java/com/gregtechceu/gtceu/common/network/packets/SPacketImageResponse.java @@ -4,12 +4,15 @@ import com.gregtechceu.gtceu.client.util.ClientImageCache; import com.gregtechceu.gtceu.utils.GTMath; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.network.handling.IPayloadContext; +import io.netty.buffer.ByteBuf; +import lombok.AccessLevel; +import lombok.Getter; import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.NotNull; @@ -17,16 +20,24 @@ public class SPacketImageResponse implements CustomPacketPayload { - public static final ResourceLocation ID = GTCEu.id("packet_image_response"); - public static final Type TYPE = new Type<>(ID); - public static final StreamCodec CODEC = StreamCodec - .ofMember(SPacketImageResponse::encode, SPacketImageResponse::new); + public static final ResourceLocation ID = GTCEu.id("image_response"); + public static final CustomPacketPayload.Type TYPE = new CustomPacketPayload.Type<>(ID); + public static final StreamCodec CODEC = StreamCodec.composite( + ByteBufCodecs.STRING_UTF8, SPacketImageResponse::getUrl, + ByteBufCodecs.BYTE_ARRAY, SPacketImageResponse::getImagePart, + ByteBufCodecs.VAR_INT, SPacketImageResponse::getIndex, + ByteBufCodecs.VAR_INT, SPacketImageResponse::getTotalSize, + SPacketImageResponse::new); private static final int MAX_BYTES_PER_PACKET = 120000; - private final byte[] imagePart; + @Getter(AccessLevel.PRIVATE) private final String url; + @Getter(AccessLevel.PRIVATE) + private final byte[] imagePart; + @Getter(AccessLevel.PRIVATE) private final int index; + @Getter(AccessLevel.PRIVATE) private final int totalSize; public SPacketImageResponse(String url, byte[] imagePart, int index, int totalSize) { @@ -36,26 +47,12 @@ public SPacketImageResponse(String url, byte[] imagePart, int index, int totalSi this.totalSize = totalSize; } - public SPacketImageResponse(FriendlyByteBuf buf) { - this.index = buf.readInt(); - this.totalSize = buf.readInt(); - this.url = buf.readUtf(); - this.imagePart = buf.readByteArray(); - } - - public void encode(FriendlyByteBuf buffer) { - buffer.writeInt(index); - buffer.writeInt(totalSize); - buffer.writeUtf(url); - buffer.writeByteArray(imagePart); - } - public void execute(IPayloadContext context) { - if (imagePart == null) { + if (this.imagePart == null) { return; } try { - ClientImageCache.receiveImagePart(url, imagePart, index, totalSize); + ClientImageCache.receiveImagePart(this.url, this.imagePart, this.index, this.totalSize); } catch (IOException ignored) {} } diff --git a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java index 5b46cbc0b44..cf96bb5f84f 100644 --- a/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java +++ b/src/main/java/com/gregtechceu/gtceu/config/ConfigHolder.java @@ -2,12 +2,15 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTCEuAPI; +import com.gregtechceu.gtceu.api.GTValues; import net.minecraft.commands.Commands; +import net.minecraft.resources.ResourceLocation; import dev.toma.configuration.Configuration; import dev.toma.configuration.config.Config; import dev.toma.configuration.config.Configurable; +import dev.toma.configuration.config.UpdateRestrictions; import dev.toma.configuration.config.format.ConfigFormats; import org.jetbrains.annotations.ApiStatus; @@ -54,115 +57,150 @@ public static class RecipeConfigs { @Configurable @Configurable.Comment({ "Whether to generate Flawed and Chipped Gems for materials and recipes involving them.", "Useful for mods like TerraFirmaCraft.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean generateLowQualityGems = false; // default false @Configurable @Configurable.Comment({ "Whether to remove Block/Ingot compression and decompression in the Crafting Table.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean disableManualCompression = true; // default true @Configurable @Configurable.Comment({ "Change the recipe of Rods in the Lathe to 1 Rod and 2 Small Piles of Dust, instead of 2 Rods.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean harderRods = true; // default true @Configurable @Configurable.Comment({ "Whether to make crafting recipes for Bricks, Firebricks, Nether Bricks, and Coke Bricks harder.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean harderBrickRecipes = false; // default false @Configurable @Configurable.Comment({ "Whether to nerf Wood crafting to 2 Planks from 1 Log, and 2 Sticks from 2 Planks.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean nerfWoodCrafting = false; // default false @Configurable @Configurable.Comment({ "Whether to make Wood related recipes harder.", "Excludes sticks and planks.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardWoodRecipes = false; // default false @Configurable @Configurable.Comment({ "Recipes for Buckets, Cauldrons, Hoppers, and Iron Bars" + " require Iron Plates, Rods, and more.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardIronRecipes = true; // default true @Configurable @Configurable.Comment({ "Whether to make Redstone related recipes harder.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardRedstoneRecipes = false; // default false @Configurable @Configurable.Comment({ "Whether to make Vanilla Tools and Armor recipes harder.", "Excludes Flint and Steel, and Buckets.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardToolArmorRecipes = false; // default false @Configurable @Configurable.Comment({ "Whether to make miscellaneous recipes harder.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardMiscRecipes = false; // default false @Configurable @Configurable.Comment({ "Whether to make Glass related recipes harder. Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardGlassRecipes = true; // default true @Configurable @Configurable.Comment({ "Whether to nerf the Paper crafting recipe.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean nerfPaperCrafting = true; // default true @Configurable @Configurable.Comment({ "Recipes for items like Iron Doors, Trapdoors, Anvil" + " require Iron Plates, Rods, and more.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardAdvancedIronRecipes = true; // default true @Configurable @Configurable.Comment({ "Whether to make coloring blocks like Concrete or Glass harder.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardDyeRecipes = false; // default false @Configurable @Configurable.Comment({ "Whether to remove charcoal smelting recipes from the vanilla furnace.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean harderCharcoalRecipe = true; // default true @Configurable @Configurable.Comment({ "Whether to make the Flint and Steel recipe require steel parts.", "Default: true." }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean flintAndSteelRequireSteel = true; // default true @Configurable @Configurable.Comment({ "Whether to remove Vanilla Block Recipes from the Crafting Table.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean removeVanillaBlockRecipes = false; // default false @Configurable @Configurable.Comment({ "Whether to remove Vanilla TNT Recipe from the Crafting Table.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean removeVanillaTNTRecipe = true; // default true @Configurable @Configurable.Comment({ "How many Multiblock Casings to make per craft. Either 1, 2, or 3.", "Default: 2" }) @Configurable.Range(min = 1, max = 3) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public int casingsPerCraft = 2; @Configurable @Configurable.Comment({ "Whether to nerf the output amounts of the first circuit in a set to 1 (from 2) and SoC to 2 (from 4).", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean harderCircuitRecipes = false; @Configurable @Configurable.Comment({ "Whether to nerf machine controller recipes.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean hardMultiRecipes = false; // default false @Configurable @Configurable.Comment({ "Whether tools should have enchants or not. Like the flint sword getting fire aspect.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean enchantedTools = false; @Configurable @Configurable.Comment({ "Whether to enable macerator decomposition recycling", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean enableMaceratorRecycling = true; @Configurable @Configurable.Comment({ "Percentage yield of macerator decomposition recycling outputs, 1.0 means 100%", "Default: 1.0f" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) @Configurable.DecimalRange(min = 0.0f, max = 1.0f) public float maceratorRecyclingYield = 1.0f; @Configurable @Configurable.Comment({ "Whether to enable arc furnace decomposition recycling", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean enableArcRecycling = true; @Configurable @Configurable.Comment({ "Percentage yield of arc furnace decomposition recycling outputs, 1.0 means 100%", "Default: 1.0f" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) @Configurable.DecimalRange(min = 0.0f, max = 1.0f) public float arcRecyclingYield = 1.0f; @Configurable @Configurable.Comment({ "Whether to enable extractor decomposition recycling", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean enableExtractorRecycling = true; @Configurable @Configurable.Comment({ "Percentage yield of extractor decomposition recycling outputs, 1.0 means 100%", "Default: 1.0f" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) @Configurable.DecimalRange(min = 0.0f, max = 1.0f) public float extractorRecyclingYield = 1.0f; } public static class CompatibilityConfigs { + @Configurable + @Configurable.Comment({ "Whether to run datafixers on world load.", + "Do note that mods like ModernFix will interfere with this.", + "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) + public boolean doDatafixers = true; + @Configurable @Configurable.Comment("Config options regarding GTEU compatibility with other energy systems") public EnergyCompatConfig energy = new EnergyCompatConfig(); @@ -203,6 +241,7 @@ public static class CompatibilityConfigs { @Configurable @Configurable.Comment({ "Whether Create compatibility will be available.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean createCompat = true; public static class EnergyCompatConfig { @@ -214,18 +253,19 @@ public static class EnergyCompatConfig { @Configurable @Configurable.Comment({ "Enable GTEU to FE (and vice versa) Converters.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean enableFEConverters = false; @Configurable @Configurable.Comment({ "Forge Energy to GTEU ratio for converting FE to EU.", "Only affects converters.", "Default: 4 FE == 1 EU" }) - @Configurable.Range(min = 1, max = Integer.MAX_VALUE) + @Configurable.Range(min = 1, max = 16) public int feToEuRatio = 4; @Configurable @Configurable.Comment({ "GTEU to Forge Energy ratio for converting EU to FE.", "Affects native conversion and Converters.", "Default: 4 FE == 1 EU" }) - @Configurable.Range(min = 1, max = Integer.MAX_VALUE) + @Configurable.Range(min = 1, max = 16) public int euToFeRatio = 4; } @@ -240,6 +280,7 @@ public static class AE2CompatConfig { @Configurable @Configurable.Comment({ "The energy consumption of ME Hatch/Bus.", "Default: 4.0AE/t" }) @Configurable.DecimalRange(min = 0.0, max = Integer.MAX_VALUE) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public double meHatchEnergyUsage = 4.0; } @@ -247,18 +288,19 @@ public static class MinimapCompatConfig { @Configurable @Configurable.Comment({ - "Toggle specific map mod integration on/off (need to restart for this to take effect)" }) + "Toggle specific map mod integration on/off" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public Toggle toggle = new Toggle(); @Configurable @Configurable.Comment({ "The radius, in blocks, that picking up a surface rock will search for veins in.", "-1 to disable.", "Default: 24" }) - @Configurable.Range(min = -1) + @Configurable.Range(min = 1) public int surfaceRockProspectRange = 24; @Configurable @Configurable.Comment({ "The radius, in blocks, that clicking an ore block will search for veins in.", "-1 to disable", "Default: 24" }) - @Configurable.Range(min = -1) + @Configurable.Range(min = 1) public int oreBlockProspectRange = 24; @Configurable @@ -301,14 +343,17 @@ public static class Toggle { @Configurable @Configurable.Comment({ "FTB Chunks integration enabled" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean ftbChunksIntegration = false; @Configurable @Configurable.Comment({ "Journey Map integration enabled" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean journeyMapIntegration = true; @Configurable @Configurable.Comment({ "Xaerox's map integration enabled" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean xaerosMapIntegration = true; } @@ -375,10 +420,12 @@ public static class WorldGenConfigs { @Configurable.Comment({ "Whether to increase number of rolls for dungeon chests. Increases dungeon loot drastically.", "Default: true", "WARNING: Currently unimplemented." }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean increaseDungeonLoot = true; @Configurable @Configurable.Comment({ "Allow GregTech to add additional GregTech Items as loot in various structures.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean addLoot = true; @Configurable @@ -403,9 +450,11 @@ public static class OreVeinConfigs { @Configurable @Configurable.Comment({ "Prevents regular vanilla ores from being generated outside GregTech ore veins", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean removeVanillaOreGen = true; @Configurable @Configurable.Comment({ "Prevents vanilla's large ore veins from being generated", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean removeVanillaLargeOreVeins = true; @Configurable @Configurable.Comment({ "Distance between bedrock ore veins in chunks, if enabled.", "Default: 16" }) @@ -421,15 +470,17 @@ public static class OreVeinConfigs { "Sets the maximum number of chunks that may be cached for ore vein generation.", "Higher values may improve world generation performance, but at the cost of more RAM usage.", "If you substantially increase the ore vein grid size, random vein offset, or have very large (custom) veins, you may need to increase this value as well.", - "Default: 512 (requires restarting the server / re-opening the world)" + "Default: 512" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public int oreGenerationChunkCacheSize = 512; @Configurable @Configurable.Comment({ "Sets the maximum number of chunks for which ore indicators may be cached.", "If you register any custom veins with very large indicator ranges (or modify existing ones that way), you may need to increase this value.", - "Default: 2048 (requires restarting the server / re-opening the world)" + "Default: 2048" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public int oreIndicatorChunkCacheSize = 2048; } } @@ -440,28 +491,34 @@ public static class MachineConfigs { @Configurable.Comment({ "Whether to require a Wrench, Wirecutter, or other GregTech tools to break machines, casings, wires, and more.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean requireGTToolsForBlocks = true; @Configurable @Configurable.Comment({ "Whether machines explode in rainy weather or when placed next to certain terrain, such as fire or lava", "Default: false" }) + @Configurable.Synchronized public boolean shouldWeatherOrTerrainExplosion = false; @Configurable @Configurable.Comment({ "Energy use multiplier for electric items.", "Default: 100" }) + @Configurable.Synchronized public int energyUsageMultiplier = 100; @Configurable @Configurable.Comment({ "Energy use multiplier for prospectors.", "Default: 100" }) + @Configurable.Synchronized public int prospectorEnergyUseMultiplier = 100; @Configurable @Configurable.Comment({ "Whether machines or boilers damage the terrain when they explode.", "Note machines and boilers always explode when overloaded with power or met with special conditions, regardless of this config.", "Default: true" }) + @Configurable.Synchronized public boolean doesExplosionDamagesTerrain = true; @Configurable @Configurable.Comment({ "Enables Safe Active Transformers, removing their ability to explode if unformed while transmitting/receiving power.", "Default: false" }) + @Configurable.Synchronized public boolean harmlessActiveTransformers = false; @Configurable @Configurable.Comment({ "Whether to play machine sounds while machines are active.", "Default: true" }) @@ -471,9 +528,11 @@ public static class MachineConfigs { public int batchDuration = 100; @Configurable @Configurable.Comment({ "Whether Steam Multiblocks should use Steel instead of Bronze.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean steelSteamMultiblocks = false; @Configurable @Configurable.Comment({ "Whether to enable the cleanroom, required for various recipes.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean enableCleanroom = true; @Configurable @Configurable.Comment({ "Whether multiblocks should ignore all cleanroom requirements.", @@ -490,9 +549,11 @@ public static class MachineConfigs { public String replaceMinedBlocksWith = "minecraft:cobblestone"; @Configurable @Configurable.Comment({ "Whether to enable Assembly Line research for recipes.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean enableResearch = true; @Configurable @Configurable.Comment({ "Whether to enable the Maintenance Hatch, required for Multiblocks.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean enableMaintenance = true; @Configurable @Configurable.Comment({ @@ -505,27 +566,32 @@ public static class MachineConfigs { @Configurable.Comment({ "Whether to enable World Accelerators, which accelerate ticks for surrounding Tile Entities, Crops, etc.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean enableWorldAccelerators = true; @Configurable - @Configurable.Comment({ "List of TileEntities that the World Accelerator should not accelerate.", + @Configurable.Comment({ "List of Block entities that the World Accelerator should not accelerate.", "GregTech TileEntities are always blocked.", - "Entries must be in a fully qualified format. For example: appeng.tile.networking.TileController", + "Entries must be in a fully qualified format. For example: ae2:controller", "Default: none" }) - public String[] worldAcceleratorBlacklist = new String[0]; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public ResourceLocation[] worldAcceleratorBlacklist = new ResourceLocation[0]; @Configurable @Configurable.Comment({ "Whether to use GT6-style pipe and cable connections, meaning they will not auto-connect " + "unless placed directly onto another pipe or cable.", "Default: true" }) + @Configurable.Synchronized public boolean gt6StylePipesCables = true; @Configurable @Configurable.Comment({ "Whether the machine's circuit slot need to be inserted a real circuit." }) + @Configurable.Synchronized public boolean ghostCircuit = true; @Configurable @Configurable.Comment({ "Whether to add a \"Bedrock Ore Miner\" (also enables bedrock ore generation)", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean doBedrockOres = false; @Configurable @Configurable.Comment({ "What Kind of material should the bedrock ore miner output?", "Default: \"raw\"" }) @@ -538,24 +604,30 @@ public static class MachineConfigs { @Configurable @Configurable.Comment({ "Makes nearly every GCYM Multiblock require blocks which set their maximum voltages.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) // todo: implement or purge public boolean enableTieredCasings = false; @Configurable @Configurable.Comment({ "Minimum distance between Long Distance Item Pipe Endpoints", "Default: 50" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public int ldItemPipeMinDistance = 50; @Configurable @Configurable.Comment({ "Minimum distance betweeb Long Distance Fluid Pipe Endpoints", "Default: 50" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public int ldFluidPipeMinDistance = 50; @Configurable @Configurable.Comment({ "Whether ONLY owners can open a machine gui", "Default: false" }) + @Configurable.Synchronized public boolean onlyOwnerGUI = false; @Configurable @Configurable.Comment({ "Whether ONLY owners can break a machine", "Default: false" }) + @Configurable.Synchronized public boolean onlyOwnerBreak = false; @Configurable @Configurable.Comment({ "Minimum op level to bypass the ownership checks", "Default: 2" }) @Configurable.Range(min = Commands.LEVEL_ALL, max = Commands.LEVEL_OWNERS) + @Configurable.Synchronized public int ownerOPBypass = Commands.LEVEL_GAMEMASTERS; /** @@ -568,6 +640,7 @@ public static class MachineConfigs { "This is intended for modpack developers only, and is not playable without custom tweaks or addons.", "Other mods can override this to true, regardless of the config file.", "Default: false" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public boolean highTierContent = false; @Configurable @@ -584,6 +657,7 @@ public static class MachineConfigs { "Default maximum parallel of steam multiblocks", "Default: 8" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public int steamMultiParallelAmount = 8; @Configurable @@ -592,9 +666,11 @@ public static class MachineConfigs { @Configurable @Configurable.Comment("Small Steam Boiler Options") + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public SmallBoilers smallBoilers = new SmallBoilers(); @Configurable @Configurable.Comment("Large Steam Boiler Options") + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public LargeBoilers largeBoilers = new LargeBoilers(); public static class SmallBoilers { @@ -680,41 +756,50 @@ public static class ToolConfigs { @Configurable @Configurable.Comment("NightVision Goggles Voltage Tier. Default: 1 (LV)") @Configurable.Range(min = 0, max = 14) - public int voltageTierNightVision = 1; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public int voltageTierNightVision = GTValues.LV; @Configurable @Configurable.Comment("NanoSuit Voltage Tier. Default: 3 (HV)") @Configurable.Range(min = 0, max = 14) - public int voltageTierNanoSuit = 3; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public int voltageTierNanoSuit = GTValues.HV; @Configurable @Configurable.Comment({ "Advanced NanoSuit Chestplate Voltage Tier.", "Default: 3 (HV)" }) @Configurable.Range(min = 0, max = 14) - public int voltageTierAdvNanoSuit = 3; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public int voltageTierAdvNanoSuit = GTValues.HV; @Configurable @Configurable.Comment({ "QuarkTech Suit Voltage Tier.", "Default: 5 (IV)" }) @Configurable.Range(min = 0, max = 14) - public int voltageTierQuarkTech = 5; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public int voltageTierQuarkTech = GTValues.IV; @Configurable @Configurable.Comment({ "Advanced QuarkTech Suit Chestplate Voltage Tier.", "Default: 6 (LuV)" }) @Configurable.Range(min = 0, max = 14) - public int voltageTierAdvQuarkTech = 6; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public int voltageTierAdvQuarkTech = GTValues.LuV; @Configurable @Configurable.Comment({ "Electric Impeller Jetpack Voltage Tier.", "Default: 2 (MV)" }) @Configurable.Range(min = 0, max = 14) - public int voltageTierImpeller = 2; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public int voltageTierImpeller = GTValues.MV; @Configurable @Configurable.Comment({ "Advanced Electric Jetpack Voltage Tier.", "Default: 3 (HV)" }) @Configurable.Range(min = 0, max = 14) - public int voltageTierAdvImpeller = 3; + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) + public int voltageTierAdvImpeller = GTValues.HV; public static class NanoSaber { @Configurable @Configurable.DecimalRange(min = 0, max = 100) @Configurable.Comment({ "The additional damage added when the NanoSaber is powered.", "Default: 20.0" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public double nanoSaberDamageBoost = 20; @Configurable @Configurable.DecimalRange(min = 0, max = 100) @Configurable.Comment({ "The base damage of the NanoSaber.", "Default: 5.0" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public double nanoSaberBaseDamage = 5; @Configurable @Configurable.Comment({ "Should Zombies spawn with charged, active NanoSabers on hard difficulty?", @@ -723,6 +808,7 @@ public static class NanoSaber { @Configurable @Configurable.Range(min = 1, max = 512) @Configurable.Comment({ "The EU/t consumption of the NanoSaber.", "Default: 64" }) + @Configurable.UpdateRestriction(UpdateRestrictions.GAME_RESTART) public int energyConsumption = 64; } } @@ -731,14 +817,17 @@ public static class GameplayConfigs { @Configurable @Configurable.Comment({ "Enable hazardous materials", "Default: true" }) + @Configurable.Synchronized public boolean hazardsEnabled = true; @Configurable @Configurable.Comment({ "Whether hazards are applied to all valid items, or just GT's.", "true = all, false = GT only.", "Default: true" }) + @Configurable.Synchronized public boolean universalHazards = true; @Configurable @Configurable.Comment({ "Whether environmental hazards like pollution or radiation are active", "Default: false" }) + @Configurable.Synchronized public boolean environmentalHazards = false; @Configurable @Configurable.Comment({ "How much environmental hazards decay per chunk, per tick.", @@ -746,6 +835,7 @@ public static class GameplayConfigs { public float environmentalHazardDecayRate = 0.001f; @Configurable @Configurable.Comment({ "List of domains that are allowed in the image module" }) + @Configurable.Synchronized public String[] allowedImageDomains = new String[] { "imgur.com", "discord.com", "github.com", "raw.githubusercontent.com" }; } @@ -787,6 +877,7 @@ public static class ClientConfigs { @Configurable @Configurable.Comment({ "Use VBO cache for multiblock preview.", "Disable if you have issues with rendering multiblocks.", "Default: true" }) + @Configurable.UpdateRestriction(UpdateRestrictions.MAIN_MENU) public boolean useVBO = true; @Configurable @Configurable.Comment({ "Duration of the multiblock in-world preview (s)", "Default: 10" }) diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/ChunkSerializerDataFixMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/ChunkSerializerDataFixMixin.java new file mode 100644 index 00000000000..0b703c913a7 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/ChunkSerializerDataFixMixin.java @@ -0,0 +1,23 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.chunk.storage.ChunkSerializer; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +@Mixin(ChunkSerializer.class) +public abstract class ChunkSerializerDataFixMixin { + + @ModifyVariable( + method = "write", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/nbt/CompoundTag;putInt(Ljava/lang/String;I)V", + ordinal = 0)) + private static CompoundTag gtceu$addModDataVersions(CompoundTag compound) { + return DataFixesInternals.get().addModDataVersions(compound); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/DataFixTypesDataFixMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/DataFixTypesDataFixMixin.java new file mode 100644 index 00000000000..4cb6e73d62e --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/DataFixTypesDataFixMixin.java @@ -0,0 +1,28 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.util.datafix.DataFixTypes; + +import com.llamalad7.mixinextras.injector.ModifyReturnValue; +import com.mojang.datafixers.DSL; +import com.mojang.serialization.Dynamic; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(DataFixTypes.class) +public class DataFixTypesDataFixMixin { + + @Shadow + @Final + private DSL.TypeReference type; + + // ModifyReturnValue to inject our fixes *after* vanilla ones + @ModifyReturnValue(method = "update(Lcom/mojang/datafixers/DataFixer;Lcom/mojang/serialization/Dynamic;II)Lcom/mojang/serialization/Dynamic;", + at = @At(value = "RETURN")) + private Dynamic gtceu$injectDataFixers(Dynamic value) { + return DataFixesInternals.get().updateWithAllFixers(this.type, value); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/EntityAccessor.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/EntityAccessor.java new file mode 100644 index 00000000000..622fbdaa21d --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/EntityAccessor.java @@ -0,0 +1,13 @@ +package com.gregtechceu.gtceu.core.mixins; + +import net.minecraft.world.entity.Entity; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(Entity.class) +public interface EntityAccessor { + + @Invoker("getPermissionLevel") + int gtceu$getPermissionLevel(); +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/IOWorkerDataFixMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/IOWorkerDataFixMixin.java new file mode 100644 index 00000000000..6a1b11235d5 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/IOWorkerDataFixMixin.java @@ -0,0 +1,26 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.storage.IOWorker; + +import org.jetbrains.annotations.Nullable; +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.CallbackInfoReturnable; + +import java.util.concurrent.CompletableFuture; + +@Mixin(IOWorker.class) +public class IOWorkerDataFixMixin { + + @Inject(method = "store", at = @At("HEAD")) + private void gtceu$addModDataVersions(ChunkPos chunkPos, @Nullable CompoundTag chunkData, + CallbackInfoReturnable> cir) { + if (chunkData != null) + DataFixesInternals.get().addModDataVersions(chunkData); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/StructureTemplateDataFixMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/StructureTemplateDataFixMixin.java new file mode 100644 index 00000000000..0ac242eae85 --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/StructureTemplateDataFixMixin.java @@ -0,0 +1,22 @@ +package com.gregtechceu.gtceu.core.mixins; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; + +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.CallbackInfoReturnable; + +@Mixin(StructureTemplate.class) +public abstract class StructureTemplateDataFixMixin { + + @Inject(method = "save", at = @At("TAIL"), cancellable = true) + private void addModDataVersions(CompoundTag compound, CallbackInfoReturnable cir) { + CompoundTag out = cir.getReturnValue(); + DataFixesInternals.get().addModDataVersions(out); + cir.setReturnValue(out); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/client/HotbarManagerDataFixMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/client/HotbarManagerDataFixMixin.java new file mode 100644 index 00000000000..86c0170a07a --- /dev/null +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/client/HotbarManagerDataFixMixin.java @@ -0,0 +1,40 @@ +/* + * Copyright 2022 QuiltMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gregtechceu.gtceu.core.mixins.client; + +import com.gregtechceu.gtceu.api.datafixer.DataFixesInternals; + +import net.minecraft.client.HotbarManager; +import net.minecraft.nbt.CompoundTag; + +import com.llamalad7.mixinextras.sugar.Local; +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; + +@Mixin(HotbarManager.class) +public abstract class HotbarManagerDataFixMixin { + + @Inject( + method = "save", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/nbt/NbtIo;write(Lnet/minecraft/nbt/CompoundTag;Ljava/nio/file/Path;)V", + shift = At.Shift.AFTER)) + private void gtceu$addModDataVersions(CallbackInfo ci, @Local CompoundTag tag) { + DataFixesInternals.get().addModDataVersions(tag); + } +} diff --git a/src/main/java/com/gregtechceu/gtceu/core/mixins/client/ModelManagerMixin.java b/src/main/java/com/gregtechceu/gtceu/core/mixins/client/ModelManagerMixin.java index 5ce2c2fa834..b116f6100e4 100644 --- a/src/main/java/com/gregtechceu/gtceu/core/mixins/client/ModelManagerMixin.java +++ b/src/main/java/com/gregtechceu/gtceu/core/mixins/client/ModelManagerMixin.java @@ -1,7 +1,7 @@ package com.gregtechceu.gtceu.core.mixins.client; import com.gregtechceu.gtceu.GTCEu; -import com.gregtechceu.gtceu.data.pack.event.RegisterDynamicResourcesEvent; +import com.gregtechceu.gtceu.api.data.pack.event.RegisterDynamicResourcesEvent; import com.gregtechceu.gtceu.integration.modernfix.GTModernFixIntegration; import net.minecraft.client.resources.model.ModelManager; diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/ConfigurationLang.java b/src/main/java/com/gregtechceu/gtceu/data/lang/ConfigurationLang.java index 6c355cf0c83..de63da5fa7d 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/ConfigurationLang.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/ConfigurationLang.java @@ -1,30 +1,33 @@ package com.gregtechceu.gtceu.data.lang; -import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.config.ConfigHolder; import com.tterrag.registrate.providers.RegistrateLangProvider; -import dev.toma.configuration.config.value.ConfigValue; -import dev.toma.configuration.config.value.ObjectValue; +import dev.toma.configuration.config.value.IConfigValue; +import dev.toma.configuration.config.value.IHierarchical; import java.util.HashSet; -import java.util.Map; import java.util.Set; public class ConfigurationLang { - public static void init(RegistrateLangProvider provider) { - dfs(provider, new HashSet<>(), ConfigHolder.INTERNAL_INSTANCE.getValueMap()); + public static void init(final RegistrateLangProvider provider) { + final Set added = new HashSet<>(); + ConfigHolder.INTERNAL_INSTANCE.values() + .forEach((value) -> addTranslation(provider, added, value)); } - private static void dfs(RegistrateLangProvider provider, Set added, Map> map) { - for (var entry : map.entrySet()) { - var id = entry.getValue().getId(); - if (added.add(id)) { - provider.add(String.format("config.%s.option.%s", GTCEu.MOD_ID, id), id); - } - if (entry.getValue() instanceof ObjectValue objectValue) { - dfs(provider, added, objectValue.get()); + private static void addTranslation(RegistrateLangProvider provider, Set added, IConfigValue value) { + var id = value.getId(); + if (added.add(id)) { + provider.add("config.gtceu.option." + id, id); + } + if (value instanceof IHierarchical hierarchical) { + for (String childKey : value.getChildrenKeys()) { + IConfigValue child = hierarchical.getChildById(childKey); + if (child != null) { + addTranslation(provider, added, child); + } } } } diff --git a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java index 3ad832031b8..3bb539dbc3a 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java +++ b/src/main/java/com/gregtechceu/gtceu/data/lang/LangHandler.java @@ -546,9 +546,9 @@ public static void init(RegistrateLangProvider provider) { provider.add("item.gtceu.bucket", "%s Bucket"); replace(provider, GTMaterials.FullersEarth.getUnlocalizedName(), "Fuller's Earth"); - replace(provider, GTMaterials.Cooperite.getUnlocalizedName(), "Sheldonite"); // greg's humor is now on - // 1.19... - replace(provider, GTMaterials.YellowLimonite.getUnlocalizedName(), "Yellow Limonite"); + // greg's humor is now on 1.21... + replace(provider, GTMaterials.Cooperite.getUnlocalizedName(), "Sheldonite"); + replace(provider, GTMaterials.HSSG.getUnlocalizedName(), "HSS-G"); replace(provider, GTMaterials.HSSE.getUnlocalizedName(), "HSS-E"); replace(provider, GTMaterials.HSSS.getUnlocalizedName(), "HSS-S"); diff --git a/src/main/java/com/gregtechceu/gtceu/common/data/GTPlaceholders.java b/src/main/java/com/gregtechceu/gtceu/data/placeholder/GTPlaceholders.java similarity index 95% rename from src/main/java/com/gregtechceu/gtceu/common/data/GTPlaceholders.java rename to src/main/java/com/gregtechceu/gtceu/data/placeholder/GTPlaceholders.java index 826ea873f7a..0cd535968b6 100644 --- a/src/main/java/com/gregtechceu/gtceu/common/data/GTPlaceholders.java +++ b/src/main/java/com/gregtechceu/gtceu/data/placeholder/GTPlaceholders.java @@ -22,10 +22,10 @@ import com.gregtechceu.gtceu.client.renderer.placeholder.RectPlaceholderRenderer; import com.gregtechceu.gtceu.common.blockentity.CableBlockEntity; import com.gregtechceu.gtceu.common.data.item.GTDataComponents; +import com.gregtechceu.gtceu.common.item.behavior.modules.ImageModuleBehaviour; import com.gregtechceu.gtceu.common.item.datacomponents.BindingData; import com.gregtechceu.gtceu.common.item.datacomponents.DataItem; import com.gregtechceu.gtceu.common.item.datacomponents.FormatStringList; -import com.gregtechceu.gtceu.common.item.modules.ImageModuleBehaviour; import com.gregtechceu.gtceu.common.machine.multiblock.part.monitor.AdvancedMonitorPartMachine; import com.gregtechceu.gtceu.config.ConfigHolder; import com.gregtechceu.gtceu.integration.ae2.GTAEPlaceholders; @@ -164,12 +164,13 @@ public MultiLineComponent apply(PlaceholderContext ctx, } if (GTStringUtils.equals(args.getFirst(), "filter")) { int slot = PlaceholderUtils.toInt(args.get(1)); - if (ctx.itemStackHandler() == null) + if (ctx.itemHandler() == null) { throw new NotSupportedException(); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); + } + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); try { return MultiLineComponent.literal(countItems( - ItemFilter.loadFilter(ctx.itemStackHandler().getStackInSlot(slot - 1)), itemHandler)); + ItemFilter.loadFilter(ctx.itemHandler().getStackInSlot(slot - 1)), itemHandler)); } catch (NullPointerException e) { throw new MissingItemException("filter", slot); } @@ -198,11 +199,13 @@ public MultiLineComponent apply(PlaceholderContext ctx, List args) throws PlaceholderException { PlaceholderUtils.checkArgs(args, 2, true); try { - if (GTStringUtils.toDouble(args.get(0)) != 0) { + if (GTStringUtils.toDouble(args.getFirst()) != 0) { return new MultiLineComponent(args.get(1)).setIgnoreSpaces(true); } else if (args.size() > 2) { return new MultiLineComponent(args.get(2)).setIgnoreSpaces(true); - } else return MultiLineComponent.empty(); + } else { + return MultiLineComponent.empty(); + } } catch (NumberFormatException e) { return args.get(1); } @@ -429,9 +432,10 @@ public MultiLineComponent apply(PlaceholderContext ctx, PlaceholderUtils.checkArgs(args, 2, true); try { int slot = PlaceholderUtils.toInt(args.get(1)); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); - ItemStack stack = ctx.itemStackHandler().getStackInSlot(slot - 1); + if (ctx.itemHandler() == null) throw new NotSupportedException(); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + + ItemStack stack = ctx.itemHandler().getStackInSlot(slot - 1); DataItem component = stack.get(GTDataComponents.DATA_ITEM); if (component == null) { throw new MissingItemException("any data item", slot); @@ -495,11 +499,13 @@ public MultiLineComponent apply(PlaceholderContext ctx, List public MultiLineComponent apply(PlaceholderContext ctx, List args) throws PlaceholderException { PlaceholderUtils.checkArgs(args, 1, true); + if (ctx.itemHandler() == null) throw new NotSupportedException(); + int slot = GTStringUtils.toInt(args.getFirst()); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + return MultiLineComponent - .literal(ctx.itemStackHandler().getStackInSlot(slot - 1).getComponents().toString()); + .literal(ctx.itemHandler().getStackInSlot(slot - 1).getComponents().toString()); } }); PlaceholderHandler.addPlaceholder(new Placeholder("toChars") { @@ -580,9 +586,9 @@ public MultiLineComponent apply(PlaceholderContext ctx, PlaceholderUtils.checkArgs(args, 2); int slot = PlaceholderUtils.toInt(args.getFirst()); PlaceholderUtils.checkRange("slot index", 1, 8, slot); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); + if (ctx.itemHandler() == null) throw new NotSupportedException(); - ItemStack stack = ctx.itemStackHandler().getStackInSlot(slot - 1); + ItemStack stack = ctx.itemHandler().getStackInSlot(slot - 1); FormatStringList immutableData = stack.get(GTDataComponents.COMPUTER_MONITOR_DATA); if (immutableData == null) { throw new MissingItemException("any data item", slot); @@ -675,10 +681,10 @@ public MultiLineComponent apply(PlaceholderContext ctx, public MultiLineComponent apply(PlaceholderContext ctx, List args) throws PlaceholderException { PlaceholderUtils.checkArgs(args, 2); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); + if (ctx.itemHandler() == null) throw new NotSupportedException(); int slot = PlaceholderUtils.toInt(args.getFirst()); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); - ItemStack stack = ctx.itemStackHandler().getStackInSlot(slot - 1); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + ItemStack stack = ctx.itemHandler().getStackInSlot(slot - 1); BindingData bindingData = stack.get(GTDataComponents.BINDING_DATA); if (bindingData == null) { @@ -787,10 +793,10 @@ public MultiLineComponent apply(PlaceholderContext ctx, String channel = args.get(1).toString(); UUID owner = null; if (args.size() > 2 && !args.get(2).toString().isEmpty()) { - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); + if (ctx.itemHandler() == null) throw new NotSupportedException(); int slot = PlaceholderUtils.toInt(args.get(2)); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); - ItemStack stack = ctx.itemStackHandler().getStackInSlot(slot - 1); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + ItemStack stack = ctx.itemHandler().getStackInSlot(slot - 1); if (stack.has(GTDataComponents.BINDING_DATA)) { owner = stack.get(GTDataComponents.BINDING_DATA).uuid(); @@ -803,10 +809,10 @@ public MultiLineComponent apply(PlaceholderContext ctx, if (!ender.hasEntry(owner, EntryTypes.ENDER_REDSTONE, channel)) return MultiLineComponent.literal(0); if (args.size() > 4) { - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); + if (ctx.itemHandler() == null) throw new NotSupportedException(); int slot = PlaceholderUtils.toInt(args.get(3)); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); - ItemStack stack = ctx.itemStackHandler().getStackInSlot(slot - 1); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + ItemStack stack = ctx.itemHandler().getStackInSlot(slot - 1); UUID uuid; if (stack.has(GTDataComponents.ENDER_REDSTONE_LINK_TRANSMITTER_UUID)) { uuid = stack.get(GTDataComponents.ENDER_REDSTONE_LINK_TRANSMITTER_UUID); @@ -844,8 +850,8 @@ public MultiLineComponent apply(PlaceholderContext ctx, if (!ender.hasEntry(owner, EntryTypes.ENDER_ITEM, channel)) return MultiLineComponent.empty(); IItemHandler items = ender.getEntry(owner, EntryTypes.ENDER_ITEM, channel).getHandler(); - if (ctx.itemStackHandler() != null) - GTTransferUtils.transferItemsFiltered(items, ctx.itemStackHandler(), stack -> true, 1); + if (ctx.itemHandler() != null) + GTTransferUtils.transferItemsFiltered(items, ctx.itemHandler(), stack -> true, 1); else throw new NotSupportedException(); return MultiLineComponent.empty(); } @@ -854,8 +860,8 @@ public MultiLineComponent apply(PlaceholderContext ctx, if (!ender.hasEntry(owner, EntryTypes.ENDER_ITEM, channel)) return MultiLineComponent.empty(); IItemHandler items = ender.getEntry(owner, EntryTypes.ENDER_ITEM, channel).getHandler(); - if (ctx.itemStackHandler() != null) - GTTransferUtils.transferItemsFiltered(ctx.itemStackHandler(), items, stack -> true, 1); + if (ctx.itemHandler() != null) + GTTransferUtils.transferItemsFiltered(ctx.itemHandler(), items, stack -> true, 1); else throw new NotSupportedException(); return MultiLineComponent.empty(); } @@ -889,9 +895,9 @@ public MultiLineComponent apply(PlaceholderContext ctx, int slot = PlaceholderUtils.toInt(args.get(0)); double x = PlaceholderUtils.toDouble(args.get(1)); double y = PlaceholderUtils.toDouble(args.get(2)); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); - ItemStack stack = ctx.itemStackHandler().getStackInSlot(slot); + if (ctx.itemHandler() == null) throw new NotSupportedException(); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + ItemStack stack = ctx.itemHandler().getStackInSlot(slot); if (stack.getItem() instanceof IComponentItem componentItem) { for (IItemComponent component : componentItem.getComponents()) { if (component instanceof IMonitorModuleItem module) module.tickInPlaceholder(stack, ctx); @@ -911,9 +917,9 @@ public MultiLineComponent apply(PlaceholderContext ctx, PlaceholderUtils.checkArgs(args, 2); int slot = PlaceholderUtils.toInt(args.get(0)); String url = args.get(1).toString(); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); - ItemStack stack = ctx.itemStackHandler().getStackInSlot(slot); + if (ctx.itemHandler() == null) throw new NotSupportedException(); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + ItemStack stack = ctx.itemHandler().getStackInSlot(slot); if (stack.getItem() instanceof IComponentItem componentItem) { for (IItemComponent component : componentItem.getComponents()) { if (component instanceof ImageModuleBehaviour module) { @@ -989,9 +995,9 @@ public MultiLineComponent apply(PlaceholderContext ctx, List args) throws PlaceholderException { PlaceholderUtils.checkArgs(args, 1); int slot = PlaceholderUtils.toInt(args.get(0)); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); - PlaceholderUtils.checkRange("slot index", 1, ctx.itemStackHandler().getSlots(), slot); - return MultiLineComponent.literal(ctx.itemStackHandler().getStackInSlot(slot - 1).toString()); + if (ctx.itemHandler() == null) throw new NotSupportedException(); + PlaceholderUtils.checkRange("slot index", 1, ctx.itemHandler().getSlots(), slot); + return MultiLineComponent.literal(ctx.itemHandler().getStackInSlot(slot - 1).toString()); } }); } diff --git a/src/main/java/com/gregtechceu/gtceu/data/recipe/GTCraftingComponents.java b/src/main/java/com/gregtechceu/gtceu/data/recipe/GTCraftingComponents.java index b5015a7f873..6ded1eb6c7a 100644 --- a/src/main/java/com/gregtechceu/gtceu/data/recipe/GTCraftingComponents.java +++ b/src/main/java/com/gregtechceu/gtceu/data/recipe/GTCraftingComponents.java @@ -2,10 +2,10 @@ import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTCEuAPI; +import com.gregtechceu.gtceu.api.recipe.event.CraftingComponentModificationEvent; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTItems; import com.gregtechceu.gtceu.common.data.GTMachines; -import com.gregtechceu.gtceu.data.recipe.event.CraftingComponentModificationEvent; import com.gregtechceu.gtceu.integration.kjs.GTCEuStartupEvents; import com.gregtechceu.gtceu.integration.kjs.events.CraftingComponentsEventJS; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/ae2/GTAEPlaceholders.java b/src/main/java/com/gregtechceu/gtceu/integration/ae2/GTAEPlaceholders.java index 75784a5a998..4c4569521ad 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/ae2/GTAEPlaceholders.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/ae2/GTAEPlaceholders.java @@ -13,8 +13,10 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Fluids; import net.neoforged.neoforge.fluids.FluidStack; import appeng.api.networking.GridHelper; @@ -65,12 +67,12 @@ private static IGrid getGrid(PlaceholderContext ctx) throws PlaceholderException } private static long countItems(String id, IGrid grid) { - var key = ResourceLocation.parse(id); - if (key == null) return 0; - if (!BuiltInRegistries.ITEM.containsKey(key)) return 0; - Item item = BuiltInRegistries.ITEM.get(key); + Item item = BuiltInRegistries.ITEM.get(ResourceLocation.parse(id)); + if (item == Items.AIR) return 0; + GenericStack stack = GenericStack.fromItemStack(new ItemStack(item, 1)); if (stack == null) return 0; + return grid.getStorageService().getInventory().getAvailableStacks().get(stack.what()); } @@ -90,15 +92,18 @@ private static long countFluids(@Nullable String id, IGrid grid) { KeyCounter stacks = grid.getStorageService().getCachedInventory(); long count = 0; for (var stack : stacks) { - if (stack.getKey() instanceof AEFluidKey) count += stack.getLongValue(); + if (stack.getKey() instanceof AEFluidKey) { + count += stack.getLongValue(); + } } return count; } - var fluidId = ResourceLocation.parse(id); - if (!BuiltInRegistries.FLUID.containsKey(fluidId)) return 0; - Fluid fluid = BuiltInRegistries.FLUID.get(fluidId); + Fluid fluid = BuiltInRegistries.FLUID.get(ResourceLocation.parse(id)); + if (fluid == Fluids.EMPTY) return 0; + GenericStack stack = GenericStack.fromFluidStack(new FluidStack(fluid, 1)); if (stack == null) return 0; + return grid.getStorageService().getInventory().getAvailableStacks().get(stack.what()); } @@ -123,9 +128,9 @@ public MultiLineComponent apply(PlaceholderContext ctx, int slot = PlaceholderUtils.toInt(args.get(1)); try { PlaceholderUtils.checkRange("slot index", 1, 8, slot); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); + if (ctx.itemHandler() == null) throw new NotSupportedException(); return MultiLineComponent.literal(countItems( - ItemFilter.loadFilter(ctx.itemStackHandler().getStackInSlot(slot - 1)), grid)); + ItemFilter.loadFilter(ctx.itemHandler().getStackInSlot(slot - 1)), grid)); } catch (NullPointerException e) { throw new MissingItemException("filter", slot); } @@ -140,8 +145,9 @@ public MultiLineComponent apply(PlaceholderContext ctx, List args) throws PlaceholderException { IGrid grid = getGrid(ctx); if (args.isEmpty()) return MultiLineComponent.literal(countFluids(null, grid)); - if (args.size() == 1) + if (args.size() == 1) { return MultiLineComponent.literal(countFluids(GTStringUtils.componentsToString(args.get(0)), grid)); + } throw new WrongNumberOfArgsException(1, args.size()); } }); @@ -218,7 +224,7 @@ else if (GTStringUtils.equals(args.get(2), "threads")) else if (GTStringUtils.equals(args.get(2), "name")) return MultiLineComponent .of(cpu.getName() == null ? Component.literal("Crafting CPU " + i) : - cpu.getName().copy()); + cpu.getName()); else if (GTStringUtils.equals(args.get(2), "selectionMode")) return MultiLineComponent.literal(cpu.getSelectionMode().name()); else if (job == null) return MultiLineComponent.literal(0); diff --git a/src/main/java/com/gregtechceu/gtceu/integration/cctweaked/peripherals/CentralMonitorPeripheral.java b/src/main/java/com/gregtechceu/gtceu/integration/cctweaked/peripherals/CentralMonitorPeripheral.java index 5b20d658ca3..4182c6aea57 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/cctweaked/peripherals/CentralMonitorPeripheral.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/cctweaked/peripherals/CentralMonitorPeripheral.java @@ -4,8 +4,8 @@ import com.gregtechceu.gtceu.api.item.ComponentItem; import com.gregtechceu.gtceu.api.item.component.IItemComponent; import com.gregtechceu.gtceu.api.item.component.IMonitorModuleItem; -import com.gregtechceu.gtceu.common.item.modules.ImageModuleBehaviour; -import com.gregtechceu.gtceu.common.item.modules.TextModuleBehaviour; +import com.gregtechceu.gtceu.common.item.behavior.modules.ImageModuleBehaviour; +import com.gregtechceu.gtceu.common.item.behavior.modules.TextModuleBehaviour; import com.gregtechceu.gtceu.common.machine.multiblock.electric.monitor.MonitorGroup; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/com/gregtechceu/gtceu/integration/create/GTCreateIntegration.java b/src/main/java/com/gregtechceu/gtceu/integration/create/GTCreateIntegration.java index cddad6d91f3..b70fef9a3d8 100644 --- a/src/main/java/com/gregtechceu/gtceu/integration/create/GTCreateIntegration.java +++ b/src/main/java/com/gregtechceu/gtceu/integration/create/GTCreateIntegration.java @@ -119,9 +119,9 @@ private static MultiLineComponent processRedstonePlaceholder(PlaceholderContext int slot = PlaceholderUtils.toInt(args.get(2)); int freq_slot = PlaceholderUtils.toInt(args.get(3)); PlaceholderUtils.checkRange("slot index", 1, 8, slot); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); + if (ctx.itemHandler() == null) throw new NotSupportedException(); - ItemStack item = ctx.itemStackHandler().getStackInSlot(slot - 1); + ItemStack item = ctx.itemHandler().getStackInSlot(slot - 1); if (item.is(AllItems.LINKED_CONTROLLER.get())) { Couple freq = LinkedControllerItem.toFrequency(item, freq_slot); @@ -144,9 +144,9 @@ private static MultiLineComponent processRedstonePlaceholder(PlaceholderContext int power = PlaceholderUtils.toInt(args.get(4)); PlaceholderUtils.checkRange("redstone power", 0, 15, power); PlaceholderUtils.checkRange("slot", 1, 8, slot); - if (ctx.itemStackHandler() == null) throw new NotSupportedException(); + if (ctx.itemHandler() == null) throw new NotSupportedException(); - ItemStack item = ctx.itemStackHandler().getStackInSlot(slot - 1); + ItemStack item = ctx.itemHandler().getStackInSlot(slot - 1); if (item.is(AllItems.LINKED_CONTROLLER.get())) { Couple freq = LinkedControllerItem.toFrequency(item, freq_slot); diff --git a/src/main/java/com/gregtechceu/gtceu/utils/GTStringUtils.java b/src/main/java/com/gregtechceu/gtceu/utils/GTStringUtils.java index 2c1bdb96b2e..09cf14fa9c8 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/GTStringUtils.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/GTStringUtils.java @@ -3,11 +3,7 @@ import net.minecraft.ChatFormatting; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.ListTag; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.ComponentUtils; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.contents.PlainTextContents; +import net.minecraft.network.chat.*; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.fluids.FluidStack; @@ -183,7 +179,7 @@ public static void append(List components, @Nullable List replacements) } public static Component toComponent(ListTag arr) { - return toComponent(List.of(arr.toArray(new String[0]))); + return toComponent(List.of(arr.toArray(String[]::new))); } public static Component toComponent(List arr) { @@ -212,17 +208,21 @@ public static Component toComponent(List arr) { if (arr.size() <= 5) { for (int i = 0; i < arr.size(); i++) { component.append(Component.literal('"' + arr.get(i) + '"').withStyle(ChatFormatting.DARK_AQUA)); - if (i != arr.size() - 1) component.append(", "); + if (i != arr.size() - 1) { + component.append(ComponentUtils.DEFAULT_NO_STYLE_SEPARATOR); + } } } else { for (int i = 0; i < 2; i++) { component.append(Component.literal('"' + arr.get(i) + '"').withStyle(ChatFormatting.DARK_AQUA)); - component.append(", "); + component.append(ComponentUtils.DEFAULT_NO_STYLE_SEPARATOR); } - component.append("..., "); + component.append(CommonComponents.ELLIPSIS).append(ComponentUtils.DEFAULT_NO_STYLE_SEPARATOR); for (int i = arr.size() - 2; i < arr.size(); i++) { component.append(Component.literal('"' + arr.get(i) + '"').withStyle(ChatFormatting.DARK_AQUA)); - if (i != arr.size() - 1) component.append(", "); + if (i != arr.size() - 1) { + component.append(ComponentUtils.DEFAULT_NO_STYLE_SEPARATOR); + } } } component.append("]"); diff --git a/src/main/java/com/gregtechceu/gtceu/utils/ResearchManager.java b/src/main/java/com/gregtechceu/gtceu/utils/ResearchManager.java index 55d92c3dfb8..2fba303cbc9 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/ResearchManager.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/ResearchManager.java @@ -59,7 +59,7 @@ private ResearchManager() {} public static boolean isStackDataItem(ItemStack stack, boolean isDataBank) { @Nullable DataItem dataItem = stack.get(GTDataComponents.DATA_ITEM); - return dataItem != null && dataItem.requireDataBank() || isDataBank; + return dataItem != null && !dataItem.requireDataBank() || isDataBank; } /** diff --git a/src/main/java/com/gregtechceu/gtceu/utils/input/SyncedKeyMappings.java b/src/main/java/com/gregtechceu/gtceu/utils/input/SyncedKeyMappings.java index 75cfc93df49..c38c1230763 100644 --- a/src/main/java/com/gregtechceu/gtceu/utils/input/SyncedKeyMappings.java +++ b/src/main/java/com/gregtechceu/gtceu/utils/input/SyncedKeyMappings.java @@ -43,7 +43,7 @@ public final class SyncedKeyMappings { InputConstants.KEY_APOSTROPHE); public static void init() { - if (GTCEu.isClientSide()) { + if (GTCEu.isClientSide() && !GTCEu.isDataGen()) { NeoForge.EVENT_BUS.register(SyncedKeyMapping.class); } ModLoader.postEvent(new SyncedKeyMappingEvent()); diff --git a/src/main/resources/META-INF/enum_extensions.json b/src/main/resources/META-INF/enum_extensions.json index ec517e59218..f05c43e0991 100644 --- a/src/main/resources/META-INF/enum_extensions.json +++ b/src/main/resources/META-INF/enum_extensions.json @@ -5,7 +5,7 @@ "name": "GTCEU_RUBBER", "constructor": "(Ljava/util/function/Supplier;Ljava/lang/String;Ljava/util/function/Supplier;Ljava/util/function/Supplier;Ljava/util/function/Supplier;Z)V", "parameters": { - "class": "com/gregtechceu/gtceu/data/inject/GTEnumProxies", + "class": "com/gregtechceu/gtceu/common/data/GTEnumProxies", "field": "RUBBER_BOAT_PROXY" } }, @@ -14,7 +14,7 @@ "name": "GTCEU_TREATED_WOOD", "constructor": "(Ljava/util/function/Supplier;Ljava/lang/String;Ljava/util/function/Supplier;Ljava/util/function/Supplier;Ljava/util/function/Supplier;Z)V", "parameters": { - "class": "com/gregtechceu/gtceu/data/inject/GTEnumProxies", + "class": "com/gregtechceu/gtceu/common/data/GTEnumProxies", "field": "TREATED_WOOD_BOAT_PROXY" } } diff --git a/src/main/resources/gtceu.mixins.json b/src/main/resources/gtceu.mixins.json index 5b4efb8bc20..de34bff6332 100644 --- a/src/main/resources/gtceu.mixins.json +++ b/src/main/resources/gtceu.mixins.json @@ -13,6 +13,7 @@ "client.FaceBakeryMixin", "client.GuiGraphicsAccessor", "client.GuiGraphicsMixin", + "client.HotbarManagerDataFixMixin", "client.ItemEntityMixin", "client.LevelRendererMixin", "client.ModelManagerMixin", @@ -38,11 +39,15 @@ "BlockMixin", "BlockPropertiesAccessor", "ChunkGeneratorMixin", + "ChunkSerializerDataFixMixin", + "DataFixTypesDataFixMixin", + "EntityAccessor", "EntityMixin", "FluidStackAccessor", "GrowingPlantBlockAccessor", "IntegerPropertyAccessor", "InventoryMixin", + "IOWorkerDataFixMixin", "LevelAccessor", "LevelMixin", "LootPoolAccessor", @@ -57,10 +62,12 @@ "ReloadableServerResourcesMixin", "RepairItemRecipeMixin", "ResourceKeyArgumentAccessor", + "ResourceLocationMixin", "ServerChunkProviderMixin", "ServerGamePacketListenerImplAccessor", "ShapedRecipeAccessor", "SidedRedstoneConnectivityMixin", + "StructureTemplateDataFixMixin", "TagLoaderMixin", "TagManagerMixin", "WorldLoaderMixin",